code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/core/config-projector.hh>
#include <hpp/core/bi-rrt-planner.hh>
#include <hpp/core/node.hh>
#include <hpp/core/edge.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-validation.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/roadmap.hh>
#include <hpp/core/steering-method.hh>
#include <hpp/core/configuration-shooter.hh>
namespace hpp {
namespace core {
using pinocchio::displayConfig;
BiRRTPlannerPtr_t BiRRTPlanner::createWithRoadmap
(const ProblemConstPtr_t& problem, const RoadmapPtr_t& roadmap)
{
BiRRTPlanner* ptr = new BiRRTPlanner (problem, roadmap);
return BiRRTPlannerPtr_t (ptr);
}
BiRRTPlannerPtr_t BiRRTPlanner::create (const ProblemConstPtr_t& problem)
{
BiRRTPlanner* ptr = new BiRRTPlanner (problem);
return BiRRTPlannerPtr_t (ptr);
}
BiRRTPlanner::BiRRTPlanner (const ProblemConstPtr_t& problem):
PathPlanner (problem),
configurationShooter_ (problem->configurationShooter()),
qProj_ (problem->robot ()->configSize ())
{
}
BiRRTPlanner::BiRRTPlanner (const ProblemConstPtr_t& problem, const RoadmapPtr_t& roadmap):
PathPlanner (problem, roadmap),
configurationShooter_ (problem->configurationShooter()),
qProj_ (problem->robot ()->configSize ())
{
}
void BiRRTPlanner::init (const BiRRTPlannerWkPtr_t& weak)
{
PathPlanner::init (weak);
weakPtr_ = weak;
}
PathPtr_t BiRRTPlanner::extendInternal (const SteeringMethodPtr_t& sm, Configuration_t& qProj_, const NodePtr_t& near,
const Configuration_t& target, bool reverse)
{
const ConstraintSetPtr_t& constraints (sm->constraints ());
if (constraints)
{
ConfigProjectorPtr_t configProjector (constraints->configProjector ());
if (configProjector)
{
configProjector->projectOnKernel (*(near->configuration ()), target,
qProj_);
}
else
{
qProj_ = target;
}
if (constraints->apply (qProj_))
{
return reverse ? (*sm) (qProj_, *(near->configuration ())) : (*sm) (*(near->configuration ()), qProj_);
}
else
{
return PathPtr_t ();
}
}
return reverse ? (*sm) (target, *(near->configuration ())) : (*sm) (*(near->configuration ()), target);
}
/// One step of extension.
void BiRRTPlanner::startSolve()
{
PathPlanner::startSolve();
startComponent_ = roadmap()->initNode()->connectedComponent();
for(NodeVector_t::const_iterator cit = roadmap()->goalNodes().begin();
cit != roadmap()->goalNodes().end(); ++cit)
{
endComponents_.push_back((*cit)->connectedComponent());
}
}
void BiRRTPlanner::oneStep ()
{
PathPtr_t validPath, path;
PathValidationPtr_t pathValidation (problem()->pathValidation ());
value_type distance;
NodePtr_t near, reachedNodeFromStart;
bool startComponentConnected(false), pathValidFromStart(false);
ConfigurationPtr_t q_new;
// first try to connect to start component
Configuration_t q_rand;
configurationShooter_->shoot (q_rand);
near = roadmap()->nearestNode (q_rand, startComponent_, distance);
path = extendInternal (problem()->steeringMethod(), qProj_, near,
q_rand);
if (path)
{
PathValidationReportPtr_t report;
pathValidFromStart = pathValidation->validate (path, false, validPath, report);
if(validPath){
// Insert new path to q_near in roadmap
value_type t_final = validPath->timeRange ().second;
if (t_final != path->timeRange ().first)
{
startComponentConnected = true;
q_new = ConfigurationPtr_t (new Configuration_t(validPath->end ()));
reachedNodeFromStart = roadmap()->addNodeAndEdge(near, q_new, validPath);
}
}
}
// now try to connect to end components
for (std::vector<ConnectedComponentPtr_t>::const_iterator itcc =
endComponents_.begin ();
itcc != endComponents_.end (); ++itcc)
{
near = roadmap()->nearestNode (q_rand, *itcc, distance,true);
path = extendInternal (problem()->steeringMethod(), qProj_, near,
q_rand, true);
if (path)
{
PathValidationReportPtr_t report;
if(pathValidation->validate (path, true, validPath, report) && pathValidFromStart)
{
// we won, a path is found
roadmap()->addEdge(reachedNodeFromStart, near, validPath);
return;
}
else if (validPath)
{
value_type t_final = validPath->timeRange ().second;
if (t_final != path->timeRange ().first)
{
ConfigurationPtr_t q_newEnd = ConfigurationPtr_t (new Configuration_t(validPath->initial()));
NodePtr_t newNode = roadmap()->addNodeAndEdge (q_newEnd,near,validPath);
// now try to connect both nodes
if(startComponentConnected)
{
path = (*(problem()->steeringMethod()))
(*q_new, *q_newEnd);
if(path && pathValidation->validate (path, false, validPath, report))
{
roadmap()->addEdge (reachedNodeFromStart, newNode, path);
return;
}
}
}
}
}
}
}
} // namespace core
} // namespace hpp
| humanoid-path-planner/hpp-core | src/bi-rrt-planner.cc | C++ | lgpl-3.0 | 6,887 |
/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2021 Live Networks, Inc. All rights reserved.
// DV Video RTP Sources
// Implementation
#include "DVVideoRTPSource.hh"
DVVideoRTPSource*
DVVideoRTPSource::createNew(UsageEnvironment& env,
Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency) {
return new DVVideoRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency);
}
DVVideoRTPSource::DVVideoRTPSource(UsageEnvironment& env,
Groupsock* rtpGS,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency)
: MultiFramedRTPSource(env, rtpGS,
rtpPayloadFormat, rtpTimestampFrequency) {
}
DVVideoRTPSource::~DVVideoRTPSource() {
}
#define DV_DIF_BLOCK_SIZE 80
#define DV_SECTION_HEADER 0x1F
Boolean DVVideoRTPSource
::processSpecialHeader(BufferedPacket* packet,
unsigned& resultSpecialHeaderSize) {
unsigned const packetSize = packet->dataSize();
if (packetSize < DV_DIF_BLOCK_SIZE) return False; // TARFU!
u_int8_t const* data = packet->data();
fCurrentPacketBeginsFrame = data[0] == DV_SECTION_HEADER && (data[1]&0xf8) == 0 && data[2] == 0; // thanks to Ben Hutchings
// The RTP "M" (marker) bit indicates the last fragment of a frame:
fCurrentPacketCompletesFrame = packet->rtpMarkerBit();
// There is no special header
resultSpecialHeaderSize = 0;
return True;
}
char const* DVVideoRTPSource::MIMEtype() const {
return "video/DV";
}
| k0zmo/live555 | liveMedia/DVVideoRTPSource.cpp | C++ | lgpl-3.0 | 2,229 |
#include "stdafx.h"
#include "UIObject.h"
UIObject::UIObject()
{
}
UIObject::~UIObject()
{
}
void UIObject::SetRootParameter(ID3D12GraphicsCommandList * pd3dCommandList)
{
pd3dCommandList->SetGraphicsRootDescriptorTable(0, m_d3dCbvGPUDescriptorHandle);
}
void UIObject::Render(ID3D12GraphicsCommandList * pd3dCommandList)
{
SetRootParameter(pd3dCommandList);
pd3dCommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pd3dCommandList->DrawInstanced(6, 1, 0, 0);
}
bool UIObject::CollisionUI(POINT * pPoint, XMFLOAT2& trueSetData, XMFLOAT2& falseSetData)
{
if (m_fAlpha < 1.0f) {
m_fData = falseSetData.x;
m_fData2 = falseSetData.y;
return false;
}
if (m_xmf2StartPos.x < pPoint->x && m_xmf2StartPos.y > pPoint->y) {
if (m_xmf2EndPos.x > pPoint->x && m_xmf2EndPos.y < pPoint->y) {
m_fData = trueSetData.x;
m_fData2 = trueSetData.y;
return true;
}
}
m_fData = falseSetData.x;
m_fData2 = falseSetData.y;
return false;
}
void UIObject::CreateCollisionBox()
{
m_xmf2StartPos = XMFLOAT2(
m_xmf2ScreenPos.x - static_cast<float>(m_nSize.x / 2) * m_xmf2Scale.x,
static_cast<float>(FRAME_BUFFER_HEIGHT)-(m_xmf2ScreenPos.y - static_cast<float>(m_nSize.y / 2) * m_xmf2Scale.y)
);
m_xmf2EndPos = XMFLOAT2(
m_xmf2ScreenPos.x + static_cast<float>(m_nSize.x / 2) * m_xmf2Scale.x,
static_cast<float>(FRAME_BUFFER_HEIGHT)-(m_xmf2ScreenPos.y + static_cast<float>(m_nSize.y / 2) * m_xmf2Scale.y)
);
}
void UIObject::SetScreenSize(XMFLOAT2 & size)
{
m_xmf2ScreenSize = size;
}
void UIObject::SetPosition(XMFLOAT2 & pos)
{
m_xmf2ScreenPos = pos;
}
void UIObject::SetScale(XMFLOAT2 & scale)
{
m_xmf2Scale = scale;
}
void UIObject::SetSize(XMUINT2 & size)
{
m_nSize = size;
}
void UIObject::SetAlpha(float alpha)
{
m_fAlpha = alpha;
}
void UIObject::SetNumSprite(XMUINT2 & numSprite, XMUINT2& nowSprite)
{
m_nNumSprite = numSprite;
m_nNowSprite = nowSprite;
}
///////////////////////////////////////////////////
void HPBarObject::SetPlayerStatus(Status * pPlayerStatus)
{
m_pPlayerStatus = pPlayerStatus;
m_fMaxHP = static_cast<float>(pPlayerStatus->m_maxhealth);
m_fMaxMP = static_cast<float>(pPlayerStatus->m_maxmp);
}
void HPBarObject::Update(float fTimeElapsed)
{
float currStatus = 0.0f;
if (m_IsHP) {
currStatus = static_cast<float>(m_pPlayerStatus->m_health);
m_fMaxHP = static_cast<float>(m_pPlayerStatus->m_maxhealth);
m_fData = currStatus / m_fMaxHP;
}
else {
currStatus = static_cast<float>(m_pPlayerStatus->m_mp);
m_fMaxMP = static_cast<float>(m_pPlayerStatus->m_maxmp);
m_fData = currStatus / m_fMaxMP;
}
}
| yeosu0107/SilentEngine | SilentEngine/src/Object/UIObject.cpp | C++ | lgpl-3.0 | 2,603 |
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.site;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author Ricardo Mariaca (r.mariaca@dynamicreports.org)
*/
public class Page {
private String page;
private String path;
private String documentation;
private String examples;
private boolean sideBar;
private String content;
private boolean hasCode;
private Set<String> codeClasses;
private boolean hasImage;
private boolean hasImageGroup;
private String description;
private String keywords;
private String title;
public Page(String page, String name, String pageContent) throws Exception {
this.page = page;
init();
setPage(name, pageContent);
}
private void init() throws Exception {
path = "";
documentation = "documentation/";
examples = "examples/";
sideBar = true;
hasCode = false;
codeClasses = new LinkedHashSet<String>();
hasImage = false;
hasImageGroup = false;
description = "";
keywords = "";
title = "";
}
private void setPage(String name, String pageContent) throws Exception {
if (pageContent.indexOf("<@java_code>") != -1) {
codeClasses.add("Java");
}
if (pageContent.indexOf("<@xml_code>") != -1) {
codeClasses.add("Xml");
}
hasCode = !codeClasses.isEmpty();
hasImage = pageContent.indexOf("<@example") != -1;
hasImageGroup = pageContent.indexOf("<@image_group") != -1;
content = "/" + name;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
this.documentation = documentation;
}
public String getExamples() {
return examples;
}
public void setExamples(String examples) {
this.examples = examples;
}
public boolean isSideBar() {
return sideBar;
}
public void setSideBar(boolean sideBar) {
this.sideBar = sideBar;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isHasCode() {
return hasCode;
}
public void setHasCode(boolean hasCode) {
this.hasCode = hasCode;
}
public Set<String> getCodeClasses() {
return codeClasses;
}
public void setCodeClasses(Set<String> codeClasses) {
this.codeClasses = codeClasses;
}
public boolean isHasImage() {
return hasImage;
}
public void setHasImage(boolean hasImage) {
this.hasImage = hasImage;
}
public boolean isHasImageGroup() {
return hasImageGroup;
}
public void setHasImageGroup(boolean hasImageGroup) {
this.hasImageGroup = hasImageGroup;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| svn2github/dynamicreports-jasper | dynamicreports-distribution/src/main/java/net/sf/dynamicreports/site/Page.java | Java | lgpl-3.0 | 4,192 |
#include<bits/stdc++.h>
using namespace std;
namespace p1073_2{
int f[20001],n,m,p;
int g(int x){
if(f[x]!=x)f[x]=g(f[x]);
return f[x];
}
inline void u(int a,int b){
if(g(a)!=g(b))f[g(b)]=g(a);
}
int main(){
scanf("%d%d%d",&n,&m,&p);
for(int i=1;i<=n;i++){
f[i]=i;
}
int a,b;
for(int i=1;i<=m;i++){
scanf("%d%d",&a,&b);
u(a,b);
}
for(int i=1;i<=p;i++){
scanf("%d%d",&a,&b);
printf((g(a)==g(b))?"Yes\n":"No\n");
}
return 0;
}
}
| fxzjshm/Valuable-mess | Cpp-Learning/Cpp-Learning/codevs/1073-2.cpp | C++ | lgpl-3.0 | 449 |
//----------------------------------------------------------------------------//
// //
// A l i g n m e n t T e s t //
// //
//----------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// Copyright (C) Hervé Bitteur 2000-2011. All rights reserved. //
// This software is released under the GNU General Public License. //
// Goto http://kenai.com/projects/audiveris to report bugs or suggestions. //
//----------------------------------------------------------------------------//
// </editor-fold>
package omr.ui.symbol;
import omr.ui.symbol.Alignment.Horizontal;
import static omr.ui.symbol.Alignment.Horizontal.*;
import omr.ui.symbol.Alignment.Vertical;
import static omr.ui.symbol.Alignment.Vertical.*;
import static org.junit.Assert.*;
import org.junit.Test;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Class {@code AlignmentTest}
*
* @author Hervé Bitteur
*/
public class AlignmentTest
{
//~ Instance fields --------------------------------------------------------
/** Map Alignment -> Point */
Map<Alignment, Point> points = new HashMap<>();
//~ Constructors -----------------------------------------------------------
/**
* Creates a new AlignmentTest object.
*/
public AlignmentTest ()
{
}
//~ Methods ----------------------------------------------------------------
/**
* Test of toPoint method, of class Alignment.
*/
@Test
public void testToPoint ()
{
System.out.println("toPoint");
Rectangle rect = new Rectangle(-6, -26, 50, 38);
assignPoints();
for (Vertical vert : Vertical.values()) {
for (Horizontal hori : Horizontal.values()) {
Alignment instance = new Alignment(vert, hori);
Point start = points.get(instance);
for (Vertical v : Vertical.values()) {
for (Horizontal h : Horizontal.values()) {
Alignment expAlign = new Alignment(v, h);
Point to = instance.toPoint(expAlign, rect);
Point target = new Point(start);
target.translate(to.x, to.y);
System.out.print(
instance + " + " + to + " = " + target);
Alignment align = getAlign(target);
Point expTarget = points.get(expAlign);
System.out.println(" " + expAlign + " =? " + align);
assertEquals("Different points", expTarget, target);
assertEquals("Different aligns", expAlign, align);
}
}
System.out.println();
}
}
}
// /**
// * Test of toPoint method, of class Alignment.
// */
// @Test
// public void testToPoint2D ()
// {
// System.out.println("toPoint2D");
//
// Rectangle2D rect = new Rectangle2D.Float(-5.8f, -26.0f, 50.0f, 37.4f);
// Point2D expTo = null;
//
// for (Vertical vert : Vertical.values()) {
// for (Horizontal hori : Horizontal.values()) {
// Alignment instance = new Alignment(vert, hori);
//
// for (Vertical v : Vertical.values()) {
// for (Horizontal h : Horizontal.values()) {
// Alignment that = new Alignment(v, h);
// Point2D to = instance.toPoint(that, rect);
//
// System.out.println(
// instance + " + " + to + " = " + that);
// }
// }
//
// System.out.println();
// }
// }
// }
private Alignment getAlign (Point target)
{
for (Entry<Alignment, Point> entry : points.entrySet()) {
if (entry.getValue()
.equals(target)) {
return entry.getKey();
}
}
return null;
}
private void assignPoints ()
{
points.put(new Alignment(TOP, LEFT), new Point(-6, -26));
points.put(new Alignment(TOP, CENTER), new Point(19, -26));
points.put(new Alignment(TOP, RIGHT), new Point(44, -26));
points.put(new Alignment(TOP, XORIGIN), new Point(0, -26));
points.put(new Alignment(MIDDLE, LEFT), new Point(-6, -7));
points.put(new Alignment(MIDDLE, CENTER), new Point(19, -7));
points.put(new Alignment(MIDDLE, RIGHT), new Point(44, -7));
points.put(new Alignment(MIDDLE, XORIGIN), new Point(0, -7));
points.put(new Alignment(BOTTOM, LEFT), new Point(-6, 12));
points.put(new Alignment(BOTTOM, CENTER), new Point(19, 12));
points.put(new Alignment(BOTTOM, RIGHT), new Point(44, 12));
points.put(new Alignment(BOTTOM, XORIGIN), new Point(0, 12));
points.put(new Alignment(BASELINE, LEFT), new Point(-6, 0));
points.put(new Alignment(BASELINE, CENTER), new Point(19, 0));
points.put(new Alignment(BASELINE, RIGHT), new Point(44, 0));
points.put(new Alignment(BASELINE, XORIGIN), new Point(0, 0));
}
}
| jlpoolen/libreveris | src/test/omr/ui/symbol/AlignmentTest.java | Java | lgpl-3.0 | 5,699 |
/**
* Kopernicus Planetary System Modifier
* -------------------------------------------------------------
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* This library is intended to be used as a plugin for Kerbal Space Program
* which is copyright of TakeTwo Interactive. Your usage of Kerbal Space Program
* itself is governed by the terms of its EULA, not the license above.
*
* https://kerbalspaceprogram.com
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Kopernicus.Components.Serialization;
using UnityEngine;
namespace Kopernicus.Components
{
/// <summary>
/// Stores information about the KSC
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class KSC : SerializableMonoBehaviour
{
// PQSCity
public Double? latitude;
public Double? longitude;
public Vector3? reorientInitialUp;
public Vector3? repositionRadial;
public Boolean? repositionToSphere;
public Boolean? repositionToSphereSurface;
public Boolean? repositionToSphereSurfaceAddHeight;
public Boolean? reorientToSphere;
public Double? repositionRadiusOffset;
public Double? lodvisibleRangeMult;
public Single? reorientFinalAngle;
// PQSMod_MapDecalTangent
public Vector3? position;
public Double? radius;
public Double? heightMapDeformity;
public Double? absoluteOffset;
public Boolean? absolute;
public Double? decalLatitude;
public Double? decalLongitude;
// PQSCity Ground Material
public Texture2D mainTexture;
public Color? color;
// Grass Material
public GrassMaterial Material;
// Editor Ground Material
public Texture2D editorGroundTex;
public Color? editorGroundColor;
public Vector2? editorGroundTexScale;
public Vector2? editorGroundTexOffset;
// Current Instance
public static KSC Instance;
private void Awake()
{
if (Material == null)
{
Material = new GrassMaterial();
}
Instance = this;
}
// Mods
private CelestialBody _body;
private PQSCity _ksc;
private PQSMod_MapDecalTangent _mapDecal;
// Apply the patches
public void Start()
{
_body = GetComponent<CelestialBody>();
if (!_body.isHomeWorld)
{
Destroy(this);
return;
}
_ksc = _body.pqsController.GetComponentsInChildren<PQSCity>(true).First(m => m.name == "KSC");
_mapDecal = _body.pqsController.GetComponentsInChildren<PQSMod_MapDecalTangent>(true)
.First(m => m.name == "KSC");
if (_ksc == null)
{
Debug.LogError("[Kopernicus] KSC: Unable to find homeworld body with PQSCity named KSC");
return;
}
if (_mapDecal == null)
{
Debug.LogError(
"[Kopernicus] KSC: Unable to find homeworld body with PQSMod_MapDecalTangent named KSC");
return;
}
// Load new data into the PQSCity
if (latitude.HasValue && longitude.HasValue)
{
_ksc.repositionRadial = Utility.LLAtoECEF(latitude.Value, longitude.Value, 0, _body.Radius);
}
else if (repositionRadial.HasValue)
{
_ksc.repositionRadial = repositionRadial.Value;
}
else
{
repositionRadial = _ksc.repositionRadial;
}
if (reorientInitialUp.HasValue)
{
_ksc.reorientInitialUp = reorientInitialUp.Value;
}
else
{
reorientInitialUp = _ksc.reorientInitialUp;
}
if (repositionToSphere.HasValue)
{
_ksc.repositionToSphere = repositionToSphere.Value;
}
else
{
repositionToSphere = _ksc.repositionToSphere;
}
if (repositionToSphereSurface.HasValue)
{
_ksc.repositionToSphereSurface = repositionToSphereSurface.Value;
}
else
{
repositionToSphereSurface = _ksc.repositionToSphereSurface;
}
if (repositionToSphereSurfaceAddHeight.HasValue)
{
_ksc.repositionToSphereSurfaceAddHeight = repositionToSphereSurfaceAddHeight.Value;
}
else
{
repositionToSphereSurfaceAddHeight = _ksc.repositionToSphereSurfaceAddHeight;
}
if (reorientToSphere.HasValue)
{
_ksc.reorientToSphere = reorientToSphere.Value;
}
else
{
reorientToSphere = _ksc.reorientToSphere;
}
if (repositionRadiusOffset.HasValue)
{
_ksc.repositionRadiusOffset = repositionRadiusOffset.Value;
}
else
{
repositionRadiusOffset = _ksc.repositionRadiusOffset;
}
if (lodvisibleRangeMult.HasValue)
{
foreach (PQSCity.LODRange lodRange in _ksc.lod)
{
lodRange.visibleRange *= (Single)lodvisibleRangeMult.Value;
}
}
else
{
lodvisibleRangeMult = 1;
}
if (reorientFinalAngle.HasValue)
{
_ksc.reorientFinalAngle = reorientFinalAngle.Value;
}
else
{
reorientFinalAngle = _ksc.reorientFinalAngle;
}
// Load new data into the MapDecal
if (radius.HasValue)
{
_mapDecal.radius = radius.Value;
}
else
{
radius = _mapDecal.radius;
}
if (heightMapDeformity.HasValue)
{
_mapDecal.heightMapDeformity = heightMapDeformity.Value;
}
else
{
heightMapDeformity = _mapDecal.heightMapDeformity;
}
if (absoluteOffset.HasValue)
{
_mapDecal.absoluteOffset = absoluteOffset.Value;
}
else
{
absoluteOffset = _mapDecal.absoluteOffset;
}
if (absolute.HasValue)
{
_mapDecal.absolute = absolute.Value;
}
else
{
absolute = _mapDecal.absolute;
}
if (decalLatitude.HasValue && decalLongitude.HasValue)
{
_mapDecal.position = Utility.LLAtoECEF(decalLatitude.Value, decalLongitude.Value, 0, _body.Radius);
}
else if (position.HasValue)
{
_mapDecal.position = position.Value;
}
else
{
position = _mapDecal.position;
}
// Move the SpaceCenter
if (SpaceCenter.Instance != null)
{
Transform spaceCenterTransform = SpaceCenter.Instance.transform;
Transform kscTransform = _ksc.transform;
spaceCenterTransform.localPosition = kscTransform.localPosition;
spaceCenterTransform.localRotation = kscTransform.localRotation;
// Reset the SpaceCenter
SpaceCenter.Instance.Start();
}
else
{
Debug.Log("[Kopernicus]: KSC: No SpaceCenter instance!");
}
// Add a material fixer
DontDestroyOnLoad(gameObject.AddComponent<MaterialFixer>());
// Events
Events.OnSwitchKSC.Fire(this);
}
// Material
public class GrassMaterial
{
// Grass
[SerializeField]
public Texture2D nearGrassTexture;
[SerializeField]
public Single? nearGrassTiling;
[SerializeField]
public Texture2D farGrassTexture;
[SerializeField]
public Single? farGrassTiling;
[SerializeField]
public Single? farGrassBlendDistance;
[SerializeField]
public Color? grassColor;
// Tarmac
[SerializeField]
public Texture2D tarmacTexture;
[SerializeField]
public Vector2? tarmacTextureOffset;
[SerializeField]
public Vector2? tarmacTextureScale;
// Other
[SerializeField]
public Single? opacity;
[SerializeField]
public Color? rimColor;
[SerializeField]
public Single? rimFalloff;
[SerializeField]
public Single? underwaterFogFactor;
}
// MaterialFixer
private class MaterialFixer : MonoBehaviour
{
private void Update()
{
if (HighLogic.LoadedScene != GameScenes.SPACECENTER)
{
return;
}
Material[] materials = Resources.FindObjectsOfTypeAll<Material>().Where(m => (m.shader.name.Contains("Ground KSC"))).ToArray();
for (int i = materials.Length; i > 0; i--)
{
var material = materials[i - 1];
// Grass
if (Instance.mainTexture) material.SetTexture("_NearGrassTexture", Instance.mainTexture);
if (Instance.Material.nearGrassTexture) material.SetTexture("_NearGrassTexture", Instance.Material.nearGrassTexture);
if (Instance.Material.nearGrassTiling.HasValue) material.SetFloat("_NearGrassTiling", material.GetFloat("_NearGrassTiling") * Instance.Material.nearGrassTiling.Value);
if (Instance.Material.farGrassTexture) material.SetTexture("_FarGrassTexture", Instance.Material.farGrassTexture);
if (Instance.Material.farGrassTiling.HasValue) material.SetFloat("_FarGrassTiling", material.GetFloat("_FarGrassTiling") * Instance.Material.farGrassTiling.Value);
if (Instance.Material.farGrassBlendDistance.HasValue) material.SetFloat("_FarGrassBlendDistance", Instance.Material.farGrassBlendDistance.Value);
if (Instance.color.HasValue) material.SetColor("_GrassColor", Instance.color.Value);
if (Instance.Material.grassColor.HasValue) material.SetColor("_GrassColor", Instance.Material.grassColor.Value);
// Tarmac
if (Instance.Material.tarmacTexture) material.SetTexture("_TarmacTexture", Instance.Material.tarmacTexture);
if (Instance.Material.tarmacTextureOffset.HasValue) material.SetTextureOffset("_TarmacTexture", Instance.Material.tarmacTextureOffset.Value);
if (Instance.Material.tarmacTextureScale.HasValue) material.SetTextureScale("_TarmacTexture", material.GetTextureScale("_TarmacTexture") * Instance.Material.tarmacTextureScale.Value);
// Other
if (Instance.Material.opacity.HasValue) material.SetFloat("_Opacity", Instance.Material.opacity.Value);
if (Instance.Material.rimColor.HasValue) material.SetColor("_RimColor", Instance.Material.rimColor.Value);
if (Instance.Material.rimFalloff.HasValue) material.SetFloat("_RimFalloff", Instance.Material.rimFalloff.Value);
if (Instance.Material.underwaterFogFactor.HasValue) material.SetFloat("_UnderwaterFogFactor", Instance.Material.underwaterFogFactor.Value);
}
Destroy(this);
}
}
}
[KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class EditorMaterialFixer : MonoBehaviour
{
private void Start()
{
KSC ksc = KSC.Instance;
if (!ksc)
{
return;
}
GameObject scenery = (GameObject.Find("VABscenery") != null)
? GameObject.Find("VABscenery")
: GameObject.Find("SPHscenery");
Material material = null;
if (scenery != null) material = scenery.GetChild("ksc_terrain").GetComponent<Renderer>().sharedMaterial;
if (material == null)
{
return;
}
if (ksc.editorGroundColor.HasValue)
{
material.color = ksc.editorGroundColor.Value;
}
if (ksc.editorGroundTex)
{
material.mainTexture = ksc.editorGroundTex;
}
if (ksc.editorGroundTexScale.HasValue)
{
material.mainTextureScale = ksc.editorGroundTexScale.Value;
}
if (ksc.editorGroundTexOffset.HasValue)
{
material.mainTextureOffset = ksc.editorGroundTexOffset.Value;
}
}
}
}
| Kopernicus/Kopernicus | src/Kopernicus/Components/KSC.cs | C# | lgpl-3.0 | 14,100 |
/**
* This file is part of the CRISTAL-iSE kernel.
* Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* http://www.fsf.org/licensing/licenses/lgpl.html
*/
package org.cristalise.kernel.lookup;
import java.util.List;
import java.util.UUID;
import org.cristalise.kernel.common.ObjectNotFoundException;
import org.cristalise.kernel.common.SystemKey;
import org.cristalise.kernel.persistency.ClusterType;
import org.cristalise.kernel.process.Gateway;
/**
* Extends ItemPath with Agent specific codes
**/
public class AgentPath extends ItemPath {
private String mAgentName = null;
private boolean mPasswordTemporary = false;
public AgentPath() {
super();
}
public AgentPath(UUID uuid, String ior, String agentName) {
super(uuid, ior);
mAgentName = agentName;
}
public AgentPath(UUID uuid, String ior, String agentName, boolean isPwdTemporary) {
super(uuid, ior);
mAgentName = agentName;
mPasswordTemporary = isPwdTemporary;
}
public AgentPath(UUID uuid) throws InvalidAgentPathException {
super(uuid);
//This is commented so a AgentPath can be constructed without setting up Lookup
//if (getAgentName() == null) throw new InvalidAgentPathException();
}
public AgentPath(SystemKey syskey) throws InvalidAgentPathException {
this(new UUID(syskey.msb, syskey.lsb));
}
public AgentPath(ItemPath itemPath) throws InvalidAgentPathException {
this(itemPath.getUUID());
}
public AgentPath(String path) throws InvalidItemPathException {
//remove the '/entity/' string from the beginning if exists
this(UUID.fromString(path.substring( (path.lastIndexOf("/") == -1 ? 0 : path.lastIndexOf("/")+1) )));
}
public AgentPath(ItemPath itemPath, String agentName) {
super(itemPath.getUUID());
mAgentName = agentName;
}
public AgentPath(UUID uuid, String agentName) {
super(uuid);
mAgentName = agentName;
}
public void setAgentName(String agentID) {
mAgentName = agentID;
}
public String getAgentName() {
if (mAgentName == null) {
try {
mAgentName = Gateway.getLookup().getAgentName(this);
}
catch (ObjectNotFoundException e) {
return null;
}
}
return mAgentName;
}
public RolePath[] getRoles() {
return Gateway.getLookup().getRoles(this);
}
public RolePath getFirstMatchingRole(List<RolePath> roles) {
for (RolePath role : roles) {
if (Gateway.getLookup().hasRole(this, role)) return role;
}
return null;
}
public boolean hasRole(RolePath role) {
return Gateway.getLookup().hasRole(this, role);
}
public boolean hasRole(String role) {
try {
return hasRole(Gateway.getLookup().getRolePath(role));
}
catch (ObjectNotFoundException ex) {
return false;
}
}
@Override
public String getClusterPath() {
return ClusterType.PATH + "/Agent";
}
@Override
public String dump() {
return super.dump() + "\n agentID=" + mAgentName;
}
public boolean isPasswordTemporary() {
return mPasswordTemporary;
}
}
| cristal-ise/kernel | src/main/java/org/cristalise/kernel/lookup/AgentPath.java | Java | lgpl-3.0 | 4,238 |
/*
* Created on 2005-09-27
* @author M.Olszewski
*/
package net.java.dante.algorithms.common;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Class provides easy-to-control debug output.
*
* @author M.Olszewski
*/
public class Dbg
{
/* Store standard and error outputs */
private static PrintStream standardOut = System.out;
private static PrintStream standardErr = System.err;
private static PrintStream lastLogFile = null;
// Debug prefixes
private static final String debugPrefix = "[DEBUG]";
private static final String errorPrefix = debugPrefix + "[ ERROR ] ";
private static final String warningPrefix = debugPrefix + "[ WARNING ] ";
private static final String infoPrefix = debugPrefix + "[ INFO ] ";
// Debug flags
private static final int DBGS_NONE = 0x0000;
private static final int DBGW_ENABLED = 0x0001;
private static final int DBGE_ENABLED = 0x0002;
// Debug level
private static final int DBG_LEVEL = 2;
private static final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.LONG);
/** Enables/disables time stamps in debug messages. */
private static final boolean TIME_STAMP = true;
/** Enables/disables thread names in debug messages. */
private static final boolean THREAD_NAME = true;
// Debug options - should contain all required flags
private static final int DEBUG_OPTIONS = DBGS_NONE | DBGW_ENABLED | DBGE_ENABLED;
/**
* Indicates whether debug output is enabled.
*/
public static final boolean DEBUG = false;
/**
* Indicates whether warning debug output is enabled.
*/
public static final boolean DBGW = (DEBUG && ((DEBUG_OPTIONS & DBGW_ENABLED) == DBGW_ENABLED));
/**
* Indicates whether error debug output is enabled.
*/
public static final boolean DBGE = (DEBUG && ((DEBUG_OPTIONS & DBGE_ENABLED) == DBGE_ENABLED));
/**
* Indicates whether level 1 debug output is enabled.
*/
public static final boolean DBG1 = (DEBUG && (DBG_LEVEL >= 1));
/**
* Indicates whether level 2 debug output is enabled.
*/
public static final boolean DBG2 = (DEBUG && (DBG_LEVEL >= 2));
/**
* Indicates whether level 3 debug output is enabled.
*/
public static final boolean DBG3 = (DEBUG && (DBG_LEVEL >= 3));
/**
* Private constructor - no external class creation, no inheritance.
*/
private Dbg()
{
// Intentionally left empty.
}
/**
* Prints <code>string</code> to console with debug prefix.
*
* @param string string to be printed.
*/
public static void write(String string)
{
String commonPrefix = createCommonPrefix();
if (commonPrefix != null)
{
System.err.println(commonPrefix + " " + debugPrefix + " " + string);
}
else
{
System.err.println(debugPrefix + " " + string);
}
}
/**
* Prints <code>string</code> to console with warning prefix.
*
* @param string warning string to be printed.
*/
public static void warning(String string)
{
String commonPrefix = createCommonPrefix();
if (commonPrefix != null)
{
System.err.println(commonPrefix + " " + warningPrefix + " " + string);
}
else
{
System.err.println(warningPrefix + string);
}
}
/**
* Prints <code>string</code> to console with error prefix.
*
* @param string error string to be printed.
*/
public static void error(String string)
{
String commonPrefix = createCommonPrefix();
if (commonPrefix != null)
{
System.err.println(commonPrefix + " " + errorPrefix + " " + string);
}
else
{
System.err.println(errorPrefix + string);
}
}
/**
* Prints <code>string</code> on console with information prefix
*
* @param string information string to be printed
*/
public static void info(String string)
{
String commonPrefix = createCommonPrefix();
if (commonPrefix != null)
{
System.err.println(commonPrefix + " " + infoPrefix + " " + string);
}
else
{
System.err.println(infoPrefix + string);
}
}
/**
* Throws {@link AssertionError} if specified <code>statement</code> is
* <code>false</code>.
*
* @param statement statement to check.
* @param string error with this message is thrown if
* <code>statement</code> is <code>false</code>
*/
public static void assertion(boolean statement, String string)
{
if (!statement)
{
throw new AssertionError(string);
}
}
/**
* Enables logging and stores all standard and error output in log file
* with name based on the specified file prefix and suffix and current
* date and time.
* Log files will be stored in 'logs' directory in working directory.
*
* @param logFilePrefix the specified file prefix.
* @param logFileSuffix the specified file suffix.
*/
public static void enableDateTimeLog(String logFilePrefix, String logFileSuffix)
{
StringBuilder fullFileName = new StringBuilder("./logs/");
fullFileName.append(logFilePrefix).
append(String.format("%1$tY-%1$tm-%1$td_%1$tH.%1$tM.%1$tS.%1$tL", Calendar.getInstance())).
append(logFileSuffix);
enableLogging(fullFileName.toString());
}
/**
* Enables logging and stores all standard and error output in log file
* with random name, generated by using the specified file prefix and suffix.
* Log files will be stored in 'logs' directory in working directory.
*
* @param logFilePrefix the specified file prefix.
* @param logFileSuffix the specified file suffix.
*/
public static void enableLogging(String logFilePrefix, String logFileSuffix)
{
try
{
enableLogging(File.createTempFile(logFilePrefix, logFileSuffix, new File("./logs")));
}
catch (IOException e)
{
// Intentionally left empty.
}
}
/**
* Enables logging and stores all standard and error output in specified file.
*
* @param filePath path to a file where results sent to standard out and
* error output will be stored.
*/
public static void enableLogging(String filePath)
{
enableLogging(new File(filePath));
}
/**
* Enables logging and stores all standard and error output in specified file.
*
* @param filePath path to a file where results sent to standard out and
* error output will be stored.
*/
public static void enableLogging(File filePath)
{
ensureLogDirExists();
try
{
PrintStream logFile = new PrintStream(filePath);
lastLogFile = logFile;
System.setOut(logFile);
System.setErr(logFile);
}
catch (FileNotFoundException e)
{
if (DBGE)
{
error("Exception in enableLogging() - printing stack trace.");
}
e.printStackTrace();
}
}
/**
* Ensures that logs directory exists.
*/
private static void ensureLogDirExists()
{
File d = new File("./logs");
if (!d.exists())
{
d.mkdir();
}
}
/**
* Disables logging.
*/
public static void disableLogging()
{
System.setOut(standardOut);
System.setErr(standardErr);
if (lastLogFile != null)
{
lastLogFile.close();
lastLogFile = null;
}
}
private static String createCommonPrefix()
{
return (THREAD_NAME)? ((TIME_STAMP)? (createThreadName() + " " + createTimeStamp()) : createThreadName()) :
((TIME_STAMP)? createTimeStamp() : null);
}
private static synchronized String createTimeStamp()
{
return timeFormat.format(new Date());
}
private static String createThreadName()
{
return Thread.currentThread().getName();
}
} | molszewski/dante | module/AlgorithmsFramework/src/net/java/dante/algorithms/common/Dbg.java | Java | lgpl-3.0 | 7,814 |
#ifndef FILE_NGEXCEPTION
#define FILE_NGEXCEPTION
/**************************************************************************/
/* File: ngexception.hpp */
/* Author: Joachim Schoeberl */
/* Date: 16. Jan. 2002 */
/**************************************************************************/
namespace netgen
{
/// Base class for all ng exceptions
class NgException
{
/// verbal description of exception
std::string what;
public:
///
DLL_HEADER NgException (const std::string & s);
///
DLL_HEADER virtual ~NgException ();
/// append string to description
DLL_HEADER void Append (const std::string & s);
// void Append (const char * s);
/// verbal description of exception
const std::string & What() const { return what; }
};
}
#endif
| cgogn/SCHNApps | schnapps/plugins/meshgen/netgen/libsrc/general/ngexception.hpp | C++ | lgpl-3.0 | 912 |
package dataengine.tasker;
import javax.jms.Connection;
import com.google.inject.Provides;
import dataengine.apis.DepJobService_I;
import dataengine.apis.RpcClientProvider;
import dataengine.apis.SessionsDB_I;
import dataengine.apis.CommunicationConsts;
import lombok.extern.slf4j.Slf4j;
import net.deelam.activemq.rpc.RpcClientsModule;
/// provides verticle clients used by Tasker service
@Slf4j
class RpcClients4TaskerModule extends RpcClientsModule {
// private final String depJobMgrBroadcastAddr;
public RpcClients4TaskerModule(Connection connection/*, String depJobMgrBroadcastAddr*/) {
super(connection);
// this.depJobMgrBroadcastAddr=depJobMgrBroadcastAddr;
//debug = true;
log.debug("VertxRpcClients4TaskerModule configured");
}
// @Provides
// RpcClientProvider<DepJobService_I> jobDispatcherRpcClient(){
// return new RpcClientProvider<>(getAmqClientSupplierFor(DepJobService_I.class, depJobMgrBroadcastAddr));
// }
@Provides
RpcClientProvider<SessionsDB_I> sessionsDbRpcClient(){
return new RpcClientProvider<>(getAmqClientSupplierFor(SessionsDB_I.class, CommunicationConsts.SESSIONDB_RPCADDR));
}
}
| deelam/agilion | dataengine/tasker/src/main/java/dataengine/tasker/RpcClients4TaskerModule.java | Java | lgpl-3.0 | 1,155 |
<?php
namespace Loamok\SubformsMadeEasyBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class LoamokSubformsMadeEasyBundle extends Bundle {
}
| loamok/sf_subformsMadeEasy | LoamokSubformsMadeEasyBundle.php | PHP | lgpl-3.0 | 153 |
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.server.authentication;
import org.sonar.api.server.ServerSide;
/**
* Entry-point to define a new Identity provider.
* Only one of this two interfaces can be used :
* <ul>
* <li>{@link OAuth2IdentityProvider} for OAuth2 authentication</li>
* <li>{@link BaseIdentityProvider} for other kind of authentication</li>
* </ul>
*
* @since 5.4
*/
@ServerSide
public interface IdentityProvider {
/**
* Unique key of provider, for example "github".
* Must not be blank.
*/
String getKey();
/**
* Name displayed in login form.
* Must not be blank.
*/
String getName();
/**
* Display information for the login form
*/
Display getDisplay();
/**
* Is the provider fully configured and enabled ? If {@code true}, then
* the provider is available in login form.
*/
boolean isEnabled();
/**
* Can users sign-up (connecting with their account for the first time) ? If {@code true},
* then users can register and create their account into SonarQube, else only already
* registered users can login.
*/
boolean allowsUsersToSignUp();
}
| Builders-SonarSource/sonarqube-bis | sonar-plugin-api/src/main/java/org/sonar/api/server/authentication/IdentityProvider.java | Java | lgpl-3.0 | 1,968 |
/*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package org.meteoinfo.jts.precision;
import org.meteoinfo.jts.geom.*;
import org.meteoinfo.jts.geom.util.*;
/**
* Reduces the precision of a {@link Geometry}
* according to the supplied {@link PrecisionModel},
* ensuring that the result is topologically valid.
*
* @version 1.12
*/
public class GeometryPrecisionReducer
{
/**
* Convenience method for doing precision reduction
* on a single geometry,
* with collapses removed
* and keeping the geometry precision model the same,
* and preserving polygonal topology.
*
* @param g the geometry to reduce
* @param precModel the precision model to use
* @return the reduced geometry
*/
public static Geometry reduce(Geometry g, PrecisionModel precModel)
{
GeometryPrecisionReducer reducer = new GeometryPrecisionReducer(precModel);
return reducer.reduce(g);
}
/**
* Convenience method for doing pointwise precision reduction
* on a single geometry,
* with collapses removed
* and keeping the geometry precision model the same,
* but NOT preserving valid polygonal topology.
*
* @param g the geometry to reduce
* @param precModel the precision model to use
* @return the reduced geometry
*/
public static Geometry reducePointwise(Geometry g, PrecisionModel precModel)
{
GeometryPrecisionReducer reducer = new GeometryPrecisionReducer(precModel);
reducer.setPointwise(true);
return reducer.reduce(g);
}
private PrecisionModel targetPM;
private boolean removeCollapsed = true;
private boolean changePrecisionModel = false;
private boolean isPointwise = false;
public GeometryPrecisionReducer(PrecisionModel pm)
{
targetPM = pm;
}
/**
* Sets whether the reduction will result in collapsed components
* being removed completely, or simply being collapsed to an (invalid)
* Geometry of the same type.
* The default is to remove collapsed components.
*
* @param removeCollapsed if <code>true</code> collapsed components will be removed
*/
public void setRemoveCollapsedComponents(boolean removeCollapsed)
{
this.removeCollapsed = removeCollapsed;
}
/**
* Sets whether the {@link PrecisionModel} of the new reduced Geometry
* will be changed to be the {@link PrecisionModel} supplied to
* specify the precision reduction.
* <p>
* The default is to <b>not</b> change the precision model
*
* @param changePrecisionModel if <code>true</code> the precision model of the created Geometry will be the
* the precisionModel supplied in the constructor.
*/
public void setChangePrecisionModel(boolean changePrecisionModel)
{
this.changePrecisionModel = changePrecisionModel;
}
/**
* Sets whether the precision reduction will be done
* in pointwise fashion only.
* Pointwise precision reduction reduces the precision
* of the individual coordinates only, but does
* not attempt to recreate valid topology.
* This is only relevant for geometries containing polygonal components.
*
* @param isPointwise if reduction should be done pointwise only
*/
public void setPointwise(boolean isPointwise)
{
this.isPointwise = isPointwise;
}
public Geometry reduce(Geometry geom)
{
Geometry reducePW = reducePointwise(geom);
if (isPointwise)
return reducePW;
//TODO: handle GeometryCollections containing polys
if (! (reducePW instanceof Polygonal))
return reducePW;
// Geometry is polygonal - test if topology needs to be fixed
if (reducePW.isValid()) return reducePW;
// hack to fix topology.
// TODO: implement snap-rounding and use that.
return fixPolygonalTopology(reducePW);
}
private Geometry reducePointwise(Geometry geom)
{
GeometryEditor geomEdit;
if (changePrecisionModel) {
GeometryFactory newFactory = createFactory(geom.getFactory(), targetPM);
geomEdit = new GeometryEditor(newFactory);
}
else
// don't change geometry factory
geomEdit = new GeometryEditor();
/**
* For polygonal geometries, collapses are always removed, in order
* to produce correct topology
*/
boolean finalRemoveCollapsed = removeCollapsed;
if (geom.getDimension() >= 2)
finalRemoveCollapsed = true;
Geometry reduceGeom = geomEdit.edit(geom,
new PrecisionReducerCoordinateOperation(targetPM, finalRemoveCollapsed));
return reduceGeom;
}
private Geometry fixPolygonalTopology(Geometry geom)
{
/**
* If precision model was *not* changed, need to flip
* geometry to targetPM, buffer in that model, then flip back
*/
Geometry geomToBuffer = geom;
if (! changePrecisionModel) {
geomToBuffer = changePM(geom, targetPM);
}
Geometry bufGeom = geomToBuffer.buffer(0);
Geometry finalGeom = bufGeom;
if (! changePrecisionModel) {
// a slick way to copy the geometry with the original precision factory
finalGeom = geom.getFactory().createGeometry(bufGeom);
}
return finalGeom;
}
/**
* Duplicates a geometry to one that uses a different PrecisionModel,
* without changing any coordinate values.
*
* @param geom the geometry to duplicate
* @param newPM the precision model to use
* @return the geometry value with a new precision model
*/
private Geometry changePM(Geometry geom, PrecisionModel newPM)
{
GeometryEditor geomEditor = createEditor(geom.getFactory(), newPM);
// this operation changes the PM for the entire geometry tree
return geomEditor.edit(geom, new GeometryEditor.NoOpGeometryOperation());
}
private GeometryEditor createEditor(GeometryFactory geomFactory, PrecisionModel newPM)
{
// no need to change if precision model is the same
if (geomFactory.getPrecisionModel() == newPM)
return new GeometryEditor();
// otherwise create a geometry editor which changes PrecisionModel
GeometryFactory newFactory = createFactory(geomFactory, newPM);
GeometryEditor geomEdit = new GeometryEditor(newFactory);
return geomEdit;
}
private GeometryFactory createFactory(GeometryFactory inputFactory, PrecisionModel pm)
{
GeometryFactory newFactory
= new GeometryFactory(pm,
inputFactory.getSRID(),
inputFactory.getCoordinateSequenceFactory());
return newFactory;
}
}
| meteoinfo/meteoinfolib | src/org/meteoinfo/jts/precision/GeometryPrecisionReducer.java | Java | lgpl-3.0 | 7,754 |
// HTMLParser Library - A java-based parser for HTML
// http://htmlparser.org
// Copyright (C) 2006 Dhaval Udani
//
// Revision Control Information
//
// $URL: file:///svn/p/htmlparser/code/tags/HTMLParserProject-2.1/parser/src/main/java/org/htmlparser/tags/HeadTag.java $
// $Author: derrickoswald $
// $Date: 2006-09-16 14:44:17 +0000 (Sat, 16 Sep 2006) $
// $Revision: 4 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Common Public License; either
// version 1.0 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
// Common Public License for more details.
//
// You should have received a copy of the Common Public License
// along with this library; if not, the license is available from
// the Open Source Initiative (OSI) website:
// http://opensource.org/licenses/cpl1.0.php
package org.htmlparser.tags;
/**
* A head tag.
*/
public class HeadTag extends CompositeTag
{
/**
* The set of names handled by this tag.
*/
private static final String[] mIds = new String[] {"HEAD"};
/**
* The set of tag names that indicate the end of this tag.
*/
private static final String[] mEnders = new String[] {"HEAD", "BODY"};
/**
* The set of end tag names that indicate the end of this tag.
*/
private static final String[] mEndTagEnders = new String[] {"HTML"};
/**
* Create a new head tag.
*/
public HeadTag ()
{
}
/**
* Return the set of names handled by this tag.
* @return The names to be matched that create tags of this type.
*/
public String[] getIds ()
{
return (mIds);
}
/**
* Return the set of tag names that cause this tag to finish.
* @return The names of following tags that stop further scanning.
*/
public String[] getEnders ()
{
return (mEnders);
}
/**
* Return the set of end tag names that cause this tag to finish.
* @return The names of following end tags that stop further scanning.
*/
public String[] getEndTagEnders ()
{
return (mEndTagEnders);
}
/**
* Returns a string representation of this <code>HEAD</code> tag suitable for debugging.
* @return A string representing this tag.
*/
public String toString()
{
return "HEAD: " + super.toString();
}
}
| socialwareinc/html-parser | parser/src/main/java/org/htmlparser/tags/HeadTag.java | Java | lgpl-3.0 | 2,672 |
import unittest
from matching.cpe_sorter import *
unsorted_cpes = [{'wfn': {'version': '4.0', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.0:beta:~~~android_marshmallow~~'},
{'wfn': {'version': '1.0.1.2', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:1.0.1.2:beta'},
{'wfn': {'version': '4.1.2', 'target_sw': 'ANY'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'},
{'wfn': {'version': '4.6.3', 'target_sw': 'windows'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.6.3:beta:~~~windows~~'},
{'wfn': {'version': '4.7.1', 'target_sw': 'android'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'},
{'wfn': {'version': '4.7.2', 'target_sw': 'ANY'},
'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.2:beta'},
{'wfn': {'version': '4.3.2', 'target_sw': 'linux'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'},
{'wfn': {'version': '2.3.1', 'target_sw': 'linux'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2.3.1:beta'},
{'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'}
]
unsorted_cpes_year = [{'wfn': {'version': '2000', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2000:beta:~~~android_marshmallow~~'},
{'wfn': {'version': '2007', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2007:beta'},
{'wfn': {'version': '4.1.2', 'target_sw': 'ANY'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'},
{'wfn': {'version': '2010', 'target_sw': 'windows'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~windows~~'},
{'wfn': {'version': '4.7.1', 'target_sw': 'android'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'},
{'wfn': {'version': '2001', 'target_sw': 'ANY'},
'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:2001:beta'},
{'wfn': {'version': '4.3.2', 'target_sw': 'linux'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'},
{'wfn': {'version': '2010', 'target_sw': 'linux'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta'},
{'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'},
{'wfn': {'version': '2010', 'target_sw': 'mac_os_x'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~mac_os_x~~'}]
version = '4.7.2'
version_without_points = '4_7-2'
version_year = '2010'
os_windows = 'windows_7'
os_linux = 'linux_ubuntu'
os_android = 'android'
os_mac = 'mac_os_x_10.11'
class TestCPESorter(unittest.TestCase):
def test_sort_cpes_by_software_version(self):
sorted_cpes = sort_cpes_by_version(unsorted_cpes, version)
self.assertEqual(len(unsorted_cpes), len(sorted_cpes))
self.assertEqual(unsorted_cpes[5], sorted_cpes[0]) # 4.7.2
self.assertEqual(unsorted_cpes[4], sorted_cpes[1]) # 4.7.1
self.assertEqual(unsorted_cpes[8], sorted_cpes[2]) # 4.7.3
self.assertEqual(unsorted_cpes[0], sorted_cpes[3]) # 4.0
self.assertEqual(unsorted_cpes[2], sorted_cpes[4]) # 4.1.2
self.assertEqual(unsorted_cpes[3], sorted_cpes[5]) # 4.6.3
self.assertEqual(unsorted_cpes[6], sorted_cpes[6]) # 4.3.2
def test_cpes_and_sorted_cpes_are_equal_when_software_version_not_splitted_by_points(self):
sorted_cpes = sort_cpes_by_version(unsorted_cpes, version_without_points)
self.assertListEqual(unsorted_cpes, sorted_cpes)
def test_sort_cpes_by_version_with_year(self):
sorted_cpes = sort_cpes_by_version(unsorted_cpes_year, version_year)
self.assertEqual(len(unsorted_cpes_year), len(sorted_cpes))
self.assertEqual(unsorted_cpes_year[3], sorted_cpes[0]) # 2010
self.assertEqual(unsorted_cpes_year[7], sorted_cpes[1]) # 2010
self.assertEqual(unsorted_cpes_year[9], sorted_cpes[2]) # 2010
self.assertEqual(unsorted_cpes_year[0], sorted_cpes[3]) # 2000
self.assertEqual(unsorted_cpes_year[1], sorted_cpes[4]) # 2007
self.assertEqual(unsorted_cpes_year[5], sorted_cpes[5]) # 2001
def test_sort_cpes_by_operating_system_windows(self):
sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_windows)
self.assertEqual(len(unsorted_cpes), len(sorted_cpes))
self.assertEqual(unsorted_cpes[3], sorted_cpes[0])
def test_sort_cpes_by_operating_system_linux(self):
sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_linux)
self.assertEqual(len(unsorted_cpes), len(sorted_cpes))
self.assertEqual(unsorted_cpes[6], sorted_cpes[0])
def test_sort_cpes_by_operating_system_android(self):
sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_android)
self.assertEqual(len(unsorted_cpes), len(sorted_cpes))
self.assertEqual(unsorted_cpes[4], sorted_cpes[0])
self.assertEqual(unsorted_cpes[0], sorted_cpes[1])
if __name__ == '__main__':
unittest.main()
| fkie-cad/iva | tests/test_cpe_matching/test_cpe_sorter.py | Python | lgpl-3.0 | 6,349 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace NuGet
{
/// <remarks>
/// Based on the blog post by Travis Illig at http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx
/// </remarks>
public class MultipartWebRequest
{
private const string FormDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
private const string FileTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
private readonly Dictionary<string, string> _formData;
private readonly List<PostFileData> _files;
public MultipartWebRequest()
: this(new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase))
{
}
public MultipartWebRequest(Dictionary<string, string> formData)
{
_formData = formData;
_files = new List<PostFileData>();
}
public void AddFormData(string key, string value)
{
_formData.Add(key, value);
}
public void AddFile(Func<Stream> fileFactory, string fieldName, string contentType = "application/octet-stream")
{
_files.Add(new PostFileData { FileFactory = fileFactory, FieldName = fieldName, ContentType = contentType });
}
public void CreateMultipartRequest(WebRequest request)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
request.ContentType = "multipart/form-data; boundary=" + boundary;
byte[] byteContent;
using (var memoryStream = new MemoryStream())
{
foreach (var item in _formData)
{
string header = String.Format(CultureInfo.InvariantCulture, FormDataTemplate, boundary, item.Key, item.Value);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
memoryStream.Write(headerBytes, 0, headerBytes.Length);
}
byte[] newlineBytes = Encoding.UTF8.GetBytes("\r\n");
foreach (var file in _files)
{
string header = String.Format(CultureInfo.InvariantCulture, FileTemplate, boundary, file.FieldName, file.FieldName, file.ContentType);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
memoryStream.Write(headerBytes, 0, headerBytes.Length);
using (Stream fileStream = file.FileFactory())
{
fileStream.CopyTo(memoryStream);
}
memoryStream.Write(newlineBytes, 0, newlineBytes.Length);
}
string trailer = String.Format(CultureInfo.InvariantCulture, "--{0}--", boundary);
byte[] trailerBytes = Encoding.UTF8.GetBytes(trailer);
memoryStream.Write(trailerBytes, 0, trailerBytes.Length);
byteContent = memoryStream.ToArray();
}
request.ContentLength = byteContent.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteContent, 0, byteContent.Length);
}
}
private sealed class PostFileData
{
public Func<Stream> FileFactory { get; set; }
public string ContentType { get; set; }
public string FieldName { get; set; }
}
}
}
| peterstevens130561/sonarlint-vs | its/nuget/src/Core/Http/MultipartWebRequest.cs | C# | lgpl-3.0 | 3,710 |
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.wizards.impl;
import android.preference.ListPreference;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chatme.R;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesWrapper;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
public class Betamax extends AuthorizationImplementation {
static String PROVIDER = "provider";
protected static final String THIS_FILE = "BetamaxW";
private LinearLayout customWizard;
private TextView customWizardText;
ListPreference providerListPref;
static SortedMap<String, String[]> providers = new TreeMap<String, String[]>() {
private static final long serialVersionUID = 4984940975243241784L;
{
put("FreeCall", new String[] {
"sip.voiparound.com", "stun.voiparound.com"
});
put("InternetCalls", new String[] {
"sip.internetcalls.com", "stun.internetcalls.com"
});
put("Low Rate VoIP", new String[] {
"sip.lowratevoip.com", "stun.lowratevoip.com"
});
put("NetAppel", new String[] {
"sip.netappel.fr", "stun.netappel.fr"
});
put("Poivy", new String[] {
"sip.poivy.com", "stun.poivy.com"
});
put("SIP Discount", new String[] {
"sip.sipdiscount.com", "stun.sipdiscount.com"
});
put("SMS Discount", new String[] {
"sip.smsdiscount.com", "stun.smsdiscount.com"
});
put("SparVoIP", new String[] {
"sip.sparvoip.com", "stun.sparvoip.com"
});
put("VoIP Buster", new String[] {
"sip.voipbuster.com", "stun.voipbuster.com"
});
put("VoIP Buster Pro", new String[] {
"sip.voipbusterpro.com", "stun.voipbusterpro.com"
});
put("VoIP Cheap", new String[] {
"sip.voipcheap.com", "stun.voipcheap.com"
});
put("VoIP Discount", new String[] {
"sip.voipdiscount.com", "stun.voipdiscount.com"
});
put("12VoIP", new String[] {
"sip.12voip.com", "stun.12voip.com"
});
put("VoIP Stunt", new String[] {
"sip.voipstunt.com", "stun.voipstunt.com"
});
put("WebCall Direct", new String[] {
"sip.webcalldirect.com", "stun.webcalldirect.com"
});
put("Just VoIP", new String[] {
"sip.justvoip.com", "stun.justvoip.com"
});
put("Nonoh", new String[] {
"sip.nonoh.net", "stun.nonoh.net"
});
put("VoIPWise", new String[] {
"sip.voipwise.com", "stun.voipwise.com"
});
put("VoIPRaider", new String[] {
"sip.voipraider.com", "stun.voipraider.com"
});
put("BudgetSIP", new String[] {
"sip.budgetsip.com", "stun.budgetsip.com"
});
put("InterVoIP", new String[] {
"sip.intervoip.com", "stun.intervoip.com"
});
put("VoIPHit", new String[] {
"sip.voiphit.com", "stun.voiphit.com"
});
put("SmartVoIP", new String[] {
"sip.smartvoip.com", "stun.smartvoip.com"
});
put("ActionVoIP", new String[] {
"sip.actionvoip.com", "stun.actionvoip.com"
});
put("Jumblo", new String[] {
"sip.jumblo.com", "stun.jumblo.com"
});
put("Rynga", new String[] {
"sip.rynga.com", "stun.rynga.com"
});
put("PowerVoIP", new String[] {
"sip.powervoip.com", "stun.powervoip.com"
});
put("Voice Trading", new String[] {
"sip.voicetrading.com", "stun.voicetrading.com"
});
put("EasyVoip", new String[] {
"sip.easyvoip.com", "stun.easyvoip.com"
});
put("VoipBlast", new String[] {
"sip.voipblast.com", "stun.voipblast.com"
});
put("FreeVoipDeal", new String[] {
"sip.freevoipdeal.com", "stun.freevoipdeal.com"
});
put("VoipAlot", new String[] {
"sip.voipalot.com", ""
});
put("CosmoVoip", new String[] {
"sip.cosmovoip.com", "stun.cosmovoip.com"
});
put("BudgetVoipCall", new String[] {
"sip.budgetvoipcall.com", "stun.budgetvoipcall.com"
});
put("CheapBuzzer", new String[] {
"sip.cheapbuzzer.com", "stun.cheapbuzzer.com"
});
put("CallPirates", new String[] {
"sip.callpirates.com", "stun.callpirates.com"
});
put("CheapVoipCall", new String[] {
"sip.cheapvoipcall.com", "stun.cheapvoipcall.com"
});
put("DialCheap", new String[] {
"sip.dialcheap.com", "stun.dialcheap.com"
});
put("DiscountCalling", new String[] {
"sip.discountcalling.com", "stun.discountcalling.com"
});
put("Frynga", new String[] {
"sip.frynga.com", "stun.frynga.com"
});
put("GlobalFreeCall", new String[] {
"sip.globalfreecall.com", "stun.globalfreecall.com"
});
put("HotVoip", new String[] {
"sip.hotvoip.com", "stun.hotvoip.com"
});
put("MEGAvoip", new String[] {
"sip.megavoip.com", "stun.megavoip.com"
});
put("PennyConnect", new String[] {
"sip.pennyconnect.com", "stun.pennyconnect.com"
});
put("Rebvoice", new String[] {
"sip.rebvoice.com", "stun.rebvoice.com"
});
put("StuntCalls", new String[] {
"sip.stuntcalls.com", "stun.stuntcalls.com"
});
put("VoipBlazer", new String[] {
"sip.voipblazer.com", "stun.voipblazer.com"
});
put("VoipCaptain", new String[] {
"sip.voipcaptain.com", "stun.voipcaptain.com"
});
put("VoipChief", new String[] {
"sip.voipchief.com", "stun.voipchief.com"
});
put("VoipJumper", new String[] {
"sip.voipjumper.com", "stun.voipjumper.com"
});
put("VoipMove", new String[] {
"sip.voipmove.com", "stun.voipmove.com"
});
put("VoipSmash", new String[] {
"sip.voipsmash.com", "stun.voipsmash.com"
});
put("VoipGain", new String[] {
"sip.voipgain.com", "stun.voipgain.com"
});
put("VoipZoom", new String[] {
"sip.voipzoom.com", "stun.voipzoom.com"
});
put("Telbo", new String[] {
"sip.telbo.com", "stun.telbo.com"
});
put("Llevoip", new String[] {
"77.72.174.129", "77.72.174.160"
});
put("Llevoip (server 2)", new String[] {
"77.72.174.130:6000", "77.72.174.162"
});
/*
* put("InternetCalls", new String[] {"", ""});
*/
}
};
/**
* {@inheritDoc}
*/
@Override
protected String getDefaultName() {
return "Betamax";
}
private static final String PROVIDER_LIST_KEY = "provider_list";
/**
* {@inheritDoc}
*/
@Override
public void fillLayout(final SipProfile account) {
super.fillLayout(account);
accountUsername.setTitle(R.string.w_advanced_caller_id);
accountUsername.setDialogTitle(R.string.w_advanced_caller_id_desc);
boolean recycle = true;
providerListPref = (ListPreference) findPreference(PROVIDER_LIST_KEY);
if (providerListPref == null) {
Log.d(THIS_FILE, "Create new list pref");
providerListPref = new ListPreference(parent);
providerListPref.setKey(PROVIDER_LIST_KEY);
recycle = false;
} else {
Log.d(THIS_FILE, "Recycle existing list pref");
}
CharSequence[] v = new CharSequence[providers.size()];
int i = 0;
for (String pv : providers.keySet()) {
v[i] = pv;
i++;
}
providerListPref.setEntries(v);
providerListPref.setEntryValues(v);
providerListPref.setKey(PROVIDER);
providerListPref.setDialogTitle("Provider");
providerListPref.setTitle("Provider");
providerListPref.setSummary("Betamax clone provider");
providerListPref.setDefaultValue("12VoIP");
if (!recycle) {
addPreference(providerListPref);
}
hidePreference(null, SERVER);
String domain = account.getDefaultDomain();
if (domain != null) {
for (Entry<String, String[]> entry : providers.entrySet()) {
String[] val = entry.getValue();
if (val[0].equalsIgnoreCase(domain)) {
Log.d(THIS_FILE, "Set provider list pref value to " + entry.getKey());
providerListPref.setValue(entry.getKey());
break;
}
}
}
Log.d(THIS_FILE, providerListPref.getValue());
// Get wizard specific row
customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text);
customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row);
updateAccountInfos(account);
}
/**
* {@inheritDoc}
*/
@Override
public SipProfile buildAccount(SipProfile account) {
account = super.buildAccount(account);
account.mwi_enabled = false;
return account;
}
private static HashMap<String, Integer> SUMMARIES = new HashMap<String, Integer>() {
/**
*
*/
private static final long serialVersionUID = -5743705263738203615L;
{
put(DISPLAY_NAME, R.string.w_common_display_name_desc);
put(USER_NAME, R.string.w_advanced_caller_id_desc);
put(AUTH_NAME, R.string.w_authorization_auth_name_desc);
put(PASSWORD, R.string.w_common_password_desc);
put(SERVER, R.string.w_common_server_desc);
}
};
/**
* {@inheritDoc}
*/
@Override
public void updateDescriptions() {
super.updateDescriptions();
setStringFieldSummary(PROVIDER);
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultFieldSummary(String fieldName) {
Integer res = SUMMARIES.get(fieldName);
if (fieldName == PROVIDER) {
if (providerListPref != null) {
return providerListPref.getValue();
}
}
if (res != null) {
return parent.getString(res);
}
return "";
}
/**
* {@inheritDoc}
*/
@Override
public boolean canSave() {
boolean isValid = true;
isValid &= checkField(accountDisplayName, isEmpty(accountDisplayName));
isValid &= checkField(accountUsername, isEmpty(accountUsername));
isValid &= checkField(accountAuthorization, isEmpty(accountAuthorization));
isValid &= checkField(accountPassword, isEmpty(accountPassword));
return isValid;
}
/**
* {@inheritDoc}
*/
@Override
protected String getDomain() {
String provider = providerListPref.getValue();
if (provider != null) {
String[] set = providers.get(provider);
return set[0];
}
return "";
}
/**
* {@inheritDoc}
*/
@Override
public boolean needRestart() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultParams(PreferencesWrapper prefs) {
super.setDefaultParams(prefs);
// Disable ICE and turn on STUN!!!
prefs.setPreferenceBooleanValue(SipConfigManager.ENABLE_STUN, true);
String provider = providerListPref.getValue();
if (provider != null) {
String[] set = providers.get(provider);
if (!TextUtils.isEmpty(set[1])) {
prefs.addStunServer(set[1]);
}
}
prefs.setPreferenceBooleanValue(SipConfigManager.ENABLE_ICE, false);
}
private void updateAccountInfos(final SipProfile acc) {
if (acc != null && acc.id != SipProfile.INVALID_ID) {
customWizard.setVisibility(View.GONE);
accountBalanceHelper.launchRequest(acc);
} else {
// add a row to link
customWizard.setVisibility(View.GONE);
}
}
private AccountBalanceHelper accountBalanceHelper = new AccountBalance(this);
private static class AccountBalance extends AccountBalanceHelper {
WeakReference<Betamax> w;
AccountBalance(Betamax wizard){
w = new WeakReference<Betamax>(wizard);
}
/**
* {@inheritDoc}
*/
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
Betamax wizard = w.get();
if(wizard == null) {
return null;
}
String requestURL = "https://";
String provider = wizard.providerListPref.getValue();
if (provider != null) {
String[] set = providers.get(provider);
requestURL += set[0].replace("sip.", "www.");
requestURL += "/myaccount/getbalance.php";
requestURL += "?username=" + acc.username;
requestURL += "&password=" + acc.data;
return new HttpGet(requestURL);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String parseResponseLine(String line) {
try {
float value = Float.parseFloat(line.trim());
if (value >= 0) {
return "Balance : " + Math.round(value * 100.0) / 100.0 + " euros";
}
} catch (NumberFormatException e) {
Log.e(THIS_FILE, "Can't get value for line");
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void applyResultError() {
Betamax wizard = w.get();
if(wizard != null) {
wizard.customWizard.setVisibility(View.GONE);
}
}
/**
* {@inheritDoc}
*/
@Override
public void applyResultSuccess(String balanceText) {
Betamax wizard = w.get();
if(wizard != null) {
wizard.customWizardText.setText(balanceText);
wizard.customWizard.setVisibility(View.VISIBLE);
}
}
};
}
| caihongwang/ChatMe | src/com/csipsimple/wizards/impl/Betamax.java | Java | lgpl-3.0 | 16,922 |
#--
# Copyleft meh. [http://meh.paranoid.pk | meh@paranoici.org]
#
# 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.
#
# THIS SOFTWARE IS PROVIDED BY meh ''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 meh OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied.
#++
module FFI
typedef :ushort, :Rotation
typedef :ushort, :SizeID
typedef :ushort, :SubpixelOrder
typedef :ushort, :Connection
typedef :ushort, :XRandrRotation
typedef :ushort, :XRandrSizeID
typedef :ushort, :XRandrSubpixelOrder
typedef :ulong, :XRandrModeFlags
end
| meh/ruby-x11 | lib/X11/extensions/randr/c.rb | Ruby | lgpl-3.0 | 1,786 |
<?php
class Tranche extends EMongoSoftDocument
{
public $id;
public $id_donor;
public $presenceCession;
public $hemisphere;
public $idPrelevement;
public $nameSamplesTissue;
public $originSamplesTissue;
public $prelevee;
public $nAnonymat;
public $qualite;
public $quantityAvailable;
public $remarques;
public $selection;
public $selectionnee;
public $storageConditions;
// This has to be defined in every model, this is same as with standard Yii ActiveRecord
public static function model($className = __CLASS__)
{
return parent::model($className);
}
// This method is required!
public function getCollectionName()
{
return 'Tranche';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
$result = array(
array('id_donor', 'required'),
array(
'id_donor,presenceCession,hemisphere,idPrelevement,nameSamplesTissue,originSamplesTissue,prelevee,nAnonymat,qualite,quantityAvailable,remarques,selection,selectionnee,storageConditions',
'safe'
)
);
return $result;
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'Identifiant du prélèvement',
'id_donor' => "Identifiant du donneur",
'originSamplesTissue' => "Origin Samples Tissue",
'quantityAvailable' => "Quantity available",
'storageConditions' => "Storage conditions",
'presenceCession' => "Présence cession",
'hemisphere' => "Hémisphère",
'idPrelevement' => "Identifiant du prélèvement",
'nameSamplesTissue' => "Nom de l'échantillon",
'prelevee' => "Prélevée",
'nAnonymat' => "N° anonymat",
'qualite' => "Qualité"
);
}
public function setQuantityAvailable() {
return array(
'Available' => 'Available',
'Not available' => 'Not available'
);
}
} | Biobanques/cbsd_platform | webapp/protected/models/Tranche.php | PHP | lgpl-3.0 | 2,296 |
"""
# Copyright (c) 05 2015 | surya
# 18/05/15 nanang.ask@kubuskotak.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# __init__.py.py
"""
import urlparse
from niimanga.libs.exceptions import HtmlError
from requests import request
class Site:
def __init__(self):
pass
def get_html(self, url, method='GET', **kwargs):
resp = request(method, url, **kwargs)
if resp.status_code != 200:
raise HtmlError({'msg': 'external_request_fail', 'url': url})
return resp.content
def fetch_manga_seed_page(self, url, **kwargs):
return self.get_html(url, **kwargs)
def fetch_chapter_seed_page(self, url, **kwargs):
return self.get_html(url, **kwargs)
def fetch_page_image(self, url, **kwargs):
return self.get_html(url, **kwargs)
def search_by_author(self, author):
"""
Return list of chapter dicts whose keys are:
name
url
site
This should be specifically implemented in each Site subclass. If not,
this method will be used which returns an empty list.
"""
return []
from mangaeden import MangaEden
from batoto import Batoto
available_sites = [
# Kissmanga(),
# Vitaku(),
Batoto(),
# Mangafox(),
# Mangahere(),
# MangaHereMob(),
MangaEden()
]
# Factory function, return instance of suitable "site" class from url
def get_site(url):
netloc = urlparse.urlparse(url).netloc
for site in available_sites:
if netloc in site.netlocs:
return site
return None | suryakencana/niimanga | niimanga/sites/__init__.py | Python | lgpl-3.0 | 2,259 |
import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
import builtins
def _input(prompt=''):
sys.stdout.write(prompt)
sys.stdout.flush()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((input_host, input_port))
userdata = sock.recv(1024)
except ConnectionRefusedError:
userdata = b'<user-input-unavailable>'
return userdata.decode()
builtins._input = input # type: ignore
builtins.input = _input
else:
# __builtins__ is an alias dict for __builtin__ in modules other than __main__.
# Thus, we have to explicitly import __builtin__ module in Python 2.
import __builtin__
builtins = __builtin__
def _raw_input(prompt=''):
sys.stdout.write(prompt)
sys.stdout.flush()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((input_host, input_port))
userdata = sock.recv(1024)
except socket.error:
userdata = b'<user-input-unavailable>'
finally:
sock.close()
return userdata.decode()
builtins._raw_input = builtins.raw_input # type: ignore
builtins.raw_input = _raw_input # type: ignore
| lablup/sorna-agent | src/ai/backend/kernel/python/sitecustomize.py | Python | lgpl-3.0 | 1,693 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "globals.h"
#include "mainwindow.h"
#include "messagemodel.h"
#include "phrase.h"
#include "phraseview.h"
#include "phrasemodel.h"
#include "simtexth.h"
#include <QHeaderView>
#include <QKeyEvent>
#include <QSettings>
#include <QTreeView>
#include <QWidget>
#include <QDebug>
QT_BEGIN_NAMESPACE
// Maximum number of guesses to display
static const int MaxCandidates = 5;
static QString phraseViewHeaderKey()
{
return settingPath("PhraseViewHeader");
}
PhraseView::PhraseView(MultiDataModel *model, QList<QHash<QString, QList<Phrase *> > > *phraseDict, QWidget *parent)
: QTreeView(parent),
m_dataModel(model),
m_phraseDict(phraseDict),
m_modelIndex(-1),
m_doGuesses(true)
{
setObjectName(QLatin1String("phrase list view"));
m_phraseModel = new PhraseModel(this);
setModel(m_phraseModel);
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
setRootIsDecorated(false);
setItemsExpandable(false);
for (int i = 0; i < 10; i++)
(void) new GuessShortcut(i, this, SLOT(guessShortcut(int)));
header()->setSectionResizeMode(QHeaderView::Interactive);
header()->setSectionsClickable(true);
header()->restoreState(QSettings().value(phraseViewHeaderKey()).toByteArray());
connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(selectPhrase(QModelIndex)));
}
PhraseView::~PhraseView()
{
QSettings().setValue(phraseViewHeaderKey(), header()->saveState());
deleteGuesses();
}
void PhraseView::toggleGuessing()
{
m_doGuesses = !m_doGuesses;
update();
}
void PhraseView::update()
{
setSourceText(m_modelIndex, m_sourceText);
}
void PhraseView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex index = indexAt(event->pos());
if (!index.isValid())
return;
QMenu *contextMenu = new QMenu(this);
QAction *insertAction = new QAction(tr("Insert"), contextMenu);
connect(insertAction, SIGNAL(triggered()), this, SLOT(selectPhrase()));
QAction *editAction = new QAction(tr("Edit"), contextMenu);
connect(editAction, SIGNAL(triggered()), this, SLOT(editPhrase()));
editAction->setEnabled(model()->flags(index) & Qt::ItemIsEditable);
contextMenu->addAction(insertAction);
contextMenu->addAction(editAction);
contextMenu->exec(event->globalPos());
event->accept();
}
void PhraseView::mouseDoubleClickEvent(QMouseEvent *event)
{
QModelIndex index = indexAt(event->pos());
if (!index.isValid())
return;
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(index)->target());
event->accept();
}
void PhraseView::guessShortcut(int key)
{
foreach (const Phrase *phrase, m_phraseModel->phraseList())
if (phrase->shortcut() == key) {
emit phraseSelected(m_modelIndex, phrase->target());
return;
}
}
void PhraseView::selectPhrase(const QModelIndex &index)
{
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(index)->target());
}
void PhraseView::selectPhrase()
{
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(currentIndex())->target());
}
void PhraseView::editPhrase()
{
edit(currentIndex());
}
static CandidateList similarTextHeuristicCandidates(MultiDataModel *model, int mi,
const char *text, int maxCandidates)
{
QList<int> scores;
CandidateList candidates;
StringSimilarityMatcher stringmatcher(QString::fromLatin1(text));
for (MultiDataModelIterator it(model, mi); it.isValid(); ++it) {
MessageItem *m = it.current();
if (!m)
continue;
TranslatorMessage mtm = m->message();
if (mtm.type() == TranslatorMessage::Unfinished
|| mtm.translation().isEmpty())
continue;
QString s = m->text();
int score = stringmatcher.getSimilarityScore(s);
if (candidates.count() == maxCandidates && score > scores[maxCandidates - 1])
candidates.removeLast();
if (candidates.count() < maxCandidates && score >= textSimilarityThreshold ) {
Candidate cand(s, mtm.translation());
int i;
for (i = 0; i < candidates.size(); ++i) {
if (score >= scores.at(i)) {
if (score == scores.at(i)) {
if (candidates.at(i) == cand)
goto continue_outer_loop;
} else {
break;
}
}
}
scores.insert(i, score);
candidates.insert(i, cand);
}
continue_outer_loop:
;
}
return candidates;
}
void PhraseView::setSourceText(int model, const QString &sourceText)
{
m_modelIndex = model;
m_sourceText = sourceText;
m_phraseModel->removePhrases();
deleteGuesses();
if (model < 0)
return;
foreach (Phrase *p, getPhrases(model, sourceText))
m_phraseModel->addPhrase(p);
if (!sourceText.isEmpty() && m_doGuesses) {
CandidateList cl = similarTextHeuristicCandidates(m_dataModel, model,
sourceText.toLatin1(), MaxCandidates);
int n = 0;
foreach (const Candidate &candidate, cl) {
QString def;
if (n < 9)
def = tr("Guess (%1)").arg(QKeySequence(Qt::CTRL | (Qt::Key_0 + (n + 1))).toString(QKeySequence::NativeText));
else
def = tr("Guess");
Phrase *guess = new Phrase(candidate.source, candidate.target, def, n);
m_guesses.append(guess);
m_phraseModel->addPhrase(guess);
++n;
}
}
}
QList<Phrase *> PhraseView::getPhrases(int model, const QString &source)
{
QList<Phrase *> phrases;
QString f = MainWindow::friendlyString(source);
QStringList lookupWords = f.split(QLatin1Char(' '));
foreach (const QString &s, lookupWords) {
if (m_phraseDict->at(model).contains(s)) {
foreach (Phrase *p, m_phraseDict->at(model).value(s)) {
if (f.contains(MainWindow::friendlyString(p->source())))
phrases.append(p);
}
}
}
return phrases;
}
void PhraseView::deleteGuesses()
{
qDeleteAll(m_guesses);
m_guesses.clear();
}
QT_END_NAMESPACE
| clarkli86/qttools | src/linguist/linguist/phraseview.cpp | C++ | lgpl-3.0 | 7,944 |
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.measures;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Nullable;
import java.util.Collection;
/**
* An utility class to manipulate measures
*
* @since 1.10
*/
public final class MeasureUtils {
/**
* Class cannot be instantiated, it should only be access through static methods
*/
private MeasureUtils() {
}
/**
* Return true if all measures have numeric value
*
* @param measures the measures
* @return true if all measures numeric values
*/
public static boolean haveValues(Measure... measures) {
if (measures == null || measures.length == 0) {
return false;
}
for (Measure measure : measures) {
if (!hasValue(measure)) {
return false;
}
}
return true;
}
/**
* Get the value of a measure, or alternatively a default value
*
* @param measure the measure
* @param defaultValue the default value
* @return <code>defaultValue</code> if measure is null or has no values.
*/
public static Double getValue(Measure measure, @Nullable Double defaultValue) {
if (MeasureUtils.hasValue(measure)) {
return measure.getValue();
}
return defaultValue;
}
public static Long getValueAsLong(Measure measure, Long defaultValue) {
if (MeasureUtils.hasValue(measure)) {
return measure.getValue().longValue();
}
return defaultValue;
}
public static Double getVariation(Measure measure, int periodIndex) {
return getVariation(measure, periodIndex, null);
}
public static Double getVariation(Measure measure, int periodIndex, @Nullable Double defaultValue) {
Double result = null;
if (measure != null) {
result = measure.getVariation(periodIndex);
}
return result != null ? result : defaultValue;
}
public static Long getVariationAsLong(Measure measure, int periodIndex) {
return getVariationAsLong(measure, periodIndex, null);
}
public static Long getVariationAsLong(Measure measure, int periodIndex, @Nullable Long defaultValue) {
Double result = null;
if (measure != null) {
result = measure.getVariation(periodIndex);
}
return result == null ? defaultValue : Long.valueOf(result.longValue());
}
/**
* Tests if a measure has a value
*
* @param measure the measure
* @return whether the measure has a value
*/
public static boolean hasValue(Measure measure) {
return measure != null && measure.getValue() != null;
}
/**
* Tests if a measure has a data field
*
* @param measure the measure
* @return whether the measure has a data field
*/
public static boolean hasData(Measure measure) {
return measure != null && StringUtils.isNotBlank(measure.getData());
}
/**
* Sums a series of measures
*
* @param zeroIfNone whether to return 0 or null in case measures is null
* @param measures the series of measures
* @return the sum of the measure series
*/
public static Double sum(boolean zeroIfNone, Collection<Measure> measures) {
if (measures != null) {
return sum(zeroIfNone, measures.toArray(new Measure[measures.size()]));
}
return zeroIfNone(zeroIfNone);
}
/**
* Sums a series of measures
*
* @param zeroIfNone whether to return 0 or null in case measures is null
* @param measures the series of measures
* @return the sum of the measure series
*/
public static Double sum(boolean zeroIfNone, Measure... measures) {
if (measures == null) {
return zeroIfNone(zeroIfNone);
}
Double sum = 0d;
boolean hasValue = false;
for (Measure measure : measures) {
if (measure != null && measure.getValue() != null) {
hasValue = true;
sum += measure.getValue();
}
}
if (hasValue) {
return sum;
}
return zeroIfNone(zeroIfNone);
}
/**
* Sums a series of measures for the given variation index
*
* @param zeroIfNone whether to return 0 or null in case measures is null
* @param variationIndex the index of the variation to use
* @param measures the series of measures
* @return the sum of the variations for the measure series
*/
public static Double sumOnVariation(boolean zeroIfNone, int variationIndex, Collection<Measure> measures) {
if (measures == null) {
return zeroIfNone(zeroIfNone);
}
Double sum = 0d;
for (Measure measure : measures) {
Double var = measure.getVariation(variationIndex);
if (var != null) {
sum += var;
}
}
return sum;
}
private static Double zeroIfNone(boolean zeroIfNone) {
return zeroIfNone ? 0d : null;
}
}
| joansmith/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureUtils.java | Java | lgpl-3.0 | 5,520 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import { connect } from 'react-redux';
import { getGlobalSettingValue, Store } from '../../../store/rootReducer';
import { AdminPageExtension } from '../../../types/extension';
import { Extension } from '../../../types/types';
import { fetchValues } from '../../settings/store/actions';
import '../style.css';
import { HousekeepingPolicy, RangeOption } from '../utils';
import AuditAppRenderer from './AuditAppRenderer';
interface Props {
auditHousekeepingPolicy: HousekeepingPolicy;
fetchValues: typeof fetchValues;
adminPages: Extension[];
}
interface State {
dateRange?: { from?: Date; to?: Date };
hasGovernanceExtension?: boolean;
downloadStarted: boolean;
selection: RangeOption;
}
export class AuditApp extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
const hasGovernanceExtension = Boolean(
props.adminPages?.find(e => e.key === AdminPageExtension.GovernanceConsole)
);
this.state = {
downloadStarted: false,
selection: RangeOption.Today,
hasGovernanceExtension
};
}
componentDidMount() {
const { hasGovernanceExtension } = this.state;
if (hasGovernanceExtension) {
this.props.fetchValues(['sonar.dbcleaner.auditHousekeeping']);
}
}
componentDidUpdate(prevProps: Props) {
if (prevProps.adminPages !== this.props.adminPages) {
const hasGovernanceExtension = Boolean(
this.props.adminPages?.find(e => e.key === AdminPageExtension.GovernanceConsole)
);
this.setState({
hasGovernanceExtension
});
}
}
handleDateSelection = (dateRange: { from?: Date; to?: Date }) =>
this.setState({ dateRange, downloadStarted: false, selection: RangeOption.Custom });
handleOptionSelection = (selection: RangeOption) =>
this.setState({ dateRange: undefined, downloadStarted: false, selection });
handleStartDownload = () => {
setTimeout(() => {
this.setState({ downloadStarted: true });
}, 0);
};
render() {
const { hasGovernanceExtension, ...auditAppRendererProps } = this.state;
const { auditHousekeepingPolicy } = this.props;
if (!hasGovernanceExtension) {
return null;
}
return (
<AuditAppRenderer
handleDateSelection={this.handleDateSelection}
handleOptionSelection={this.handleOptionSelection}
handleStartDownload={this.handleStartDownload}
housekeepingPolicy={auditHousekeepingPolicy || HousekeepingPolicy.Monthly}
{...auditAppRendererProps}
/>
);
}
}
const mapDispatchToProps = { fetchValues };
const mapStateToProps = (state: Store) => {
const settingValue = getGlobalSettingValue(state, 'sonar.dbcleaner.auditHousekeeping');
return {
auditHousekeepingPolicy: settingValue?.value as HousekeepingPolicy
};
};
export default connect(mapStateToProps, mapDispatchToProps)(AuditApp);
| SonarSource/sonarqube | server/sonar-web/src/main/js/apps/audit-logs/components/AuditApp.tsx | TypeScript | lgpl-3.0 | 3,764 |
package net.minecraft.server.dedicated;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.ServerCommand;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.logging.ILogAgent;
import net.minecraft.logging.LogAgent;
import net.minecraft.network.NetworkListenThread;
import net.minecraft.network.rcon.IServer;
import net.minecraft.network.rcon.RConThreadMain;
import net.minecraft.network.rcon.RConThreadQuery;
import net.minecraft.profiler.PlayerUsageSnooper;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.CallableServerType;
import net.minecraft.server.dedicated.CallableType;
import net.minecraft.server.dedicated.DedicatedPlayerList;
import net.minecraft.server.dedicated.DedicatedServerCommandThread;
import net.minecraft.server.dedicated.DedicatedServerListenThread;
import net.minecraft.server.dedicated.DedicatedServerSleepThread;
import net.minecraft.server.dedicated.PropertyManager;
import net.minecraft.server.gui.MinecraftServerGui;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.CryptManager;
import net.minecraft.util.MathHelper;
import net.minecraft.world.EnumGameType;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
public class DedicatedServer extends MinecraftServer implements IServer {
private final List field_71341_l = Collections.synchronizedList(new ArrayList());
private final ILogAgent field_98131_l;
private RConThreadQuery field_71342_m;
private RConThreadMain field_71339_n;
private PropertyManager field_71340_o;
private boolean field_71338_p;
private EnumGameType field_71337_q;
private NetworkListenThread field_71336_r;
private boolean field_71335_s;
public DedicatedServer(File p_i1508_1_) {
super(p_i1508_1_);
this.field_98131_l = new LogAgent("Minecraft-Server", (String)null, (new File(p_i1508_1_, "server.log")).getAbsolutePath());
new DedicatedServerSleepThread(this);
}
protected boolean func_71197_b() throws IOException {
DedicatedServerCommandThread var1 = new DedicatedServerCommandThread(this);
var1.setDaemon(true);
var1.start();
this.func_98033_al().func_98233_a("Starting minecraft server version 1.6.4");
if(Runtime.getRuntime().maxMemory() / 1024L / 1024L < 512L) {
this.func_98033_al().func_98236_b("To start the server with more ram, launch it as \"java -Xmx1024M -Xms1024M -jar minecraft_server.jar\"");
}
this.func_98033_al().func_98233_a("Loading properties");
this.field_71340_o = new PropertyManager(new File("server.properties"), this.func_98033_al());
if(this.func_71264_H()) {
this.func_71189_e("127.0.0.1");
} else {
this.func_71229_d(this.field_71340_o.func_73670_a("online-mode", true));
this.func_71189_e(this.field_71340_o.func_73671_a("server-ip", ""));
}
this.func_71251_e(this.field_71340_o.func_73670_a("spawn-animals", true));
this.func_71257_f(this.field_71340_o.func_73670_a("spawn-npcs", true));
this.func_71188_g(this.field_71340_o.func_73670_a("pvp", true));
this.func_71245_h(this.field_71340_o.func_73670_a("allow-flight", false));
this.func_71269_o(this.field_71340_o.func_73671_a("texture-pack", ""));
this.func_71205_p(this.field_71340_o.func_73671_a("motd", "A Minecraft Server"));
this.func_104055_i(this.field_71340_o.func_73670_a("force-gamemode", false));
this.func_143006_e(this.field_71340_o.func_73669_a("player-idle-timeout", 0));
if(this.field_71340_o.func_73669_a("difficulty", 1) < 0) {
this.field_71340_o.func_73667_a("difficulty", Integer.valueOf(0));
} else if(this.field_71340_o.func_73669_a("difficulty", 1) > 3) {
this.field_71340_o.func_73667_a("difficulty", Integer.valueOf(3));
}
this.field_71338_p = this.field_71340_o.func_73670_a("generate-structures", true);
int var2 = this.field_71340_o.func_73669_a("gamemode", EnumGameType.SURVIVAL.func_77148_a());
this.field_71337_q = WorldSettings.func_77161_a(var2);
this.func_98033_al().func_98233_a("Default game type: " + this.field_71337_q);
InetAddress var3 = null;
if(this.func_71211_k().length() > 0) {
var3 = InetAddress.getByName(this.func_71211_k());
}
if(this.func_71215_F() < 0) {
this.func_71208_b(this.field_71340_o.func_73669_a("server-port", 25565));
}
this.func_98033_al().func_98233_a("Generating keypair");
this.func_71253_a(CryptManager.func_75891_b());
this.func_98033_al().func_98233_a("Starting Minecraft server on " + (this.func_71211_k().length() == 0?"*":this.func_71211_k()) + ":" + this.func_71215_F());
try {
this.field_71336_r = new DedicatedServerListenThread(this, var3, this.func_71215_F());
} catch (IOException var16) {
this.func_98033_al().func_98236_b("**** FAILED TO BIND TO PORT!");
this.func_98033_al().func_98231_b("The exception was: {0}", new Object[]{var16.toString()});
this.func_98033_al().func_98236_b("Perhaps a server is already running on that port?");
return false;
}
if(!this.func_71266_T()) {
this.func_98033_al().func_98236_b("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!");
this.func_98033_al().func_98236_b("The server will make no attempt to authenticate usernames. Beware.");
this.func_98033_al().func_98236_b("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.");
this.func_98033_al().func_98236_b("To change this, set \"online-mode\" to \"true\" in the server.properties file.");
}
this.func_71210_a(new DedicatedPlayerList(this));
long var4 = System.nanoTime();
if(this.func_71270_I() == null) {
this.func_71261_m(this.field_71340_o.func_73671_a("level-name", "world"));
}
String var6 = this.field_71340_o.func_73671_a("level-seed", "");
String var7 = this.field_71340_o.func_73671_a("level-type", "DEFAULT");
String var8 = this.field_71340_o.func_73671_a("generator-settings", "");
long var9 = (new Random()).nextLong();
if(var6.length() > 0) {
try {
long var11 = Long.parseLong(var6);
if(var11 != 0L) {
var9 = var11;
}
} catch (NumberFormatException var15) {
var9 = (long)var6.hashCode();
}
}
WorldType var17 = WorldType.func_77130_a(var7);
if(var17 == null) {
var17 = WorldType.field_77137_b;
}
this.func_71191_d(this.field_71340_o.func_73669_a("max-build-height", 256));
this.func_71191_d((this.func_71207_Z() + 8) / 16 * 16);
this.func_71191_d(MathHelper.func_76125_a(this.func_71207_Z(), 64, 256));
this.field_71340_o.func_73667_a("max-build-height", Integer.valueOf(this.func_71207_Z()));
this.func_98033_al().func_98233_a("Preparing level \"" + this.func_71270_I() + "\"");
this.func_71247_a(this.func_71270_I(), this.func_71270_I(), var9, var17, var8);
long var12 = System.nanoTime() - var4;
String var14 = String.format("%.3fs", new Object[]{Double.valueOf((double)var12 / 1.0E9D)});
this.func_98033_al().func_98233_a("Done (" + var14 + ")! For help, type \"help\" or \"?\"");
if(this.field_71340_o.func_73670_a("enable-query", false)) {
this.func_98033_al().func_98233_a("Starting GS4 status listener");
this.field_71342_m = new RConThreadQuery(this);
this.field_71342_m.func_72602_a();
}
if(this.field_71340_o.func_73670_a("enable-rcon", false)) {
this.func_98033_al().func_98233_a("Starting remote control listener");
this.field_71339_n = new RConThreadMain(this);
this.field_71339_n.func_72602_a();
}
return true;
}
public boolean func_71225_e() {
return this.field_71338_p;
}
public EnumGameType func_71265_f() {
return this.field_71337_q;
}
public int func_71232_g() {
return this.field_71340_o.func_73669_a("difficulty", 1);
}
public boolean func_71199_h() {
return this.field_71340_o.func_73670_a("hardcore", false);
}
protected void func_71228_a(CrashReport p_71228_1_) {
while(this.func_71278_l()) {
this.func_71333_ah();
try {
Thread.sleep(10L);
} catch (InterruptedException var3) {
var3.printStackTrace();
}
}
}
public CrashReport func_71230_b(CrashReport p_71230_1_) {
p_71230_1_ = super.func_71230_b(p_71230_1_);
p_71230_1_.func_85056_g().func_71500_a("Is Modded", new CallableType(this));
p_71230_1_.func_85056_g().func_71500_a("Type", new CallableServerType(this));
return p_71230_1_;
}
protected void func_71240_o() {
System.exit(0);
}
protected void func_71190_q() {
super.func_71190_q();
this.func_71333_ah();
}
public boolean func_71255_r() {
return this.field_71340_o.func_73670_a("allow-nether", true);
}
public boolean func_71193_K() {
return this.field_71340_o.func_73670_a("spawn-monsters", true);
}
public void func_70000_a(PlayerUsageSnooper p_70000_1_) {
p_70000_1_.func_76472_a("whitelist_enabled", Boolean.valueOf(this.func_71334_ai().func_72383_n()));
p_70000_1_.func_76472_a("whitelist_count", Integer.valueOf(this.func_71334_ai().func_72388_h().size()));
super.func_70000_a(p_70000_1_);
}
public boolean func_70002_Q() {
return this.field_71340_o.func_73670_a("snooper-enabled", true);
}
public void func_71331_a(String p_71331_1_, ICommandSender p_71331_2_) {
this.field_71341_l.add(new ServerCommand(p_71331_1_, p_71331_2_));
}
public void func_71333_ah() {
while(!this.field_71341_l.isEmpty()) {
ServerCommand var1 = (ServerCommand)this.field_71341_l.remove(0);
this.func_71187_D().func_71556_a(var1.field_73701_b, var1.field_73702_a);
}
}
public boolean func_71262_S() {
return true;
}
public DedicatedPlayerList func_71334_ai() {
return (DedicatedPlayerList)super.func_71203_ab();
}
public NetworkListenThread func_71212_ac() {
return this.field_71336_r;
}
public int func_71327_a(String p_71327_1_, int p_71327_2_) {
return this.field_71340_o.func_73669_a(p_71327_1_, p_71327_2_);
}
public String func_71330_a(String p_71330_1_, String p_71330_2_) {
return this.field_71340_o.func_73671_a(p_71330_1_, p_71330_2_);
}
public boolean func_71332_a(String p_71332_1_, boolean p_71332_2_) {
return this.field_71340_o.func_73670_a(p_71332_1_, p_71332_2_);
}
public void func_71328_a(String p_71328_1_, Object p_71328_2_) {
this.field_71340_o.func_73667_a(p_71328_1_, p_71328_2_);
}
public void func_71326_a() {
this.field_71340_o.func_73668_b();
}
public String func_71329_c() {
File var1 = this.field_71340_o.func_73665_c();
return var1 != null?var1.getAbsolutePath():"No settings file";
}
public boolean func_71279_ae() {
return this.field_71335_s;
}
public String func_71206_a(EnumGameType p_71206_1_, boolean p_71206_2_) {
return "";
}
public boolean func_82356_Z() {
return this.field_71340_o.func_73670_a("enable-command-block", false);
}
public int func_82357_ak() {
return this.field_71340_o.func_73669_a("spawn-protection", super.func_82357_ak());
}
public boolean func_96290_a(World p_96290_1_, int p_96290_2_, int p_96290_3_, int p_96290_4_, EntityPlayer p_96290_5_) {
if(p_96290_1_.field_73011_w.field_76574_g != 0) {
return false;
} else if(this.func_71334_ai().func_72376_i().isEmpty()) {
return false;
} else if(this.func_71334_ai().func_72353_e(p_96290_5_.func_70005_c_())) {
return false;
} else if(this.func_82357_ak() <= 0) {
return false;
} else {
ChunkCoordinates var6 = p_96290_1_.func_72861_E();
int var7 = MathHelper.func_76130_a(p_96290_2_ - var6.field_71574_a);
int var8 = MathHelper.func_76130_a(p_96290_4_ - var6.field_71573_c);
int var9 = Math.max(var7, var8);
return var9 <= this.func_82357_ak();
}
}
public ILogAgent func_98033_al() {
return this.field_98131_l;
}
public int func_110455_j() {
return this.field_71340_o.func_73669_a("op-permission-level", 4);
}
public void func_143006_e(int p_143006_1_) {
super.func_143006_e(p_143006_1_);
this.field_71340_o.func_73667_a("player-idle-timeout", Integer.valueOf(p_143006_1_));
this.func_71326_a();
}
// $FF: synthetic method
public ServerConfigurationManager func_71203_ab() {
return this.func_71334_ai();
}
@SideOnly(Side.SERVER)
public void func_120011_ar() {
MinecraftServerGui.func_120016_a(this);
this.field_71335_s = true;
}
}
| HATB0T/RuneCraftery | forge/mcp/temp/src/minecraft/net/minecraft/server/dedicated/DedicatedServer.java | Java | lgpl-3.0 | 13,490 |
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'underscore';
import Backbone from 'backbone';
export default Backbone.Model.extend({
defaults: function () {
return {
page: 1,
maxResultsReached: false,
query: {},
facets: []
};
},
nextPage: function () {
var page = this.get('page');
this.set({ page: page + 1 });
},
clearQuery: function (query) {
var q = {};
Object.keys(query).forEach(function (key) {
if (query[key]) {
q[key] = query[key];
}
});
return q;
},
_areQueriesEqual: function (a, b) {
var equal = Object.keys(a).length === Object.keys(b).length;
Object.keys(a).forEach(function (key) {
equal = equal && a[key] === b[key];
});
return equal;
},
updateFilter: function (obj, options) {
var oldQuery = this.get('query'),
query = _.extend({}, oldQuery, obj),
opts = _.defaults(options || {}, { force: false });
query = this.clearQuery(query);
if (opts.force || !this._areQueriesEqual(oldQuery, query)) {
this.setQuery(query);
}
},
setQuery: function (query) {
this.set({ query: query }, { silent: true });
this.set({ changed: true });
this.trigger('change:query');
}
});
| joansmith/sonarqube | server/sonar-web/src/main/js/components/navigator/models/state.js | JavaScript | lgpl-3.0 | 2,070 |
<?php
namespace slapper\entities\other;
use pocketmine\network\protocol\AddEntityPacket;
use pocketmine\network\Network;
use pocketmine\Player;
use pocketmine\entity\Entity;
class SlapperFallingSand extends Entity
{
const NETWORK_ID = 66;
public function getName()
{
return $this->getDataProperty(2);
}
public function spawnTo(Player $player)
{
$pk = new AddEntityPacket();
$pk->eid = $this->getId();
$pk->type = self::NETWORK_ID;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->metadata = [
2 => [4, str_ireplace("{name}", $player->getName(), str_ireplace("{display_name}", $player->getDisplayName(), $player->hasPermission("slapper.seeId") ? $this->getDataProperty(2) . "\n" . \pocketmine\utils\TextFormat::GREEN . "Entity ID: " . $this->getId() : $this->getDataProperty(2)))],
3 => [0, $this->getDataProperty(3)],
15 => [0, 1]
];
if (isset($this->namedtag->BlockID)) {
$pk->metadata[20] = [2, $this->namedtag->BlockID->getValue()];
} else {
$pk->metadata[20] = [2, 1];
}
$player->dataPacket($pk);
parent::spawnTo($player);
}
} | PMPlugins/Development | Slapper_DEV/src/slapper/entities/other/SlapperFallingSand.php | PHP | lgpl-3.0 | 1,317 |
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# 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/>.
class Range:
"""A class that mimic's the built-in range class."""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance.
Semantics is similar to built-in range class.
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop is None: # special case of range(n)
start, stop = 0, start # should be treated as if range(0,n)
# calculate the effective length once
self._length = max(0, (stop - start + step - 1) // step)
# need knowledge of start and step (but not stop) to support __getitem__
self._start = start
self._step = step
def __len__(self):
"""Return number of entries in the range."""
return self._length
def __getitem__(self, k):
"""Return entry at index k (using standard interpretation if negative)."""
if k < 0:
k += len(self) # attempt to convert negative index
if not 0 <= k < self._length:
raise IndexError('index out of range')
return self._start + k * self._step
| consultit/Ely | ely/direct/data_structures_and_algorithms/ch02/range.py | Python | lgpl-3.0 | 2,023 |
package zonefile_test
import (
"bytes"
"fmt"
"github.com/bwesterb/go-zonefile"
"testing"
)
// XXX more tests for AddEntry.
// XXX test Value() and SetValue()
// Loading and saving a zonefile shouldn't do anything
func TestLoadThenSave(t *testing.T) {
for i, test := range tests {
z, e := zonefile.Load([]byte(test))
if e != nil {
t.Fatal(i, "error loading:", e.LineNo(), e)
}
if !bytes.Equal(z.Save(), []byte(test)) {
t.Fatal("Save o Load != identity")
}
}
}
func TestSetAttributes(t *testing.T) {
zf, err := zonefile.Load([]byte(" IN A 1.2.3.4"))
if err != nil {
t.Fatal("Couldn't parse simple zonefile")
}
zf.Entries()[0].SetDomain([]byte("test"))
if !bytes.Equal(zf.Save(), []byte("test IN A 1.2.3.4")) {
t.Fatal("Setting domain failed")
}
zf.Entries()[0].SetDomain([]byte("test2"))
if !bytes.Equal(zf.Save(), []byte("test2 IN A 1.2.3.4")) {
t.Fatal("Setting domain failed")
}
zf.Entries()[0].SetDomain([]byte(""))
if !bytes.Equal(zf.Save(), []byte(" IN A 1.2.3.4")) {
t.Fatal("Setting domain failed")
}
zf.Entries()[0].SetClass([]byte(""))
if !bytes.Equal(zf.Save(), []byte(" A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
zf.Entries()[0].SetClass([]byte("IN"))
if !bytes.Equal(zf.Save(), []byte(" IN A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
zf.Entries()[0].SetDomain([]byte("test4"))
if !bytes.Equal(zf.Save(), []byte("test4 IN A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
zf.Entries()[0].SetClass([]byte(""))
if !bytes.Equal(zf.Save(), []byte("test4 A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
zf.Entries()[0].SetTTL(12)
if !bytes.Equal(zf.Save(), []byte("test4 12 A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
zf.Entries()[0].SetTTL(14)
if !bytes.Equal(zf.Save(), []byte("test4 14 A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
if *zf.Entries()[0].TTL() != 14 {
t.Fatal("TTL wasn't properly set")
}
zf.Entries()[0].RemoveTTL()
if !bytes.Equal(zf.Save(), []byte("test4 A 1.2.3.4")) {
t.Fatal("Setting class failed")
}
}
func ExampleLoad() {
zf, err := zonefile.Load([]byte(
"@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (\n" +
" 1406291485 ;serial\n" +
" 3600 ;refresh\n" +
" 600 ;retry\n" +
" 604800 ;expire\n" +
" 86400 ;minimum ttl\n" +
")\n" +
"\n" +
"@ NS NS1.NAMESERVER.NET.\n" +
"@ NS NS2.NAMESERVER.NET.\n"))
if err != nil {
fmt.Println("Parsing error", err, "on line", err.LineNo())
return
}
fmt.Println(len(zf.Entries()))
// Output: 3
}
func ExampleParseEntry() {
entry, err := zonefile.ParseEntry([]byte(" IN MX 100 alpha.example.com."))
if err != nil {
fmt.Println("Parsing error", err, "on line", err.LineNo())
return
}
fmt.Println(entry)
// Output: <Entry dom="" ttl="" cls="IN" typ="MX" ["100" "alpha.example.com."]>
}
func ExampleNew() {
z := zonefile.New()
z.AddA("", "3.2.3.2")
z.AddA("www", "1.2.3.4")
z.AddA("irc", "2.2.2.2").SetTTL(12)
fmt.Println(z)
// Output: <Zonefile [<Entry dom="" ttl="" cls="" typ="" ["3.2.3.2"]> <Entry dom="www" ttl="" cls="" typ="" ["1.2.3.4"]> <Entry dom="irc" ttl="12" cls="" typ="" ["2.2.2.2"]>]>
}
func ExampleZonefile_AddA() {
z := zonefile.New()
z.AddA("", "3.2.3.2")
z.AddA("www", "1.2.3.4")
z.AddA("irc", "2.2.2.2").SetTTL(12)
fmt.Println(z)
// Output: <Zonefile [<Entry dom="" ttl="" cls="" typ="" ["3.2.3.2"]> <Entry dom="www" ttl="" cls="" typ="" ["1.2.3.4"]> <Entry dom="irc" ttl="12" cls="" typ="" ["2.2.2.2"]>]>
}
func ExampleZonefile_AddEntry() {
z := zonefile.New()
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
z.AddEntry(entry)
fmt.Println(z)
// Output: <Zonefile [<Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>]>
}
func ExampleZonefile_Save() {
z := zonefile.New()
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
z.AddEntry(entry)
entry, _ = zonefile.ParseEntry([]byte("www IN A 2.1.4.3"))
z.AddEntry(entry)
fmt.Println(string(z.Save()))
// Output: irc IN A 1.2.3.4
// www IN A 2.1.4.3
}
func ExampleZonefile_Entries() {
zf, err := zonefile.Load([]byte(`
$TTL 3600
@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (
1406291485 ;serial
3600 ;refresh
600 ;retry
604800 ;expire
86400 ;minimum ttl
)
A 1.1.1.1
@ A 127.0.0.1
www A 127.0.0.1
mail A 127.0.0.1
A 1.2.3.4
tst 300 IN A 101.228.10.127;this is a comment`))
if err != nil {
fmt.Println("Error parsing zonefile:", err)
return
}
for _, e := range zf.Entries() {
fmt.Println(e)
}
// Output: <Entry cmd="$TTL" ["3600"]>
// <Entry dom="@" ttl="" cls="IN" typ="SOA" ["NS1.NAMESERVER.NET." "HOSTMASTER.MYDOMAIN.COM." "1406291485" "3600" "600" "604800" "86400"]>
// <Entry dom="" ttl="" cls="" typ="A" ["1.1.1.1"]>
// <Entry dom="@" ttl="" cls="" typ="A" ["127.0.0.1"]>
// <Entry dom="www" ttl="" cls="" typ="A" ["127.0.0.1"]>
// <Entry dom="mail" ttl="" cls="" typ="A" ["127.0.0.1"]>
// <Entry dom="" ttl="" cls="" typ="A" ["1.2.3.4"]>
// <Entry dom="tst" ttl="300" cls="IN" typ="A" ["101.228.10.127"]>
}
func ExampleEntry_SetValue() {
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
fmt.Println(entry)
entry.SetValue(0, []byte("4.3.2.1"))
fmt.Println(entry)
// Output: <Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="irc" ttl="" cls="IN" typ="A" ["4.3.2.1"]>
}
func ExampleEntry_RemoveTTL() {
entry, _ := zonefile.ParseEntry([]byte("irc 12 IN A 1.2.3.4"))
fmt.Println(entry)
entry.RemoveTTL()
fmt.Println(entry)
// Output: <Entry dom="irc" ttl="12" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
}
func ExampleEntry_SetTTL() {
entry, _ := zonefile.ParseEntry([]byte("irc 12 IN A 1.2.3.4"))
fmt.Println(entry)
entry.SetTTL(14)
fmt.Println(entry)
// Output: <Entry dom="irc" ttl="12" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="irc" ttl="14" cls="IN" typ="A" ["1.2.3.4"]>
}
func ExampleEntry_Domain() {
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
fmt.Printf("%q\n", entry.Domain())
entry, _ = zonefile.ParseEntry([]byte(" IN A 4.3.2.1"))
fmt.Printf("%q\n", entry.Domain())
// Output: "irc"
// ""
}
func ExampleEntry_Class() {
entry, _ := zonefile.ParseEntry([]byte("irc A 1.2.3.4"))
fmt.Printf("%q\n", entry.Class())
entry, _ = zonefile.ParseEntry([]byte("irc IN A 4.3.2.1"))
fmt.Printf("%q\n", entry.Class())
// Output: ""
// "IN"
}
func ExampleEntry_Type() {
entry, _ := zonefile.ParseEntry([]byte("irc A 1.2.3.4"))
fmt.Printf("%q\n", entry.Type())
entry, _ = zonefile.ParseEntry([]byte("irc AAAA ::1"))
fmt.Printf("%q\n", entry.Type())
// Output: "A"
// "AAAA"
}
func ExampleEntry_TTL() {
entry, _ := zonefile.ParseEntry([]byte("irc A 1.2.3.4"))
fmt.Printf("%v\n", entry.TTL() == nil)
entry, _ = zonefile.ParseEntry([]byte("irc 12 A 1.2.3.4"))
fmt.Printf("%v\n", *entry.TTL())
// Output: true
// 12
}
func ExampleEntry_Command() {
entry, _ := zonefile.ParseEntry([]byte("$TTL 123"))
fmt.Printf("%q\n", entry.Command())
// Output: "$TTL"
}
func ExampleEntry_Values() {
entry, _ := zonefile.ParseEntry([]byte(`
@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (
1406291485 ;serial
3600 ;refresh
600 ;retry
604800 ;expire
86400 ;minimum ttl
)`))
fmt.Printf("%q\n", entry.Values())
// Output: ["NS1.NAMESERVER.NET." "HOSTMASTER.MYDOMAIN.COM." "1406291485" "3600" "600" "604800" "86400"]
}
func ExampleEntry_SetDomain() {
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
fmt.Println(entry)
entry.SetDomain([]byte(""))
fmt.Println(entry)
entry.SetDomain([]byte("chat"))
fmt.Println(entry)
// Output: <Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="chat" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
}
func ExampleEntry_SetClass() {
entry, _ := zonefile.ParseEntry([]byte("irc IN A 1.2.3.4"))
fmt.Println(entry)
entry.SetClass([]byte(""))
fmt.Println(entry)
entry.SetClass([]byte("IN"))
fmt.Println(entry)
// Output: <Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
// <Entry dom="irc" ttl="" cls="" typ="A" ["1.2.3.4"]>
// <Entry dom="irc" ttl="" cls="IN" typ="A" ["1.2.3.4"]>
}
var tests = [...]string{`$ORIGIN MYDOMAIN.COM.
$TTL 3600
@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (
1406291485 ;serial
3600 ;refresh
600 ;retry
604800 ;expire
86400 ;minimum ttl
)
@ NS NS1.NAMESERVER.NET.
@ NS NS2.NAMESERVER.NET.
@ MX 0 mail1
@ MX 10 mail2
A 1.1.1.1
@ A 127.0.0.1
www A 127.0.0.1
mail A 127.0.0.1
A 1.2.3.4
tst 300 IN A 101.228.10.127;this is a comment
@ AAAA ::1
mail AAAA 2001:db8::1
mail1 CNAME mail
mail2 CNAME mail
treefrog.ca. IN TXT "v=spf1 a mx a:mail.treefrog.ca a:webmail.treefrog.ca ip4:76.75.250.33 ?all"
treemonkey.ca. IN TXT "v=DKIM1\; k=rsa\; p=MIGf..."`,
`$ORIGIN 0.168.192.IN-ADDR.ARPA.
$TTL 3600
@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (
1406291485 ;serial
3600 ;refresh
600 ;retry
604800 ;expire
86400 ;minimum ttl
)
@ NS NS1.NAMESERVER.NET.
@ NS NS2.NAMESERVER.NET.
1 PTR HOST1.MYDOMAIN.COM.
2 PTR HOST2.MYDOMAIN.COM.
$ORIGIN 30.168.192.in-addr.arpa.
3 PTR HOST3.MYDOMAIN.COM.
4 PTR HOST4.MYDOMAIN.COM.
PTR HOST5.MYDOMAIN.COM.
$ORIGIN 168.192.in-addr.arpa.
10.3 PTR HOST3.MYDOMAIN.COM.
10.4 PTR HOST4.MYDOMAIN.COM.`,
`$ORIGIN 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.
$TTL 3600
@ IN SOA NS1.NAMESERVER.NET. HOSTMASTER.MYDOMAIN.COM. (
1406291485 ;serial
3600 ;refresh
600 ;retry
604800 ;expire
86400 ;minimum ttl
)
@ NS NS1.NAMESERVER.NET.
@ NS NS2.NAMESERVER.NET.
1 PTR HOST1.MYDOMAIN.COM.
2 PTR HOST2.MYDOMAIN.COM.`,
`$ORIGIN example.com. ; designates the start of this zone file in the namespace
$TTL 1h ; default expiration time of all resource records without their own TTL value
example.com. IN SOA ns.example.com. username.example.com. ( 2007120710 1d 2h 4w 1h )
example.com. IN NS ns ; ns.example.com is a nameserver for example.com
example.com. IN NS ns.somewhere.example. ; ns.somewhere.example is a backup nameserver for example.com
example.com. IN MX 10 mail.example.com. ; mail.example.com is the mailserver for example.com
@ IN MX 20 mail2.example.com. ; equivalent to above line, "@" represents zone origin
@ IN MX 50 mail3 ; equivalent to above line, but using a relative host name
example.com. IN A 192.0.2.1 ; IPv4 address for example.com
IN AAAA 2001:db8:10::1 ; IPv6 address for example.com
ns IN A 192.0.2.2 ; IPv4 address for ns.example.com
IN AAAA 2001:db8:10::2 ; IPv6 address for ns.example.com
www IN CNAME example.com. ; www.example.com is an alias for example.com
wwwtest IN CNAME www ; wwwtest.example.com is another alias for www.example.com
mail IN A 192.0.2.3 ; IPv4 address for mail.example.com
mail2 IN A 192.0.2.4 ; IPv4 address for mail2.example.com
mail3 IN A 192.0.2.5 ; IPv4 address for mail3.example.com`}
| bwesterb/go-zonefile | zonefile_test.go | GO | lgpl-3.0 | 11,253 |
//==============================================================================
// Brief : Logging Facilities
// Authors : Bruno Santos <bsantos@av.it.pt>
//------------------------------------------------------------------------------
// ODTONE - Open Dot Twenty One
//
// Copyright (C) 2009-2012 Universidade Aveiro
// Copyright (C) 2009-2012 Instituto de Telecomunicações - Pólo Aveiro
//
// This software is distributed under a license. The full license
// agreement can be found in the file LICENSE in this distribution.
// This software may not be copied, modified, sold or distributed
// other than expressed in the named license agreement.
//
// This software is distributed without any warranty.
//==============================================================================
#include <odtone/debug.hpp>
#include <odtone/logger.hpp>
#include <boost/make_shared.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace odtone {
///////////////////////////////////////////////////////////////////////////////
/**
* Construct a logger by copying it from another logger.
*
* @param name Logger's name.
* @param log Logger to copy.
*/
logger::logger(char const* const name, logger& log)
: _lock(log._lock), _name(name), _sink(log._sink), _level(log._level)
{
ODTONE_ASSERT(name);
}
/**
* Construct a logger.
*
* @param name Logger's name.
* @param sink std::ostream which defines how the logger will write and
* format output.
*/
logger::logger(char const* const name, std::ostream& sink)
: _lock(boost::make_shared<boost::mutex>()), _name(name), _sink(sink), _level(0)
{
ODTONE_ASSERT(name);
}
/**
* Destruct a logger.
*/
logger::~logger()
{
}
/**
* Set the output level. Each logger has a level associated with it.
* This reflects the maximum level that the logger cares about. So, if the
* logger level is set to 2 it only cares about log messages belonging
* to level 0, 1 and 2.
*
* @param n Logger level.
*/
void logger::level(uint n)
{
_level = n;
}
/**
* Get the level configuration. Each logger has a level associated with it.
* This reflects the maximum level that the logger cares about. So, if the
* logger level is set to 2 it only cares about log messages belonging
* to level 0, 1 and 2.
*
* @return The logger level.
*/
uint logger::level() const
{
return _level;
}
/**
* Get the std::ostream associated with the logger.
*
* @return The std::ostream associated with the logger.
*/
std::ostream& logger::sink() const
{
return _sink;
}
///////////////////////////////////////////////////////////////////////////////
} /* namespace odtone */
// EOF ////////////////////////////////////////////////////////////////////////
| ATNoG/EMICOM | lib/odtone/logger.cpp | C++ | lgpl-3.0 | 2,744 |
namespace boost { namespace logging {
/**
@page common_usage_steps_fd Common steps when using Formatters and destinations
\n
<b>The easy way, use Named Formatters and Destinations</b>
You use a string to specify Formatters, and a string to specify Destinations. Thus, you use the @ref boost::logging::writer::named_write "writer::named_write".
First, the examples: @ref scenarios_code_mom "example 1", @ref scenarios_code_noo "example 2"
- Step 1: (optional) Specify your @ref BOOST_LOG_FORMAT_MSG "format message class" and/or @ref BOOST_LOG_DESTINATION_MSG "destination message class". By default, it's <tt>std::(w)string</tt>.
You'll use this when you want a @ref optimize "optimize string class". Or, when @ref boost::logging::tag "using tags"
- Step 2: Specify your logging and filter classes
- Step 2A: Typedef your logger as <tt>typedef boost::logging::named_logger<>::type logger_type;</tt> and @ref typedefing_your_filter "typedef your filter class"
- Step 2B: Declare the @ref declare_define "filters and loggers" you'll use (in a header file)
- Step 2C: Define the @ref declare_define "filters and loggers" you'll use (in a source file). We need this separation
(into declaring and defining the logs/filters), in order to @ref macros_compile_time "make compilation times fast".
- Step 3: Define the @ref defining_logger_macros "macros through which you'll do logging"
- Step 4: Initialize the logger.
- Step 4A: Set the @ref boost::logging::writer::named_write "formatters and destinations", as strings.
- Step 4B: @ref boost::logging::logger_base::mark_as_initialized "Mark the logger as initialized"
\n
<b>The manual way</b>
First, the examples: @ref common_your_scenario_code "example 1", @ref common_your_mul_logger_one_filter "example 2"
- Step 1: (optional) Specify your @ref BOOST_LOG_FORMAT_MSG "format message class" and/or @ref BOOST_LOG_DESTINATION_MSG "destination message class". By default, it's <tt>std::(w)string</tt>.
You'll use this when you want a @ref optimize "optimize string class". Or, when @ref boost::logging::tag "using tags"
- Step 2: (optional) Specify your @ref boost::logging::manipulator "formatter & destination base classes"
- Step 3: Specify your logging and filter classes
- Step 3A: @ref typedefing_your_filter "Typedef your filter class(es)" and @ref typedefing_your_logger "Typedef your logger class(es)"
- Step 3B: Declare the @ref declare_define "filters and loggers" you'll use (in a header file)
- Step 3C: Define the @ref declare_define "filters and loggers" you'll use (in a source file). We need this separation
(into declaring and defining the logs/filters), in order to @ref macros_compile_time "make compilation times fast".
- Step 4: Define the @ref defining_logger_macros "macros through which you'll do logging"
- Step 5: Initialize the logger
- Step 5A: Add @ref boost::logging::manipulator "formatters and destinations". That is, how the message is to be formatted...
- Step 5B: @ref boost::logging::logger_base::mark_as_initialized "Mark the logger as initialized"
*/
}}
| laz2/sc-core | thirdparty/log2/boost/logging/detail/raw_doc/common_usage_steps_fd.hpp | C++ | lgpl-3.0 | 3,085 |
class CreateArticles < ActiveRecord::Migration
def self.up
Cms::ContentType.create!(:name => "BcmsMy401kLibrary::Article", :group_name => "My401k Product")
end
def self.down
raise "down migrate this manually"
end
end
| dcvezzani/massive-octo-lana | db/migrate/20130323203723_create_articles.rb | Ruby | lgpl-3.0 | 234 |
/* --------------------------------------------------------------------------
* Copyrights
*
* Portions created by or assigned to Cursive Systems, Inc. are
* Copyright (c) 2002-2008 Cursive Systems, Inc. All Rights Reserved. Contact
* information for Cursive Systems, Inc. is available at
* http://www.cursive.net/.
*
* License
*
* Jabber-Net is licensed under the LGPL.
* See LICENSE.txt for details.
* --------------------------------------------------------------------------*/
using System;
using System.Collections;
using bedrock.util;
namespace bedrock.collections
{
/// <summary>
/// A basic balanced tree implementation.
/// </summary>
[SVN(@"$Id: Tree.cs 724 2008-08-06 18:09:25Z hildjj $")]
public class Tree : IEnumerable, IDictionary
{
private Node root = null;
private int size = 0;
private int modCount = 0;
private IComparer comparator = System.Collections.Comparer.Default;
//private bool readOnly = false;
//private bool synch = false;
/// <summary>
/// Construct an empty tree
/// </summary>
public Tree()
{
//
// TODO: Add Constructor Logic here
//
}
#region IEnumerable
/// <summary>
/// Iterate over the tree
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return new TreeEnumerator(this);
}
#endregion
#region ICollection
/// <summary>
/// The number of items in the tree.
/// </summary>
public int Count
{
get
{
return size;
}
}
/// <summary>
/// Gets a value indicating whether access to the tree is synchronized in thread-safe mode.
/// Currently, it only returns false.
/// </summary>
public bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Copies the values from the tree to the specified array in the order of the keys.
/// </summary>
/// <param name="array">The array to copy into</param>
/// <param name="index">The index to start at</param>
public void CopyTo(System.Array array, int index)
{
int i = index;
foreach (DictionaryEntry o in this)
{
array.SetValue(o.Value, i++);
}
}
/// <summary>
/// Gets an object that can be used to sychronize access to the tree. For now, it returns null.
/// </summary>
public object SyncRoot
{
get
{
return null;
}
}
#endregion
#region IDictionary
/// <summary>
/// Add an item to the tree
/// </summary>
/// <param name="key">The key for the item</param>
/// <param name="value">The data to store with this key</param>
/// <exception cref="ArgumentException">Thrown if the same key is added twice</exception>
/// <exception cref="ArgumentNullException">Thrown if key is null</exception>
public void Add(object key,object value)
{
if (key == null)
throw new ArgumentNullException("key");
Node n = root;
if (n == null)
{
sizeUp();
root = new Node(key, value, null);
return;
}
while (true)
{
int cmp = comparator.Compare(key, n.key);
if (cmp == 0)
{
//n.value = value;
//return;
throw new ArgumentException("Can't add the same key twice", "key");
}
else if (cmp < 0)
{
if (n.left != null)
{
n = n.left;
}
else
{
sizeUp();
n.left = new Node(key, value, n);
fixAfterInsertion(n.left);
return;
}
}
else // cmp > 0
{
if (n.right != null) {
n = n.right;
}
else
{
sizeUp();
n.right = new Node(key, value, n);
fixAfterInsertion(n.right);
return;
}
}
}
}
/// <summary>
/// Remove all values from the tree.
/// </summary>
public void Clear()
{
modCount++;
size = 0;
root = null;
}
/// <summary>
/// Determines if the specified key exists in the tree.
/// </summary>
/// <param name="key">The key to search for</param>
/// <returns>True if the key exists in the tree; otherwise false.</returns>
public bool Contains(object key)
{
return getNode(key) != null;
}
/// <summary>
/// Returns a dictionary enumerator.
/// </summary>
/// <returns>A dictionary enumerator</returns>
public IDictionaryEnumerator GetEnumerator()
{
return new TreeEnumerator(this);
}
/// <summary>
/// Remove the element from the tree associated
/// with this key, possibly rebalancing.
/// </summary>
/// <param name="key"></param>
public void Remove(object key)
{
Node n = getNode(key);
if (n == null)
{
return;
}
sizeDown();
// If strictly internal, first swap position with successor.
if ((n.left != null) && (n.right != null))
{
Node s = successor(n);
swapPosition(s, n);
}
// Start fixup at replacement node, if it exists.
Node replacement = ((n.left != null) ? n.left : n.right);
if (replacement != null)
{
// Link replacement to parent
replacement.parent = n.parent;
if (n.parent == null)
root = replacement;
else if (n == n.parent.left)
n.parent.left = replacement;
else
n.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
n.left = n.right = n.parent = null;
// Fix replacement
if (n.color == NodeColor.BLACK)
fixAfterDeletion(replacement);
}
else if (n.parent == null)
{
root = null;
}
else
{
if (n.color == NodeColor.BLACK)
fixAfterDeletion(n);
if (n.parent != null)
{
if (n == n.parent.left)
n.parent.left = null;
else if (n == n.parent.right)
n.parent.right = null;
n.parent = null;
}
}
}
/// <summary>
/// Retrieves the value associated with the given key.
/// </summary>
public object this[object key]
{
get
{
Node n = getNode(key);
if (n == null)
return null;
return n.value;
}
set
{
Add(key, value);
}
}
/// <summary>
/// Retrieve a list of keys.
/// </summary>
public ICollection Keys
{
get
{
object[] keys = new object[Count];
int i=0;
if (root == null)
return keys;
Node n = first(root);
while (n != null)
{
keys[i++] = n.key;
n = successor(n);
}
return keys;
}
}
/// <summary>
/// Retrieves a list of values.
/// </summary>
public ICollection Values
{
get
{
object[] vals = new object[Count];
int i=0;
Node n = first(root);
while (n != null)
{
vals[i++] = n.value;
n = successor(n);
}
return vals;
}
}
/// <summary>
/// Always returns false for now.
/// </summary>
public bool IsFixedSize
{
get
{
return false;
}
}
/// <summary>
/// Always returns false for now.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
#endregion
#region Object
/// <summary>
/// Retrieves a string representation of the tree.
/// </summary>
/// <returns>string in the format '{key1}={value1}, {key2}={value2}, ...'</returns>
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
bool f = true;
for (Node n = first(root); n != null; n = successor(n))
{
if (!f)
{
sb.Append(", ");
}
else
{
f = false;
}
sb.AppendFormat("{0}={1}", n.key, n.value);
}
return sb.ToString();
}
#endregion
/// <summary>
/// Retrieve a string representation of the tree.
/// Nice for debugging, but otherwise useless.
/// </summary>
/// <returns></returns>
public string Structure()
{
return root.ToString();
}
#region hidden
private static Node first(Node n)
{
if (n != null)
{
while (n.left != null)
n = n.left;
}
return n;
}
private static Node successor(Node t)
{
if (t == null)
return null;
if (t.right != null)
{
Node n = t.right;
while (n.left != null)
n = n.left;
return n;
}
Node p = t.parent;
Node ch = t;
while (p != null && ch == p.right)
{
ch = p;
p = p.parent;
}
return p;
}
private Node getNode(object key)
{
Node n = root;
while (n != null)
{
int cmp = comparator.Compare(key, n.key);
if (cmp == 0)
return n;
else if (cmp < 0)
n = n.left;
else
n = n.right;
}
return null;
}
private void swapPosition(Node x, Node y)
{
Node px = x.parent;
Node lx = x.left;
Node rx = x.right;
Node py = y.parent;
Node ly = y.left;
Node ry = y.right;
bool xWasLeftChild = (px != null) && (x == px.left);
bool yWasLeftChild = (py != null) && (y == py.left);
if (x == py)
{
x.parent = y;
if (yWasLeftChild)
{
y.left = x;
y.right = rx;
}
else
{
y.right = x;
y.left = lx;
}
}
else
{
x.parent = py;
if (py != null)
{
if (yWasLeftChild)
py.left = x;
else
py.right = x;
}
y.left = lx;
y.right = rx;
}
if (y == px)
{
y.parent = x;
if (xWasLeftChild)
{
x.left = y;
x.right = ry;
}
else
{
x.right = y;
x.left = ly;
}
}
else
{
y.parent = px;
if (px != null)
{
if (xWasLeftChild)
px.left = y;
else
px.right = y;
}
x.left = ly;
x.right = ry;
}
if (x.left != null)
x.left.parent = x;
if (x.right != null)
x.right.parent = x;
if (y.left != null)
y.left.parent = y;
if (y.right != null)
y.right.parent = y;
NodeColor c = x.color;
x.color = y.color;
y.color = c;
if (root == x)
root = y;
else if (root == y)
root = x;
}
private static NodeColor colorOf(Node n)
{
return (n == null ? NodeColor.BLACK : n.color);
}
private static Node parentOf(Node n)
{
return (n == null ? null: n.parent);
}
private static void setColor(Node n, NodeColor c)
{
if (n != null)
n.color = c;
}
private static Node leftOf(Node n)
{
return (n == null)? null: n.left;
}
private static Node rightOf(Node n)
{
return (n == null)? null: n.right;
}
private void rotateLeft(Node n)
{
Node r = n.right;
n.right = r.left;
if (r.left != null)
r.left.parent = n;
r.parent = n.parent;
if (n.parent == null)
root = r;
else if (n.parent.left == n)
n.parent.left = r;
else
n.parent.right = r;
r.left = n;
n.parent = r;
}
private void rotateRight(Node n)
{
Node l = n.left;
n.left = l.right;
if (l.right != null)
l.right.parent = n;
l.parent = n.parent;
if (n.parent == null)
root = l;
else if (n.parent.right == n)
n.parent.right = l;
else
n.parent.left = l;
l.right = n;
n.parent = l;
}
private void fixAfterInsertion(Node n)
{
n.color = NodeColor.RED;
while ((n != null) &&
(n != root) &&
(n.parent.color == NodeColor.RED))
{
if (parentOf(n) == leftOf(parentOf(parentOf(n))))
{
Node y = rightOf(parentOf(parentOf(n)));
if (colorOf(y) == NodeColor.RED)
{
setColor(parentOf(n), NodeColor.BLACK);
setColor(y, NodeColor.BLACK);
setColor(parentOf(parentOf(n)), NodeColor.RED);
n = parentOf(parentOf(n));
}
else
{
if (n == rightOf(parentOf(n)))
{
n = parentOf(n);
rotateLeft(n);
}
setColor(parentOf(n), NodeColor.BLACK);
setColor(parentOf(parentOf(n)), NodeColor.RED);
if (parentOf(parentOf(n)) != null)
rotateRight(parentOf(parentOf(n)));
}
}
else
{
Node y = leftOf(parentOf(parentOf(n)));
if (colorOf(y) == NodeColor.RED)
{
setColor(parentOf(n), NodeColor.BLACK);
setColor(y, NodeColor.BLACK);
setColor(parentOf(parentOf(n)), NodeColor.RED);
n = parentOf(parentOf(n));
}
else
{
if (n == leftOf(parentOf(n)))
{
n = parentOf(n);
rotateRight(n);
}
setColor(parentOf(n), NodeColor.BLACK);
setColor(parentOf(parentOf(n)), NodeColor.RED);
if (parentOf(parentOf(n)) != null)
rotateLeft(parentOf(parentOf(n)));
}
}
}
root.color = NodeColor.BLACK;
}
private void fixAfterDeletion(Node x)
{
while ((x != root) && (colorOf(x) == NodeColor.BLACK))
{
if (x == leftOf(parentOf(x)))
{
Node sib = rightOf(parentOf(x));
if (colorOf(sib) == NodeColor.RED)
{
setColor(sib, NodeColor.BLACK);
setColor(parentOf(x), NodeColor.RED);
rotateLeft(parentOf(x));
sib = rightOf(parentOf(x));
}
if ((colorOf(leftOf(sib)) == NodeColor.BLACK) &&
(colorOf(rightOf(sib)) == NodeColor.BLACK))
{
setColor(sib, NodeColor.RED);
x = parentOf(x);
}
else
{
if (colorOf(rightOf(sib)) == NodeColor.BLACK)
{
setColor(leftOf(sib), NodeColor.BLACK);
setColor(sib, NodeColor.RED);
rotateRight(sib);
sib = rightOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), NodeColor.BLACK);
setColor(rightOf(sib), NodeColor.BLACK);
rotateLeft(parentOf(x));
x = root;
}
}
else
{
Node sib = leftOf(parentOf(x));
if (colorOf(sib) == NodeColor.RED)
{
setColor(sib, NodeColor.BLACK);
setColor(parentOf(x), NodeColor.RED);
rotateRight(parentOf(x));
sib = leftOf(parentOf(x));
}
if (colorOf(rightOf(sib)) == NodeColor.BLACK &&
colorOf(leftOf(sib)) == NodeColor.BLACK)
{
setColor(sib, NodeColor.RED);
x = parentOf(x);
}
else
{
if (colorOf(leftOf(sib)) == NodeColor.BLACK) {
setColor(rightOf(sib), NodeColor.BLACK);
setColor(sib, NodeColor.RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), NodeColor.BLACK);
setColor(leftOf(sib), NodeColor.BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x, NodeColor.BLACK);
}
private void sizeUp() { modCount++; size++; }
private void sizeDown() { modCount++; size--; }
#endregion
#region node
private enum NodeColor : byte
{
RED,
BLACK
}
private class Node
{
public object key;
public object value;
public Node left = null;
public Node right = null;
public Node parent;
public NodeColor color = NodeColor.BLACK;
public Node(object key, object value, Node parent)
{
this.key = key;
this.value = value;
this.parent = parent;
}
public override bool Equals(object o)
{
Node n = o as Node;
if (n == null)
{
return false;
}
return (key == n.key) && (value == n.value);
}
public override int GetHashCode()
{
return key.GetHashCode();
}
public override string ToString()
{
//return key + "=" + value + " (" + color + ")";
if ((left==null) && (right==null))
{
return key.ToString();
}
return key + " (" +
((left == null) ? "null" : left.ToString()) + "," +
((right == null) ? "null" : right.ToString()) + ")";
}
}
#endregion
#region enumerator
private class TreeEnumerator : IDictionaryEnumerator
{
private Tree tree = null;
private Node current = null;
private int mods = -1;
public TreeEnumerator(Tree t) : this(t, t.root)
{
}
public TreeEnumerator(Tree t, Node n)
{
tree = t;
mods = t.modCount;
// foreach calls MoveNext before starting. Create a dummy node before the first one.
current = new Node(null, null, null);
current.right = first(n);
}
public object Current
{
get
{
if (tree.modCount != mods)
{
throw new InvalidOperationException("Changed list during iterator");
}
return Entry;
}
}
public bool MoveNext()
{
current = successor(current);
return current != null;
}
public void Reset()
{
current = first(tree.root);
mods = tree.modCount;
}
public object Key
{
get
{
if (tree.modCount != mods)
{
throw new InvalidOperationException("Changed list during iterator");
}
return current.key;
}
}
public object Value
{
get
{
if (tree.modCount != mods)
{
throw new InvalidOperationException("Changed list during iterator");
}
return current.value;
}
}
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(current.key, current.value);
}
}
}
#endregion
}
}
| goldpicker/jabber-net | bedrock/collections/Tree.cs | C# | lgpl-3.0 | 25,416 |
class Epics::HPD < Epics::GenericRequest
def header
{
:@authenticate => true,
static: {
"HostID" => host_id,
"Nonce" => nonce,
"Timestamp" => timestamp,
"PartnerID" => partner_id,
"UserID" => user_id,
"Product" => {
:@Language => "de",
:content! => "EPICS - a ruby ebics kernel"
},
"OrderDetails" => {
"OrderType" => "HPD",
"OrderAttribute" => "DZHNN",
"StandardOrderParams/" => ""
},
"BankPubKeyDigests" => {
"Authentication" => {
:@Version => "X002",
:@Algorithm => "http://www.w3.org/2001/04/xmlenc#sha256",
:content! => client.bank_x.public_digest
},
"Encryption" => {
:@Version => "E002",
:@Algorithm => "http://www.w3.org/2001/04/xmlenc#sha256",
:content! => client.bank_e.public_digest
}
},
"SecurityMedium" => "0000"
},
"mutable" => {
"TransactionPhase" => "Initialisation"
}
}
end
end
| vikewoods/epics | lib/epics/hpd.rb | Ruby | lgpl-3.0 | 1,102 |
/**
* This file is part of the CRISTAL-iSE kernel.
* Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* http://www.fsf.org/licensing/licenses/lgpl.html
*/
package org.cristalise.kernel.lookup;
public class InvalidPathException extends Exception {
private static final long serialVersionUID = -1980471517943177915L;
public InvalidPathException() {
super();
}
public InvalidPathException(String msg) {
super(msg);
}
}
| cristal-ise/kernel | src/main/java/org/cristalise/kernel/lookup/InvalidPathException.java | Java | lgpl-3.0 | 1,253 |
<?php
namespace AdminComment\Loop;
use AdminComment\Model\AdminComment;
use AdminComment\Model\AdminCommentQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Type;
class AdminCommentLoop extends BaseLoop implements PropelSearchLoopInterface
{
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createAlphaNumStringTypeArgument('element_key'),
Argument::createIntListTypeArgument('element_id'),
new Argument(
'order',
new Type\TypeCollection(
new Type\EnumListType(
[
'id',
'id_reverse',
'created',
'created_reverse',
'updated',
'updated_reverse'
]
)
),
'manual'
)
);
}
public function buildModelCriteria()
{
$search = AdminCommentQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$elementKey = $this->getElementKey();
if (null !== $elementKey) {
$search->filterByElementKey($elementKey, Criteria::IN);
}
$elementId = $this->getElementId();
if (null !== $elementId) {
$search->filterByElementId($elementId, Criteria::IN);
}
$orders = $this->getOrder();
if (null !== $orders) {
foreach ($orders as $order) {
switch ($order) {
case "id":
$search->orderById(Criteria::ASC);
break;
case "id_reverse":
$search->orderById(Criteria::DESC);
break;
case "created":
$search->addAscendingOrderByColumn('created_at');
break;
case "created_reverse":
$search->addDescendingOrderByColumn('created_at');
break;
case "updated":
$search->addAscendingOrderByColumn('updated_at');
break;
case "updated_reverse":
$search->addDescendingOrderByColumn('updated_at');
break;
}
}
}
return $search;
}
public function parseResults(LoopResult $loopResult)
{
/** @var AdminComment $comment */
foreach ($loopResult->getResultDataCollection() as $comment) {
$loopResultRow = new LoopResultRow($comment);
$admin = $comment->getAdmin();
$adminName = $admin ? $admin->getFirstname().' '.$admin->getLastname() : "";
$loopResultRow
->set('ID', $comment->getId())
->set('ADMIN_ID', $comment->getAdminId())
->set('ADMIN_NAME', $adminName)
->set('COMMENT', $comment->getComment())
->set('ELEMENT_KEY', $comment->getElementKey())
->set('ELEMENT_ID', $comment->getElementId())
->set('CREATED_AT', $comment->getCreatedAt())
->set('UPDATED_AT', $comment->getUpdatedAt());
$this->addOutputFields($loopResultRow, $comment);
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
} | thelia-modules/AdminComment | Loop/AdminCommentLoop.php | PHP | lgpl-3.0 | 3,967 |
package net.kyau.darkmatter.proxy;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import net.kyau.darkmatter.client.gui.GuiHUD;
import net.kyau.darkmatter.client.gui.GuiVoidJournal;
import net.kyau.darkmatter.client.renderer.EntityParticleFXQuantum;
import net.kyau.darkmatter.references.ModInfo;
import net.kyau.darkmatter.registry.ModBlocks;
import net.kyau.darkmatter.registry.ModItems;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.Particle;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
public class ClientProxy extends CommonProxy {
private static Minecraft minecraft = Minecraft.getMinecraft();
@Override
public ClientProxy getClientProxy() {
return this;
}
@Override
public void registerEventHandlers() {
super.registerEventHandlers();
MinecraftForge.EVENT_BUS.register(new GuiHUD(minecraft));
//LogManager.getLogger(ModInfo.MOD_ID).log(Level.INFO, "ClientProxy: registerEventHandlers() SUCCESS!");
}
@Override
public void registerClientEventHandlers() {
// NOOP
}
@Override
public void registerKeybindings() {
// NOOP
}
@Override
public void initRenderingAndTextures() {
ModItems.registerRenders();
ModBlocks.registerRenders();
}
@Override
public boolean isSinglePlayer() {
return Minecraft.getMinecraft().isSingleplayer();
}
@Override
public void openJournal() {
Minecraft.getMinecraft().displayGuiScreen(new GuiVoidJournal());
}
@Override
public void generateQuantumParticles(World world, BlockPos pos, Random rand) {
float motionX = (float) (rand.nextGaussian() * 0.02F);
float motionY = (float) (rand.nextGaussian() * 0.02F);
float motionZ = (float) (rand.nextGaussian() * 0.02F);
// for (int i = 0; i < 2; i++) {
Particle particleMysterious = new EntityParticleFXQuantum(world, pos.getX() + rand.nextFloat() * 0.7F + 0.2F, pos.getY() + 0.1F, pos.getZ() + rand.nextFloat() * 0.8F + 0.2F, motionX, motionY, motionZ);
Minecraft.getMinecraft().effectRenderer.addEffect(particleMysterious);
// }
}
@Override
public long getVoidPearlLastUse() {
// return lastUseVoidPearl;
return 0;
}
@Override
public void setVoidPearlLastUse(long lastUse) {
// this.lastUseVoidPearl = cooldown;
}
@Override
public void registerTileEntities() {
// TODO Auto-generated method stub
}
}
| kyau/darkmatter | src/main/java/net/kyau/darkmatter/proxy/ClientProxy.java | Java | lgpl-3.0 | 2,507 |
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* File Description:
* This code was generated by application DATATOOL
* using the following specifications:
* 'cdd.asn'.
*
* ATTENTION:
* Don't edit or commit this file into CVS as this file will
* be overridden (by DATATOOL) without warning!
* ===========================================================================
*/
// standard includes
#include <ncbi_pch.hpp>
#include <serial/serialimpl.hpp>
// generated includes
#include <objects/cdd/Cdd_Viewer.hpp>
#include <objects/cdd/Cdd_Viewer_Rect.hpp>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// generated classes
BEGIN_NAMED_ENUM_IN_INFO("", CCdd_Viewer_Base::, ECtrl, true)
{
SET_ENUM_INTERNAL_NAME("Cdd-Viewer", "ctrl");
SET_ENUM_MODULE("NCBI-Cdd");
ADD_ENUM_VALUE("unassigned", eCtrl_unassigned);
ADD_ENUM_VALUE("cd-info", eCtrl_cd_info);
ADD_ENUM_VALUE("align-annot", eCtrl_align_annot);
ADD_ENUM_VALUE("seq-list", eCtrl_seq_list);
ADD_ENUM_VALUE("seq-tree", eCtrl_seq_tree);
ADD_ENUM_VALUE("merge-preview", eCtrl_merge_preview);
ADD_ENUM_VALUE("cross-hits", eCtrl_cross_hits);
ADD_ENUM_VALUE("notes", eCtrl_notes);
ADD_ENUM_VALUE("tax-tree", eCtrl_tax_tree);
ADD_ENUM_VALUE("dart", eCtrl_dart);
ADD_ENUM_VALUE("dart-selected-rows", eCtrl_dart_selected_rows);
ADD_ENUM_VALUE("other", eCtrl_other);
}
END_ENUM_INFO
void CCdd_Viewer_Base::ResetRect(void)
{
m_Rect.Reset();
}
void CCdd_Viewer_Base::SetRect(CCdd_Viewer_Base::TRect& value)
{
m_Rect.Reset(&value);
}
CCdd_Viewer_Base::TRect& CCdd_Viewer_Base::SetRect(void)
{
if ( !m_Rect )
m_Rect.Reset(new ncbi::objects::CCdd_Viewer_Rect());
return (*m_Rect);
}
void CCdd_Viewer_Base::ResetAccessions(void)
{
m_Accessions.clear();
m_set_State[0] &= ~0x30;
}
void CCdd_Viewer_Base::Reset(void)
{
ResetCtrl();
ResetRect();
ResetAccessions();
}
BEGIN_NAMED_BASE_CLASS_INFO("Cdd-Viewer", CCdd_Viewer)
{
SET_CLASS_MODULE("NCBI-Cdd");
ADD_NAMED_ENUM_MEMBER("ctrl", m_Ctrl, ECtrl)->SetSetFlag(MEMBER_PTR(m_set_State[0]));
ADD_NAMED_REF_MEMBER("rect", m_Rect, CCdd_Viewer_Rect)->SetOptional();
ADD_NAMED_MEMBER("accessions", m_Accessions, STL_list, (STD, (string)))->SetSetFlag(MEMBER_PTR(m_set_State[0]));
info->RandomOrder();
info->CodeVersion(21600);
}
END_CLASS_INFO
// constructor
CCdd_Viewer_Base::CCdd_Viewer_Base(void)
: m_Ctrl((ECtrl)(0))
{
memset(m_set_State,0,sizeof(m_set_State));
}
// destructor
CCdd_Viewer_Base::~CCdd_Viewer_Base(void)
{
}
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/cdd/Cdd_Viewer_.cpp | C++ | lgpl-3.0 | 3,877 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KalikoCMS.Search")]
[assembly: AssemblyDescription("Lucene based search provider for Kaliko CMS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Fredrik Schultz / Kaliko")]
[assembly: AssemblyProduct("KalikoCMS.Search")]
[assembly: AssemblyCopyright("Copyright © 2016 Fredrik Schultz / Kaliko")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a018c2be-b5f7-4124-8f6d-db0d438df1d6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.3.5")]
[assembly: AssemblyFileVersion("3.0.3.5")]
| KalikoCMS/KalikoCMS.Search | KalikoCMS.Search/Properties/AssemblyInfo.cs | C# | lgpl-3.0 | 1,500 |
#include "MorsHtmlHighlighter.h"
enum Construct {
DocType,
Entity,
Tag,
Comment,
AttributeName,
AttributeValue
};
enum State {
State_Text = -1,
State_DocType,
State_Comment,
State_TagStart,
State_TagName,
State_InsideTag,
State_AttributeName,
State_SingleQuote,
State_DoubleQuote,
State_AttributeValue,
};
MorsHtmlHighlighter::MorsHtmlHighlighter(QTextDocument *document) : QSyntaxHighlighter(document)
{
colors_[DocType] = QColor(192, 192, 192);
colors_[Entity] = QColor(128, 128, 128);
colors_[Tag] = QColor(136, 18, 128);
colors_[Comment] = QColor( 35, 110, 37);
colors_[AttributeName] = QColor(153, 69, 0);
colors_[AttributeValue] = QColor( 36, 36, 170);
}
void MorsHtmlHighlighter::highlightBlock(const QString &text)
{
int state = previousBlockState();
int len = text.length();
int start = 0;
int pos = 0;
while (pos < len)
{
switch (state) {
case State_Text:
default:
while (pos < len) {
QChar ch = text.at(pos);
if (ch == '<') {
if (text.mid(pos, 4) == "<!--") {
state = State_Comment;
} else {
if (text.mid(pos, 9).toUpper() == "<!DOCTYPE")
state = State_DocType;
else
state = State_TagStart;
}
break;
} else if (ch == '&') {
start = pos;
while (pos < len
&& text.at(pos++) != ';')
;
setFormat(start, pos - start, colors_[Entity]);
} else {
++pos;
}
}
break;
case State_Comment:
start = pos;
while (pos < len) {
if (text.mid(pos, 3) == "-->") {
pos += 3;
state = State_Text;
break;
} else {
++pos;
}
}
setFormat(start, pos - start, colors_[Comment]);
break;
case State_DocType:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '>') {
state = State_Text;
break;
}
}
setFormat(start, pos - start, colors_[DocType]);
break;
// at '<' in e.g. "<span>foo</span>"
case State_TagStart:
start = pos + 1;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '>') {
state = State_Text;
break;
}
if (!ch.isSpace()) {
--pos;
state = State_TagName;
break;
}
}
break;
// at 'b' in e.g "<blockquote>foo</blockquote>"
case State_TagName:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch.isSpace()) {
--pos;
state = State_InsideTag;
break;
}
if (ch == '>') {
state = State_Text;
break;
}
}
setFormat(start, pos - start, colors_[Tag]);
break;
// anywhere after tag name and before tag closing ('>')
case State_InsideTag:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '/')
continue;
if (ch == '>') {
state = State_Text;
break;
}
if (!ch.isSpace()) {
--pos;
state = State_AttributeName;
break;
}
}
break;
// at 's' in e.g. <img src=bla.png/>
case State_AttributeName:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '=') {
state = State_AttributeValue;
break;
}
if (ch == '>' || ch == '/') {
state = State_InsideTag;
break;
}
}
setFormat(start, pos - start, colors_[AttributeName]);
break;
// after '=' in e.g. <img src=bla.png/>
case State_AttributeValue:
start = pos;
// find first non-space character
while (pos < len) {
QChar ch = text.at(pos);
++pos;
// handle opening single quote
if (ch == '\'') {
state = State_SingleQuote;
break;
}
// handle opening double quote
if (ch == '"') {
state = State_DoubleQuote;
break;
}
if (!ch.isSpace())
break;
}
if (state == State_AttributeValue) {
// attribute value without quote
// just stop at non-space or tag delimiter
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
if (ch.isSpace())
break;
if (ch == '>' || ch == '/')
break;
++pos;
}
state = State_InsideTag;
setFormat(start, pos - start, colors_[AttributeValue]);
}
break;
// after the opening single quote in an attribute value
case State_SingleQuote:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '\'')
break;
}
state = State_InsideTag;
setFormat(start, pos - start, colors_[AttributeValue]);
break;
// after the opening double quote in an attribute value
case State_DoubleQuote:
start = pos;
while (pos < len) {
QChar ch = text.at(pos);
++pos;
if (ch == '"')
break;
}
state = State_InsideTag;
setFormat(start, pos - start, colors_[AttributeValue]);
break;
}
}
setCurrentBlockState(state);
}
| MorsLiang/MorsMark | MorsMark/MorsHtmlHighlighter.cpp | C++ | lgpl-3.0 | 7,076 |
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2011 jruiz
*
* 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.cismet.verdis.commons.constants;
/**
* DOCUMENT ME!
*
* @author jruiz
* @version $Revision$, $Date$
*/
public final class KanalanschlussPropertyConstants extends PropertyConstants {
//~ Static fields/initializers ---------------------------------------------
public static final String BEFREIUNGENUNDERLAUBNISSE = "befreiungenunderlaubnisse";
//~ Constructors -----------------------------------------------------------
/**
* Creates a new KanalanschlussPropertyConstants object.
*/
KanalanschlussPropertyConstants() {
}
}
| cismet/verdis-server | src/main/java/de/cismet/verdis/commons/constants/KanalanschlussPropertyConstants.java | Java | lgpl-3.0 | 1,464 |
<?php
/**
* Help module - provides a system for viewing help pages from general Biscuit usage to module-specific help contextual to the page being viewed
*
* @package Modules
* @subpackage Help
* @author Peter Epp
* @copyright Copyright (c) 2009 Peter Epp (http://teknocat.org)
* @license GNU Lesser General Public License (http://www.gnu.org/licenses/lgpl.html)
* @version 1.0 $Id: controller.php 14283 2011-09-16 18:55:43Z teknocat $
*/
class HelpManager extends AbstractModuleController {
/**
* List of names of modules and/or extensions that have help for the current page
*
* @var string
*/
protected $_help_names = array();
/**
* Render a help page - for a specific module/extension if provided, otherwise general help
*
* @return void
* @author Peter Epp
*/
protected function action_index() {
// Ensure Fancybox is available for anyone who wants to use it on their help page:
LibraryLoader::load('JqueryFancybox');
$this->register_js('footer', 'ui-tabs-enabler.js');
$this->register_css(array('filename' => 'biscuit-help.css', 'media' => 'screen'));
if (!empty($this->params['module_or_extension_name'])) {
$help_file = AkInflector::underscore($this->params['module_or_extension_name']).'/views/biscuit-help.php';
if (Crumbs::file_exists_in_load_path($help_file)) {
$this->title(sprintf(__('%s Help'), ucwords(AkInflector::humanize(AkInflector::underscore($this->params['module_or_extension_name'])))));
$help = Crumbs::capture_include($help_file, array('Biscuit' => $this->Biscuit));
} else {
$this->title(__('Help Not Found'));
Response::http_status(404);
$help = Crumbs::capture_include('help/views/help-not-found.php');
}
} else {
$other_help_items = array();
if (empty($this->params['module_or_extension_name'])) {
// If we're on the general help page, find other help items to build an in-page menu
Event::fire('build_help_menu', $this);
if (!empty($this->_help_names)) {
sort($this->_help_names);
foreach ($this->_help_names as $module_or_extension_name) {
$human_name = ucwords(AkInflector::humanize(AkInflector::underscore($module_or_extension_name)));
$other_help_items[$human_name] = $this->url().'/'.$module_or_extension_name;
}
}
}
$help = Crumbs::capture_include('help/views/general-help.php', array('other_help_items' => $other_help_items));
$this->title(SITE_TITLE.' Help');
}
$this->set_view_var('help', $help);
$this->render();
}
/**
* Allow URLs to help page with module or extension name
*
* @return void
* @author Peter Epp
*/
public static function uri_mapping_rules() {
return array(
'/(?P<page_slug>user-help)\/(?P<module_or_extension_name>.+)$/'
);
}
/**
* Add help menu items when building admin menu
*
* @param string $caller
* @return void
* @author Peter Epp
*/
protected function act_on_build_admin_menu($caller) {
if (!$this->user_can_index()) {
// If the user does not have access to help, just skip
return;
}
$menu_items['General Help'] = array(
'url' => $this->url(),
'ui-icon' => 'ui-icon-help'
);
// Let installed modules add their help. This way only modules installed on the current page add to the help menu, making it contextual
if (empty($this->_help_names)) {
Event::fire('build_help_menu', $this);
}
if (!empty($this->_help_names)) {
sort($this->_help_names);
foreach ($this->_help_names as $module_or_extension_name) {
$human_name = ucwords(AkInflector::humanize(AkInflector::underscore($module_or_extension_name)));
$menu_items[$human_name] = array(
'url' => $this->url().'/'.$module_or_extension_name,
'ui-icon' => 'ui-icon-help'
);
}
}
$caller->add_admin_menu_items('Help',$menu_items);
}
/**
* Add the name of a module or extension to the list of things that have help so they can be added to the help menu
*
* @param string $module_or_extension_name
* @return void
* @author Peter Epp
*/
public function add_help_for($module_or_extension_name) {
$this->_help_names[] = $module_or_extension_name;
}
/**
* Add breadcrumb based on the current action if it is not "index" and the current module is primary.
*
* @param Navigation $Navigation
* @return void
* @author Peter Epp
*/
protected function act_on_build_breadcrumbs($Navigation) {
if ($this->action() == 'index' && $this->is_primary() && !empty($this->params['module_or_extension_name'])) {
$Navigation->add_breadcrumb($this->url().'/'.$this->params['module_or_extension_name'], ucwords(AkInflector::humanize(AkInflector::underscore($this->params['module_or_extension_name']))));
}
}
/**
* Installus
*
* @param string $module_id
* @return void
* @author Peter Epp
*/
public static function install_migration($module_id) {
$my_page = DB::fetch_one("SELECT `id` FROM `page_index` WHERE `slug` = 'user-help'");
if (!$my_page) {
DB::query("INSERT INTO `page_index` SET `parent` = 9999999, `slug` = 'user-help', `title` = 'General Help', `access_level` = 0");
// Ensure clean install:
DB::query("DELETE FROM `module_pages` WHERE `page_name` = 'user-help'");
DB::query("INSERT INTO `module_pages` (`module_id`, `page_name`, `is_primary`) VALUES ({$module_id}, 'user-help', 1), ({$module_id}, '*', 0)");
// Make sure all other installed modules are installed as secondary on the help page:
$installed_module_ids = DB::fetch("SELECT `id` FROM `modules` WHERE `installed` = 1 AND `id` != {$module_id}");
if (!empty($installed_module_ids)) {
$query = "INSERT INTO `module_pages` (`module_id`, `page_name`, `is_primary`) VALUES ";
$insert_values = array();
foreach ($installed_module_ids as $other_id) {
$insert_values[] = "({$other_id}, 'user-help', 0)";
}
$query .= implode(', ', $insert_values);
DB::query($query);
}
}
Permissions::add(__CLASS__, array('index' => 99));
}
/**
* Destallus
*
* @param string $module_id
* @return void
* @author Peter Epp
*/
public static function uninstall_migration($module_id) {
DB::query("DELETE FROM `page_index` WHERE `slug` = 'user-help'");
DB::query("DELETE FROM `module_pages` WHERE `page_name` = 'user-help'");
Permissions::remove(__CLASS__);
}
}
| theteknocat/Biscuit-Help | controller.php | PHP | lgpl-3.0 | 6,271 |
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
int main() {
std::string ps = "/usr/local/dayu/scripts";
boost::filesystem::path p(ps);
p /= "kk.py";
std::cout << p.string() << std::endl;
std::cout << p.stem() << std::endl;
std::cout << p.parent_path() << std::endl;
std::cout << p.filename() << std::endl;
std::cout << p.extension() << std::endl;
std::cerr << "Something error occurred." << std::endl;
return 0;
}
| kk47/C-Cpp | src/cpp/bpath.cpp | C++ | lgpl-3.0 | 487 |
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* kdm/data/KeyRelationImpl.cpp
* Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es>
* Copyright (C) INCHRON GmbH 2016 <soeren.henning@inchron.com>
*
* EMF4CPP 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.
*
* EMF4CPP 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/>.
*/
#include "KeyRelation.hpp"
#include <kdm/data/DataPackage.hpp>
#include <kdm/data/AbstractDataRelationship.hpp>
#include <kdm/kdm/Attribute.hpp>
#include <kdm/kdm/Annotation.hpp>
#include <kdm/kdm/Stereotype.hpp>
#include <kdm/kdm/ExtendedValue.hpp>
#include <kdm/data/UniqueKey.hpp>
#include <kdm/data/ReferenceKey.hpp>
#include <kdm/core/KDMEntity.hpp>
#include <ecore/EObject.hpp>
#include <ecore/EClass.hpp>
#include <ecore/EStructuralFeature.hpp>
#include <ecore/EReference.hpp>
#include <ecore/EObject.hpp>
#include <ecorecpp/mapping.hpp>
/*PROTECTED REGION ID(KeyRelationImpl.cpp) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
using namespace ::kdm::data;
void KeyRelation::_initialize()
{
// Supertypes
::kdm::data::AbstractDataRelationship::_initialize();
// References
/*PROTECTED REGION ID(KeyRelationImpl__initialize) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
}
// Operations
// EObject
::ecore::EJavaObject KeyRelation::eGet(::ecore::EInt _featureID,
::ecore::EBoolean _resolve)
{
::ecore::EJavaObject _any;
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
_any = m_attribute->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
_any = m_annotation->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
_any = m_stereotype->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
_any = m_taggedValue->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::data::DataPackage::KEYRELATION__TO:
{
if (m_to)
_any = ::ecore::as < ::ecore::EObject > (m_to);
}
return _any;
case ::kdm::data::DataPackage::KEYRELATION__FROM:
{
if (m_from)
_any = ::ecore::as < ::ecore::EObject > (m_from);
}
return _any;
}
throw "Error";
}
void KeyRelation::eSet(::ecore::EInt _featureID,
::ecore::EJavaObject const& _newValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::Element::getAttribute().clear();
::kdm::core::Element::getAttribute().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::Element::getAnnotation().clear();
::kdm::core::Element::getAnnotation().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::ModelElement::getStereotype().clear();
::kdm::core::ModelElement::getStereotype().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::ModelElement::getTaggedValue().clear();
::kdm::core::ModelElement::getTaggedValue().insert_all(*_t0);
}
return;
case ::kdm::data::DataPackage::KEYRELATION__TO:
{
::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast
< ::ecore::EObject_ptr > (_newValue);
::kdm::data::UniqueKey_ptr _t1 =
dynamic_cast< ::kdm::data::UniqueKey* >(_t0.get()); /*/// std::dynamic_pointer_cast< ::kdm::data::UniqueKey >(_t0);*/
::kdm::data::KeyRelation::setTo(_t1);
}
return;
case ::kdm::data::DataPackage::KEYRELATION__FROM:
{
::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast
< ::ecore::EObject_ptr > (_newValue);
::kdm::data::ReferenceKey_ptr _t1 =
dynamic_cast< ::kdm::data::ReferenceKey* >(_t0.get()); /*/// std::dynamic_pointer_cast< ::kdm::data::ReferenceKey >(_t0);*/
::kdm::data::KeyRelation::setFrom(_t1);
}
return;
}
throw "Error";
}
::ecore::EBoolean KeyRelation::eIsSet(::ecore::EInt _featureID)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
return m_attribute && m_attribute->size();
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
return m_annotation && m_annotation->size();
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
return m_stereotype && m_stereotype->size();
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
return m_taggedValue && m_taggedValue->size();
case ::kdm::data::DataPackage::KEYRELATION__TO:
return (bool) m_to;
case ::kdm::data::DataPackage::KEYRELATION__FROM:
return (bool) m_from;
}
throw "Error";
}
void KeyRelation::eUnset(::ecore::EInt _featureID)
{
switch (_featureID)
{
}
throw "Error";
}
::ecore::EClass_ptr KeyRelation::_eClass()
{
static ::ecore::EClass_ptr _eclass =
dynamic_cast< ::kdm::data::DataPackage* >(::kdm::data::DataPackage::_instance().get())->getKeyRelation();
return _eclass;
}
/** Set the local end of a reference with an EOpposite property.
*/
void KeyRelation::_inverseAdd(::ecore::EInt _featureID,
::ecore::EJavaObject const& _newValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
}
return;
case ::kdm::data::DataPackage::KEYRELATION__TO:
{
}
return;
case ::kdm::data::DataPackage::KEYRELATION__FROM:
{
}
return;
}
throw "Error: _inverseAdd() does not handle this featureID";
}
/** Unset the local end of a reference with an EOpposite property.
*/
void KeyRelation::_inverseRemove(::ecore::EInt _featureID,
::ecore::EJavaObject const& _oldValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
}
return;
case ::kdm::data::DataPackage::KEYRELATION__TO:
{
}
return;
case ::kdm::data::DataPackage::KEYRELATION__FROM:
{
}
return;
}
throw "Error: _inverseRemove() does not handle this featureID";
}
| catedrasaes-umu/emf4cpp | emf4cpp.tests/kdm/kdm/data/KeyRelationImpl.cpp | C++ | lgpl-3.0 | 8,644 |
// -*- mode: C++; c-file-style: "cc-mode" -*-
//*************************************************************************
// DESCRIPTION: Verilator: Replicate modules for parameterization
//
// Code available from: https://verilator.org
//
//*************************************************************************
//
// Copyright 2003-2021 by Wilson Snyder. This program is free software; you
// can redistribute it and/or modify it under the terms of either the GNU
// Lesser General Public License Version 3 or the Perl Artistic License
// Version 2.0.
// SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0
//
//*************************************************************************
// PARAM TRANSFORMATIONS:
// Top down traversal:
// For each cell:
// If parameterized,
// Determine all parameter widths, constant values.
// (Interfaces also matter, as if an interface is parameterized
// this effectively changes the width behavior of all that
// reference the iface.)
// Clone module cell calls, renaming with __{par1}_{par2}_...
// Substitute constants for cell's module's parameters.
// Relink pins and cell and ifacerefdtype to point to new module.
//
// For interface Parent's we have the AstIfaceRefDType::cellp()
// pointing to this module. If that parent cell's interface
// module gets parameterized, AstIfaceRefDType::cloneRelink
// will update AstIfaceRefDType::cellp(), and V3LinkDot will
// see the new interface.
//
// However if a submodule's AstIfaceRefDType::ifacep() points
// to the old (unparameterized) interface and needs correction.
// To detect this we must walk all pins looking for interfaces
// that the parent has changed and propagate down.
//
// Then process all modules called by that cell.
// (Cells never referenced after parameters expanded must be ignored.)
//
// After we complete parameters, the varp's will be wrong (point to old module)
// and must be relinked.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
#include "V3Global.h"
#include "V3Param.h"
#include "V3Ast.h"
#include "V3Case.h"
#include "V3Const.h"
#include "V3Os.h"
#include "V3Parse.h"
#include "V3Width.h"
#include "V3Unroll.h"
#include "V3Hasher.h"
#include <deque>
#include <map>
#include <memory>
#include <vector>
//######################################################################
// Hierarchical block and parameter db (modules without parameter is also handled)
class ParameterizedHierBlocks final {
using HierBlockOptsByOrigName = std::multimap<std::string, const V3HierarchicalBlockOption*>;
using HierMapIt = HierBlockOptsByOrigName::const_iterator;
using HierBlockModMap = std::map<const std::string, AstNodeModule*>;
using ParamConstMap = std::map<const std::string, std::unique_ptr<AstConst>>;
using GParamsMap = std::map<const std::string, AstVar*>; // key:parameter name value:parameter
// MEMBERS
// key:Original module name, value:HiearchyBlockOption*
// If a module is parameterized, the module is uniquiefied to overridden parameters.
// This is why HierBlockOptsByOrigName is multimap.
HierBlockOptsByOrigName m_hierBlockOptsByOrigName;
// key:mangled module name, value:AstNodeModule*
HierBlockModMap m_hierBlockMod;
// Overridden parameters of the hierarchical block
std::map<const V3HierarchicalBlockOption*, ParamConstMap> m_hierParams;
std::map<const std::string, GParamsMap>
m_modParams; // Parameter variables of hierarchical blocks
// METHODS
VL_DEBUG_FUNC; // Declare debug()
public:
ParameterizedHierBlocks(const V3HierBlockOptSet& hierOpts, AstNetlist* nodep) {
for (const auto& hierOpt : hierOpts) {
m_hierBlockOptsByOrigName.insert(
std::make_pair(hierOpt.second.origName(), &hierOpt.second));
const V3HierarchicalBlockOption::ParamStrMap& params = hierOpt.second.params();
ParamConstMap& consts = m_hierParams[&hierOpt.second];
for (V3HierarchicalBlockOption::ParamStrMap::const_iterator pIt = params.begin();
pIt != params.end(); ++pIt) {
std::unique_ptr<AstConst> constp{AstConst::parseParamLiteral(
new FileLine(FileLine::EmptySecret()), pIt->second)};
UASSERT(constp, pIt->second << " is not a valid parameter literal");
const bool inserted = consts.emplace(pIt->first, std::move(constp)).second;
UASSERT(inserted, pIt->first << " is already added");
}
// origName may be already registered, but it's fine.
m_modParams.insert({hierOpt.second.origName(), {}});
}
for (AstNodeModule* modp = nodep->modulesp(); modp;
modp = VN_CAST(modp->nextp(), NodeModule)) {
if (hierOpts.find(modp->prettyName()) != hierOpts.end()) {
m_hierBlockMod.emplace(modp->name(), modp);
}
const auto defParamIt = m_modParams.find(modp->name());
if (defParamIt != m_modParams.end()) {
// modp is the original of parameterized hierarchical block
for (AstNode* stmtp = modp->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isGParam()) defParamIt->second.emplace(varp->name(), varp);
}
}
}
}
}
AstNodeModule* findByParams(const string& origName, AstPin* firstPinp,
const AstNodeModule* modp) {
if (m_hierBlockOptsByOrigName.find(origName) == m_hierBlockOptsByOrigName.end()) {
return nullptr;
}
// This module is a hierarchical block. Need to replace it by the protect-lib wrapper.
const std::pair<HierMapIt, HierMapIt> candidates
= m_hierBlockOptsByOrigName.equal_range(origName);
const auto paramsIt = m_modParams.find(origName);
UASSERT_OBJ(paramsIt != m_modParams.end(), modp, origName << " must be registered");
HierMapIt hierIt;
for (hierIt = candidates.first; hierIt != candidates.second; ++hierIt) {
bool found = true;
size_t paramIdx = 0;
const ParamConstMap& params = m_hierParams[hierIt->second];
UASSERT(params.size() == hierIt->second->params().size(), "not match");
for (AstPin* pinp = firstPinp; pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
if (!pinp->exprp()) continue;
UASSERT_OBJ(!pinp->modPTypep(), pinp,
"module with type parameter must not be a hierarchical block");
if (AstVar* modvarp = pinp->modVarp()) {
AstConst* constp = VN_CAST(pinp->exprp(), Const);
UASSERT_OBJ(constp, pinp,
"parameter for a hierarchical block must have been constified");
const auto paramIt = paramsIt->second.find(modvarp->name());
UASSERT_OBJ(paramIt != paramsIt->second.end(), modvarp, "must be registered");
AstConst* defValuep = VN_CAST(paramIt->second->valuep(), Const);
if (defValuep && areSame(constp, defValuep)) {
UINFO(5, "Setting default value of " << constp << " to " << modvarp
<< std::endl);
continue; // Skip this parameter because setting the same value
}
const auto pIt = vlstd::as_const(params).find(modvarp->name());
UINFO(5, "Comparing " << modvarp->name() << " " << constp << std::endl);
if (pIt == params.end() || paramIdx >= params.size()
|| !areSame(constp, pIt->second.get())) {
found = false;
break;
}
UINFO(5, "Matched " << modvarp->name() << " " << constp << " and "
<< pIt->second.get() << std::endl);
++paramIdx;
}
}
if (found && paramIdx == hierIt->second->params().size()) break;
}
UASSERT_OBJ(hierIt != candidates.second, firstPinp, "No protect-lib wrapper found");
// parameter settings will be removed in the bottom of caller visitCell().
const HierBlockModMap::const_iterator modIt
= m_hierBlockMod.find(hierIt->second->mangledName());
UASSERT_OBJ(modIt != m_hierBlockMod.end(), firstPinp,
hierIt->second->mangledName() << " is not found");
const auto it = vlstd::as_const(m_hierBlockMod).find(hierIt->second->mangledName());
if (it == m_hierBlockMod.end()) return nullptr;
return it->second;
}
static bool areSame(AstConst* pinValuep, AstConst* hierOptParamp) {
if (pinValuep->isString()) {
return pinValuep->num().toString() == hierOptParamp->num().toString();
}
// Bitwidth of hierOptParamp is accurate because V3Width already caluclated in the previous
// run. Bitwidth of pinValuep is before width analysis, so pinValuep is casted to
// hierOptParamp width.
V3Number varNum(pinValuep, hierOptParamp->num().width());
if (hierOptParamp->isDouble()) {
varNum.isDouble(true);
if (pinValuep->isDouble()) {
varNum.opAssign(pinValuep->num());
} else { // Cast from integer to real
varNum.opIToRD(pinValuep->num());
}
return v3EpsilonEqual(varNum.toDouble(), hierOptParamp->num().toDouble());
} else { // Now integer type is assumed
if (pinValuep->isDouble()) { // Need to cast to int
// Parameter is actually an integral type, but passed value is floating point.
// Conversion from real to integer uses rounding in V3Width.cpp
varNum.opRToIRoundS(pinValuep->num());
} else if (pinValuep->isSigned()) {
varNum.opExtendS(pinValuep->num(), pinValuep->num().width());
} else {
varNum.opAssign(pinValuep->num());
}
V3Number isEq(pinValuep, 1);
isEq.opEq(varNum, hierOptParamp->num());
return isEq.isNeqZero();
}
}
};
//######################################################################
// Remove parameters from cells and build new modules
class ParamProcessor final {
// NODE STATE - Local
// AstVar::user4() // int Global parameter number (for naming new module)
// // (0=not processed, 1=iterated, but no number,
// // 65+ parameter numbered)
// NODE STATE - Shared with ParamVisitor
// AstNodeModule::user5() // bool True if processed
// AstGenFor::user5() // bool True if processed
// AstVar::user5() // bool True if constant propagated
// AstCell::user5p() // string* Generate portion of hierarchical name
AstUser4InUse m_inuser4;
AstUser5InUse m_inuser5;
// User1/2/3 used by constant function simulations
// TYPES
// Note may have duplicate entries
using IfaceRefRefs = std::deque<std::pair<AstIfaceRefDType*, AstIfaceRefDType*>>;
// STATE
using CloneMap = std::unordered_map<const AstNode*, AstNode*>;
struct ModInfo {
AstNodeModule* m_modp; // Module with specified name
CloneMap m_cloneMap; // Map of old-varp -> new cloned varp
explicit ModInfo(AstNodeModule* modp)
: m_modp{modp} {}
};
std::map<const std::string, ModInfo> m_modNameMap; // Hash of created module flavors by name
std::map<const std::string, std::string>
m_longMap; // Hash of very long names to unique identity number
int m_longId = 0;
// All module names that are loaded from source code
// Generated modules by this visitor is not included
V3StringSet m_allModuleNames;
using ValueMapValue = std::pair<int, std::string>;
std::map<const V3Hash, ValueMapValue> m_valueMap; // Hash of node hash to (param value, name)
int m_nextValue = 1; // Next value to use in m_valueMap
AstNodeModule* m_modp = nullptr; // Current module being processed
// Database to get protect-lib wrapper that matches parameters in hierarchical Verilation
ParameterizedHierBlocks m_hierBlocks;
// Default parameter values key:parameter name, value:default value (can be nullptr)
using DefaultValueMap = std::map<std::string, AstConst*>;
// Default parameter values of hierarchical blocks
std::map<AstNodeModule*, DefaultValueMap> m_defaultParameterValues;
// METHODS
VL_DEBUG_FUNC; // Declare debug()
static void makeSmallNames(AstNodeModule* modp) {
std::vector<int> usedLetter;
usedLetter.resize(256);
// Pass 1, assign first letter to each gparam's name
for (AstNode* stmtp = modp->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isGParam() || varp->isIfaceRef()) {
char ch = varp->name()[0];
ch = std::toupper(ch);
if (ch < 'A' || ch > 'Z') ch = 'Z';
varp->user4(usedLetter[static_cast<int>(ch)] * 256 + ch);
usedLetter[static_cast<int>(ch)]++;
}
} else if (AstParamTypeDType* typep = VN_CAST(stmtp, ParamTypeDType)) {
const char ch = 'T';
typep->user4(usedLetter[static_cast<int>(ch)] * 256 + ch);
usedLetter[static_cast<int>(ch)]++;
}
}
}
string paramSmallName(AstNodeModule* modp, AstNode* varp) {
if (varp->user4() <= 1) makeSmallNames(modp);
int index = varp->user4() / 256;
const char ch = varp->user4() & 255;
string st = cvtToStr(ch);
while (index) {
st += cvtToStr(char((index % 25) + 'A'));
index /= 26;
}
return st;
}
static string paramValueKey(const AstNode* nodep) {
if (const AstRefDType* const refp = VN_CAST_CONST(nodep, RefDType)) {
nodep = refp->skipRefp();
}
string key = nodep->name();
if (const AstIfaceRefDType* const ifrtp = VN_CAST_CONST(nodep, IfaceRefDType)) {
if (ifrtp->cellp() && ifrtp->cellp()->modp()) {
key = ifrtp->cellp()->modp()->name();
} else if (ifrtp->ifacep()) {
key = ifrtp->ifacep()->name();
} else {
nodep->v3fatalSrc("Can't parameterize interface without module name");
}
} else if (const AstNodeUOrStructDType* const dtypep
= VN_CAST_CONST(nodep, NodeUOrStructDType)) {
key += " ";
key += dtypep->verilogKwd();
key += " {";
for (const AstNode* memberp = dtypep->membersp(); memberp;
memberp = memberp->nextp()) {
key += paramValueKey(memberp);
key += ";";
}
key += "}";
} else if (const AstMemberDType* const dtypep = VN_CAST_CONST(nodep, MemberDType)) {
key += " ";
key += paramValueKey(dtypep->subDTypep());
} else if (const AstBasicDType* const dtypep = VN_CAST_CONST(nodep, BasicDType)) {
if (dtypep->isRanged()) {
key += "[" + cvtToStr(dtypep->left()) + ":" + cvtToStr(dtypep->right()) + "]";
}
}
return key;
}
string paramValueNumber(AstNode* nodep) {
// TODO: This parameter value number lookup via a constructed key string is not
// particularly robust for type parameters. We should really have a type
// equivalence predicate function.
const string key = paramValueKey(nodep);
V3Hash hash = V3Hasher::uncachedHash(nodep);
// Force hash collisions -- for testing only
if (VL_UNLIKELY(v3Global.opt.debugCollision())) hash = V3Hash();
int num;
const auto it = m_valueMap.find(hash);
if (it != m_valueMap.end() && it->second.second == key) {
num = it->second.first;
} else {
num = m_nextValue++;
m_valueMap[hash] = std::make_pair(num, key);
}
return string("z") + cvtToStr(num);
}
string moduleCalcName(AstNodeModule* srcModp, const string& longname) {
string newname = longname;
if (longname.length() > 30) {
const auto iter = m_longMap.find(longname);
if (iter != m_longMap.end()) {
newname = iter->second;
} else {
newname = srcModp->name();
// We use all upper case above, so lower here can't conflict
newname += "__pi" + cvtToStr(++m_longId);
m_longMap.emplace(longname, newname);
}
}
UINFO(4, "Name: " << srcModp->name() << "->" << longname << "->" << newname << endl);
return newname;
}
AstNodeDType* arraySubDTypep(AstNodeDType* nodep) {
// If an unpacked array, return the subDTypep under it
if (AstUnpackArrayDType* adtypep = VN_CAST(nodep, UnpackArrayDType)) {
return adtypep->subDTypep();
}
// We have not resolved parameter of the child yet, so still
// have BracketArrayDType's. We'll presume it'll end up as assignment
// compatible (or V3Width will complain).
if (AstBracketArrayDType* adtypep = VN_CAST(nodep, BracketArrayDType)) {
return adtypep->subDTypep();
}
return nullptr;
}
void collectPins(CloneMap* clonemapp, AstNodeModule* modp) {
// Grab all I/O so we can remap our pins later
for (AstNode* stmtp = modp->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isIO() || varp->isGParam() || varp->isIfaceRef()) {
// Cloning saved a pointer to the new node for us, so just follow that link.
AstVar* oldvarp = varp->clonep();
// UINFO(8,"Clone list 0x"<<hex<<(uint32_t)oldvarp
// <<" -> 0x"<<(uint32_t)varp<<endl);
clonemapp->emplace(oldvarp, varp);
}
} else if (AstParamTypeDType* ptp = VN_CAST(stmtp, ParamTypeDType)) {
if (ptp->isGParam()) {
AstParamTypeDType* oldptp = ptp->clonep();
clonemapp->emplace(oldptp, ptp);
}
}
}
}
void relinkPins(const CloneMap* clonemapp, AstPin* startpinp) {
for (AstPin* pinp = startpinp; pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
if (pinp->modVarp()) {
// Find it in the clone structure
// UINFO(8,"Clone find 0x"<<hex<<(uint32_t)pinp->modVarp()<<endl);
const auto cloneiter = clonemapp->find(pinp->modVarp());
UASSERT_OBJ(cloneiter != clonemapp->end(), pinp,
"Couldn't find pin in clone list");
pinp->modVarp(VN_CAST(cloneiter->second, Var));
} else if (pinp->modPTypep()) {
const auto cloneiter = clonemapp->find(pinp->modPTypep());
UASSERT_OBJ(cloneiter != clonemapp->end(), pinp,
"Couldn't find pin in clone list");
pinp->modPTypep(VN_CAST(cloneiter->second, ParamTypeDType));
} else {
pinp->v3fatalSrc("Not linked?");
}
}
}
void relinkPinsByName(AstPin* startpinp, AstNodeModule* modp) {
std::map<const string, AstVar*> nameToPin;
for (AstNode* stmtp = modp->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isIO() || varp->isGParam() || varp->isIfaceRef()) {
nameToPin.emplace(varp->name(), varp);
}
}
}
for (AstPin* pinp = startpinp; pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
if (AstVar* varp = pinp->modVarp()) {
const auto varIt = vlstd::as_const(nameToPin).find(varp->name());
UASSERT_OBJ(varIt != nameToPin.end(), varp,
"Not found in " << modp->prettyNameQ());
pinp->modVarp(varIt->second);
}
}
}
// Check if parameter setting during instantiation is simple enough for hierarchical verilation
void checkSupportedParam(AstNodeModule* modp, AstPin* pinp) const {
// InitArray and AstParamTypeDType are not supported because that can not be set via -G
// option.
if (pinp->modVarp()) {
bool supported = false;
if (AstConst* constp = VN_CAST(pinp->exprp(), Const)) {
supported = !constp->isOpaque();
}
if (!supported) {
pinp->v3error(AstNode::prettyNameQ(modp->origName())
<< " has hier_block metacomment, hierarchical verilation"
<< " supports only integer/floating point/string parameters");
}
} else if (VN_IS(pinp->modPTypep(), ParamTypeDType)) {
pinp->v3error(AstNode::prettyNameQ(modp->origName())
<< " has hier_block metacomment, but 'parameter type' is not supported");
}
}
bool moduleExists(const string& modName) const {
if (m_allModuleNames.find(modName) != m_allModuleNames.end()) return true;
if (m_modNameMap.find(modName) != m_modNameMap.end()) return true;
return false;
}
string parameterizedHierBlockName(AstNodeModule* modp, AstPin* paramPinsp) {
// Create a unique name in the following steps
// - Make a long name that includes all parameters, that appear
// in the alphabetical order.
// - Hash the long name to get valid Verilog symbol
UASSERT_OBJ(modp->hierBlock(), modp, "should be used for hierarchical block");
std::map<string, AstConst*> pins;
for (AstPin* pinp = paramPinsp; pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
checkSupportedParam(modp, pinp);
if (AstVar* varp = pinp->modVarp()) {
if (!pinp->exprp()) continue;
if (varp->isGParam()) {
AstConst* constp = VN_CAST(pinp->exprp(), Const);
pins.emplace(varp->name(), constp);
}
}
}
auto paramsIt = m_defaultParameterValues.find(modp);
if (paramsIt == m_defaultParameterValues.end()) { // Not cached yet, so check parameters
// Using map with key=string so that we can scan it in deterministic order
DefaultValueMap params;
for (AstNode* stmtp = modp->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isGParam()) {
AstConst* constp = VN_CAST(varp->valuep(), Const);
// constp can be nullptr if the parameter is not used to instantiate sub
// module. varp->valuep() is not contified yet in the case.
// nullptr means that the parameter is using some default value.
params.emplace(varp->name(), constp);
}
}
}
paramsIt = m_defaultParameterValues.emplace(modp, std::move(params)).first;
}
if (paramsIt->second.empty()) return modp->name(); // modp has no parameter
string longname = modp->name();
for (auto&& defaultValue : paramsIt->second) {
const auto pinIt = pins.find(defaultValue.first);
AstConst* constp = pinIt == pins.end() ? defaultValue.second : pinIt->second;
// This longname is not valid as verilog symbol, but ok, because it will be hashed
longname += "_" + defaultValue.first + "=";
// constp can be nullptr
if (constp) longname += constp->num().ascii(false);
}
const auto iter = m_longMap.find(longname);
if (iter != m_longMap.end()) return iter->second; // Already calculated
VHashSha256 hash;
// Calculate hash using longname
// The hash is used as the module suffix to find a module name that is unique in the design
hash.insert(longname);
while (true) {
// Copy VHashSha256 just in case of hash collision
VHashSha256 hashStrGen = hash;
// Hex string must be a safe suffix for any symbol
const string hashStr = hashStrGen.digestHex();
for (string::size_type i = 1; i < hashStr.size(); ++i) {
string newName = modp->name();
// Don't use '__' not to be encoded when this module is loaded later by Verilator
if (newName.at(newName.size() - 1) != '_') newName += '_';
newName += hashStr.substr(0, i);
if (!moduleExists(newName)) {
m_longMap.emplace(longname, newName);
return newName;
}
}
// Hash collision. maybe just v3error is practically enough
hash.insert(V3Os::trueRandom(64));
}
}
void deepCloneModule(AstNodeModule* srcModp, AstNode* cellp, AstPin* paramsp,
const string& newname, const IfaceRefRefs& ifaceRefRefs) {
// Deep clone of new module
// Note all module internal variables will be re-linked to the new modules by clone
// However links outside the module (like on the upper cells) will not.
AstNodeModule* newmodp = srcModp->cloneTree(false);
newmodp->name(newname);
newmodp->user5(false); // We need to re-recurse this module once changed
newmodp->recursive(false);
newmodp->recursiveClone(false);
// Only the first generation of clone holds this property
newmodp->hierBlock(srcModp->hierBlock() && !srcModp->recursiveClone());
// Recursion may need level cleanups
if (newmodp->level() <= m_modp->level()) newmodp->level(m_modp->level() + 1);
if ((newmodp->level() - srcModp->level()) >= (v3Global.opt.moduleRecursionDepth() - 2)) {
cellp->v3error("Exceeded maximum --module-recursion-depth of "
<< v3Global.opt.moduleRecursionDepth());
}
// Keep tree sorted by level
AstNodeModule* insertp = srcModp;
while (VN_IS(insertp->nextp(), NodeModule)
&& VN_CAST(insertp->nextp(), NodeModule)->level() < newmodp->level()) {
insertp = VN_CAST(insertp->nextp(), NodeModule);
}
insertp->addNextHere(newmodp);
m_modNameMap.emplace(newmodp->name(), ModInfo(newmodp));
const auto iter = m_modNameMap.find(newname);
CloneMap* clonemapp = &(iter->second.m_cloneMap);
UINFO(4, " De-parameterize to new: " << newmodp << endl);
// Grab all I/O so we can remap our pins later
// Note we allow multiple users of a parameterized model,
// thus we need to stash this info.
collectPins(clonemapp, newmodp);
// Relink parameter vars to the new module
relinkPins(clonemapp, paramsp);
// Fix any interface references
for (auto it = ifaceRefRefs.cbegin(); it != ifaceRefRefs.cend(); ++it) {
AstIfaceRefDType* portIrefp = it->first;
AstIfaceRefDType* pinIrefp = it->second;
AstIfaceRefDType* cloneIrefp = portIrefp->clonep();
UINFO(8, " IfaceOld " << portIrefp << endl);
UINFO(8, " IfaceTo " << pinIrefp << endl);
UASSERT_OBJ(cloneIrefp, portIrefp, "parameter clone didn't hit AstIfaceRefDType");
UINFO(8, " IfaceClo " << cloneIrefp << endl);
cloneIrefp->ifacep(pinIrefp->ifaceViaCellp());
UINFO(8, " IfaceNew " << cloneIrefp << endl);
}
// Assign parameters to the constants specified
// DOES clone() so must be finished with module clonep() before here
for (AstPin* pinp = paramsp; pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
if (pinp->exprp()) {
if (AstVar* modvarp = pinp->modVarp()) {
AstNode* newp = pinp->exprp(); // Const or InitArray
AstConst* exprp = VN_CAST(newp, Const);
AstConst* origp = VN_CAST(modvarp->valuep(), Const);
const bool overridden
= !(origp && ParameterizedHierBlocks::areSame(exprp, origp));
// Remove any existing parameter
if (modvarp->valuep()) modvarp->valuep()->unlinkFrBack()->deleteTree();
// Set this parameter to value requested by cell
UINFO(9, " set param " << modvarp << " = " << newp << endl);
modvarp->valuep(newp->cloneTree(false));
modvarp->overriddenParam(overridden);
} else if (AstParamTypeDType* modptp = pinp->modPTypep()) {
AstNodeDType* dtypep = VN_CAST(pinp->exprp(), NodeDType);
UASSERT_OBJ(dtypep, pinp, "unlinked param dtype");
if (modptp->childDTypep()) modptp->childDTypep()->unlinkFrBack()->deleteTree();
// Set this parameter to value requested by cell
modptp->childDTypep(dtypep->cloneTree(false));
// Later V3LinkDot will convert the ParamDType to a Typedef
// Not done here as may be localparams, etc, that also need conversion
}
}
}
}
const ModInfo* moduleFindOrClone(AstNodeModule* srcModp, AstNode* cellp, AstPin* paramsp,
const string& newname, const IfaceRefRefs& ifaceRefRefs) {
// Already made this flavor?
auto it = m_modNameMap.find(newname);
if (it != m_modNameMap.end()) {
UINFO(4, " De-parameterize to old: " << it->second.m_modp << endl);
} else {
deepCloneModule(srcModp, cellp, paramsp, newname, ifaceRefRefs);
it = m_modNameMap.find(newname);
UASSERT(it != m_modNameMap.end(), "should find just-made module");
}
const ModInfo* modInfop = &(it->second);
return modInfop;
}
void cellPinCleanup(AstNode* nodep, AstPin* pinp, AstNodeModule* srcModp, string& longnamer,
bool& any_overridesr) {
if (!pinp->exprp()) return; // No-connect
if (AstVar* modvarp = pinp->modVarp()) {
if (!modvarp->isGParam()) {
pinp->v3error("Attempted parameter setting of non-parameter: Param "
<< pinp->prettyNameQ() << " of " << nodep->prettyNameQ());
} else if (VN_IS(pinp->exprp(), InitArray) && arraySubDTypep(modvarp->subDTypep())) {
// Array assigned to array
AstNode* exprp = pinp->exprp();
longnamer += "_" + paramSmallName(srcModp, modvarp) + paramValueNumber(exprp);
any_overridesr = true;
} else {
AstConst* exprp = VN_CAST(pinp->exprp(), Const);
AstConst* origp = VN_CAST(modvarp->valuep(), Const);
if (!exprp) {
// if (debug()) pinp->dumpTree(cout, "error:");
pinp->v3error("Can't convert defparam value to constant: Param "
<< pinp->prettyNameQ() << " of " << nodep->prettyNameQ());
pinp->exprp()->replaceWith(new AstConst(
pinp->fileline(), AstConst::WidthedValue(), modvarp->width(), 0));
} else if (origp && exprp->sameTree(origp)) {
// Setting parameter to its default value. Just ignore it.
// This prevents making additional modules, and makes coverage more
// obvious as it won't show up under a unique module page name.
} else if (exprp->num().isDouble() || exprp->num().isString()
|| exprp->num().isFourState() || exprp->num().width() != 32) {
longnamer
+= ("_" + paramSmallName(srcModp, modvarp) + paramValueNumber(exprp));
any_overridesr = true;
} else {
longnamer
+= ("_" + paramSmallName(srcModp, modvarp) + exprp->num().ascii(false));
any_overridesr = true;
}
}
} else if (AstParamTypeDType* modvarp = pinp->modPTypep()) {
AstNodeDType* exprp = VN_CAST(pinp->exprp(), NodeDType);
AstNodeDType* origp = modvarp->subDTypep();
if (!exprp) {
pinp->v3error("Parameter type pin value isn't a type: Param "
<< pinp->prettyNameQ() << " of " << nodep->prettyNameQ());
} else if (!origp) {
pinp->v3error("Parameter type variable isn't a type: Param "
<< modvarp->prettyNameQ());
} else {
UINFO(9, "Parameter type assignment expr=" << exprp << " to " << origp << endl);
if (exprp->sameTree(origp)) {
// Setting parameter to its default value. Just ignore it.
// This prevents making additional modules, and makes coverage more
// obvious as it won't show up under a unique module page name.
} else {
V3Const::constifyParamsEdit(exprp);
longnamer += "_" + paramSmallName(srcModp, modvarp) + paramValueNumber(exprp);
any_overridesr = true;
}
}
} else {
pinp->v3error("Parameter not found in sub-module: Param "
<< pinp->prettyNameQ() << " of " << nodep->prettyNameQ());
}
}
void cellInterfaceCleanup(AstCell* nodep, AstNodeModule* srcModp, string& longnamer,
bool& any_overridesr, IfaceRefRefs& ifaceRefRefs) {
for (AstPin* pinp = nodep->pinsp(); pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
AstVar* modvarp = pinp->modVarp();
if (modvarp->isIfaceRef()) {
AstIfaceRefDType* portIrefp = VN_CAST(modvarp->subDTypep(), IfaceRefDType);
if (!portIrefp && arraySubDTypep(modvarp->subDTypep())) {
portIrefp = VN_CAST(arraySubDTypep(modvarp->subDTypep()), IfaceRefDType);
}
AstIfaceRefDType* pinIrefp = nullptr;
AstNode* exprp = pinp->exprp();
AstVar* varp
= (exprp && VN_IS(exprp, VarRef)) ? VN_CAST(exprp, VarRef)->varp() : nullptr;
if (varp && varp->subDTypep() && VN_IS(varp->subDTypep(), IfaceRefDType)) {
pinIrefp = VN_CAST(varp->subDTypep(), IfaceRefDType);
} else if (varp && varp->subDTypep() && arraySubDTypep(varp->subDTypep())
&& VN_CAST(arraySubDTypep(varp->subDTypep()), IfaceRefDType)) {
pinIrefp = VN_CAST(arraySubDTypep(varp->subDTypep()), IfaceRefDType);
} else if (exprp && exprp->op1p() && VN_IS(exprp->op1p(), VarRef)
&& VN_CAST(exprp->op1p(), VarRef)->varp()
&& VN_CAST(exprp->op1p(), VarRef)->varp()->subDTypep()
&& arraySubDTypep(VN_CAST(exprp->op1p(), VarRef)->varp()->subDTypep())
&& VN_CAST(
arraySubDTypep(VN_CAST(exprp->op1p(), VarRef)->varp()->subDTypep()),
IfaceRefDType)) {
pinIrefp = VN_CAST(
arraySubDTypep(VN_CAST(exprp->op1p(), VarRef)->varp()->subDTypep()),
IfaceRefDType);
}
UINFO(9, " portIfaceRef " << portIrefp << endl);
if (!portIrefp) {
pinp->v3error("Interface port " << modvarp->prettyNameQ()
<< " is not an interface " << modvarp);
} else if (!pinIrefp) {
pinp->v3error("Interface port "
<< modvarp->prettyNameQ()
<< " is not connected to interface/modport pin expression");
} else {
UINFO(9, " pinIfaceRef " << pinIrefp << endl);
if (portIrefp->ifaceViaCellp() != pinIrefp->ifaceViaCellp()) {
UINFO(9, " IfaceRefDType needs reconnect " << pinIrefp << endl);
longnamer += ("_" + paramSmallName(srcModp, pinp->modVarp())
+ paramValueNumber(pinIrefp));
any_overridesr = true;
ifaceRefRefs.push_back(std::make_pair(portIrefp, pinIrefp));
if (portIrefp->ifacep() != pinIrefp->ifacep()
// Might be different only due to param cloning, so check names too
&& portIrefp->ifaceName() != pinIrefp->ifaceName()) {
pinp->v3error("Port " << pinp->prettyNameQ() << " expects "
<< AstNode::prettyNameQ(portIrefp->ifaceName())
<< " interface but pin connects "
<< AstNode::prettyNameQ(pinIrefp->ifaceName())
<< " interface");
}
}
}
}
}
}
public:
void cellDeparam(AstCell* nodep, AstNodeModule* modp, const string& hierName) {
m_modp = modp;
// Cell: Check for parameters in the instantiation.
// We always run this, even if no parameters, as need to look for interfaces,
// and remove any recursive references
UINFO(4, "De-parameterize: " << nodep << endl);
// Create new module name with _'s between the constants
if (debug() >= 10) nodep->dumpTree(cout, "-cell: ");
// Evaluate all module constants
V3Const::constifyParamsEdit(nodep);
AstNodeModule* srcModp = nodep->modp();
srcModp->hierName(hierName + "." + nodep->name());
// Make sure constification worked
// Must be a separate loop, as constant conversion may have changed some pointers.
// if (debug()) nodep->dumpTree(cout, "-cel2: ");
string longname = srcModp->name() + "_";
bool any_overrides = false;
// Must always clone __Vrcm (recursive modules)
if (nodep->recursive()) any_overrides = true;
if (debug() > 8) nodep->paramsp()->dumpTreeAndNext(cout, "-cellparams: ");
if (srcModp->hierBlock()) {
longname = parameterizedHierBlockName(srcModp, nodep->paramsp());
any_overrides = longname != srcModp->name();
} else {
for (AstPin* pinp = nodep->paramsp(); pinp; pinp = VN_CAST(pinp->nextp(), Pin)) {
cellPinCleanup(nodep, pinp, srcModp, longname /*ref*/, any_overrides /*ref*/);
}
}
IfaceRefRefs ifaceRefRefs;
cellInterfaceCleanup(nodep, srcModp, longname /*ref*/, any_overrides /*ref*/,
ifaceRefRefs /*ref*/);
if (!any_overrides) {
UINFO(8, "Cell parameters all match original values, skipping expansion.\n");
} else if (AstNodeModule* paramedModp
= m_hierBlocks.findByParams(srcModp->name(), nodep->paramsp(), m_modp)) {
nodep->modp(paramedModp);
nodep->modName(paramedModp->name());
paramedModp->dead(false);
// We need to relink the pins to the new module
relinkPinsByName(nodep->pinsp(), paramedModp);
} else {
const string newname
= srcModp->hierBlock() ? longname : moduleCalcName(srcModp, longname);
const ModInfo* modInfop
= moduleFindOrClone(srcModp, nodep, nodep->paramsp(), newname, ifaceRefRefs);
// Have child use this module instead.
nodep->modp(modInfop->m_modp);
nodep->modName(newname);
// We need to relink the pins to the new module
relinkPinsByName(nodep->pinsp(), modInfop->m_modp);
UINFO(8, " Done with " << modInfop->m_modp << endl);
}
nodep->recursive(false);
// Delete the parameters from the cell; they're not relevant any longer.
if (nodep->paramsp()) nodep->paramsp()->unlinkFrBackWithNext()->deleteTree();
UINFO(8, " Done with " << nodep << endl);
// if (debug() >= 10)
// v3Global.rootp()->dumpTreeFile(v3Global.debugFilename("param-out.tree"));
}
// CONSTRUCTORS
explicit ParamProcessor(AstNetlist* nodep)
: m_hierBlocks{v3Global.opt.hierBlocks(), nodep} {
for (AstNodeModule* modp = nodep->modulesp(); modp;
modp = VN_CAST(modp->nextp(), NodeModule)) {
m_allModuleNames.insert(modp->name());
}
}
~ParamProcessor() = default;
VL_UNCOPYABLE(ParamProcessor);
};
//######################################################################
// Process parameter visitor
class ParamVisitor final : public AstNVisitor {
// STATE
ParamProcessor m_processor; // De-parameterize a cell, build modules
UnrollStateful m_unroller; // Loop unroller
AstNodeModule* m_modp = nullptr; // Current module being processed
string m_generateHierName; // Generate portion of hierarchy name
string m_unlinkedTxt; // Text for AstUnlinkedRef
std::deque<AstCell*> m_cellps; // Cells left to process (in this module)
std::multimap<int, AstNodeModule*> m_todoModps; // Modules left to process
// METHODS
VL_DEBUG_FUNC; // Declare debug()
void visitCellDeparam(AstCell* nodep, const string& hierName) {
// Cell: Check for parameters in the instantiation.
iterateChildren(nodep);
UASSERT_OBJ(nodep->modp(), nodep, "Not linked?");
m_processor.cellDeparam(nodep, m_modp, hierName);
// Remember to process the child module at the end of the module
m_todoModps.emplace(nodep->modp()->level(), nodep->modp());
}
void visitModules() {
// Loop on all modules left to process
// Hitting a cell adds to the appropriate level of this level-sorted list,
// so since cells originally exist top->bottom we process in top->bottom order too.
while (!m_todoModps.empty()) {
const auto itm = m_todoModps.cbegin();
AstNodeModule* nodep = itm->second;
m_todoModps.erase(itm);
if (!nodep->user5SetOnce()) { // Process once; note clone() must clear so we do it
// again
m_modp = nodep;
UINFO(4, " MOD " << nodep << endl);
if (m_modp->hierName().empty()) m_modp->hierName(m_modp->origName());
iterateChildren(nodep);
// Note above iterate may add to m_todoModps
//
// Process interface cells, then non-interface which may ref an interface cell
for (int nonIf = 0; nonIf < 2; ++nonIf) {
for (AstCell* cellp : m_cellps) {
if ((nonIf == 0 && VN_IS(cellp->modp(), Iface))
|| (nonIf == 1 && !VN_IS(cellp->modp(), Iface))) {
string fullName(m_modp->hierName());
if (const string* genHierNamep = (string*)cellp->user5p()) {
fullName += *genHierNamep;
cellp->user5p(nullptr);
VL_DO_DANGLING(delete genHierNamep, genHierNamep);
}
VL_DO_DANGLING(visitCellDeparam(cellp, fullName), cellp);
}
}
}
m_cellps.clear();
m_modp = nullptr;
UINFO(4, " MOD-done\n");
}
}
}
// VISITORS
virtual void visit(AstNodeModule* nodep) override {
if (nodep->dead()) {
UINFO(4, " MOD-dead. " << nodep << endl); // Marked by LinkDot
return;
} else if (nodep->recursiveClone()) {
// Fake, made for recursive elimination
UINFO(4, " MOD-recursive-dead. " << nodep << endl);
nodep->dead(true); // So Dead checks won't count references to it
return;
}
//
if (!nodep->dead() && VN_IS(nodep, Class)) {
for (AstNode* stmtp = nodep->stmtsp(); stmtp; stmtp = stmtp->nextp()) {
if (AstVar* varp = VN_CAST(stmtp, Var)) {
if (varp->isParam()) {
varp->v3warn(E_UNSUPPORTED, "Unsupported: class parameters");
}
}
}
}
//
if (m_modp) {
UINFO(4, " MOD-under-MOD. " << nodep << endl);
iterateChildren(nodep);
} else if (nodep->level() <= 2 // Haven't added top yet, so level 2 is the top
|| VN_IS(nodep, Class) // Nor moved classes
|| VN_IS(nodep, Package)) { // Likewise haven't done wrapTopPackages yet
// Add request to END of modules left to process
m_todoModps.emplace(nodep->level(), nodep);
m_generateHierName = "";
visitModules();
} else if (nodep->user5()) {
UINFO(4, " MOD-done " << nodep << endl); // Already did it
} else {
// Should have been done by now, if not dead
UINFO(4, " MOD-dead? " << nodep << endl);
}
}
virtual void visit(AstCell* nodep) override {
// Must do ifaces first, so push to list and do in proper order
string* genHierNamep = new string(m_generateHierName);
nodep->user5p(genHierNamep);
m_cellps.push_back(nodep);
}
virtual void visit(AstClassRefDType* nodep) override {
if (nodep->paramsp()) {
nodep->paramsp()->v3warn(E_UNSUPPORTED, "Unsupported: parameterized classes");
pushDeletep(nodep->paramsp()->unlinkFrBackWithNext());
}
iterateChildren(nodep);
}
// Make sure all parameters are constantified
virtual void visit(AstVar* nodep) override {
if (nodep->user5SetOnce()) return; // Process once
iterateChildren(nodep);
if (nodep->isParam()) {
if (!nodep->valuep()) {
nodep->v3error("Parameter without initial value is never given value"
<< " (IEEE 1800-2017 6.20.1): " << nodep->prettyNameQ());
} else {
V3Const::constifyParamsEdit(nodep); // The variable, not just the var->init()
}
}
}
// Make sure varrefs cause vars to constify before things above
virtual void visit(AstVarRef* nodep) override {
// Might jump across functions, so beware if ever add a m_funcp
if (nodep->varp()) iterate(nodep->varp());
}
bool ifaceParamReplace(AstVarXRef* nodep, AstNode* candp) {
for (; candp; candp = candp->nextp()) {
if (nodep->name() == candp->name()) {
if (AstVar* varp = VN_CAST(candp, Var)) {
UINFO(9, "Found interface parameter: " << varp << endl);
nodep->varp(varp);
return true;
} else if (AstPin* pinp = VN_CAST(candp, Pin)) {
UINFO(9, "Found interface parameter: " << pinp << endl);
UASSERT_OBJ(pinp->exprp(), pinp, "Interface parameter pin missing expression");
VL_DO_DANGLING(nodep->replaceWith(pinp->exprp()->cloneTree(false)), nodep);
return true;
}
}
}
return false;
}
virtual void visit(AstVarXRef* nodep) override {
// Check to see if the scope is just an interface because interfaces are special
const string dotted = nodep->dotted();
if (!dotted.empty() && nodep->varp() && nodep->varp()->isParam()) {
AstNode* backp = nodep;
while ((backp = backp->backp())) {
if (VN_IS(backp, NodeModule)) {
UINFO(9, "Hit module boundary, done looking for interface" << endl);
break;
}
if (VN_IS(backp, Var) && VN_CAST(backp, Var)->isIfaceRef()
&& VN_CAST(backp, Var)->childDTypep()
&& (VN_CAST(VN_CAST(backp, Var)->childDTypep(), IfaceRefDType)
|| (VN_CAST(VN_CAST(backp, Var)->childDTypep(), UnpackArrayDType)
&& VN_CAST(VN_CAST(backp, Var)->childDTypep()->getChildDTypep(),
IfaceRefDType)))) {
AstIfaceRefDType* ifacerefp
= VN_CAST(VN_CAST(backp, Var)->childDTypep(), IfaceRefDType);
if (!ifacerefp) {
ifacerefp = VN_CAST(VN_CAST(backp, Var)->childDTypep()->getChildDTypep(),
IfaceRefDType);
}
// Interfaces passed in on the port map have ifaces
if (AstIface* ifacep = ifacerefp->ifacep()) {
if (dotted == backp->name()) {
UINFO(9, "Iface matching scope: " << ifacep << endl);
if (ifaceParamReplace(nodep, ifacep->stmtsp())) { //
return;
}
}
}
// Interfaces declared in this module have cells
else if (AstCell* cellp = ifacerefp->cellp()) {
if (dotted == cellp->name()) {
UINFO(9, "Iface matching scope: " << cellp << endl);
if (ifaceParamReplace(nodep, cellp->paramsp())) { //
return;
}
}
}
}
}
}
nodep->varp(nullptr); // Needs relink, as may remove pointed-to var
}
virtual void visit(AstUnlinkedRef* nodep) override {
AstVarXRef* varxrefp = VN_CAST(nodep->op1p(), VarXRef);
AstNodeFTaskRef* taskrefp = VN_CAST(nodep->op1p(), NodeFTaskRef);
if (varxrefp) {
m_unlinkedTxt = varxrefp->dotted();
} else if (taskrefp) {
m_unlinkedTxt = taskrefp->dotted();
} else {
nodep->v3fatalSrc("Unexpected AstUnlinkedRef node");
return;
}
iterate(nodep->cellrefp());
if (varxrefp) {
varxrefp->dotted(m_unlinkedTxt);
} else {
taskrefp->dotted(m_unlinkedTxt);
}
nodep->replaceWith(nodep->op1p()->unlinkFrBack());
VL_DO_DANGLING(pushDeletep(nodep), nodep);
}
virtual void visit(AstCellArrayRef* nodep) override {
V3Const::constifyParamsEdit(nodep->selp());
if (const AstConst* constp = VN_CAST(nodep->selp(), Const)) {
const string index = AstNode::encodeNumber(constp->toSInt());
const string replacestr = nodep->name() + "__BRA__??__KET__";
const size_t pos = m_unlinkedTxt.find(replacestr);
UASSERT_OBJ(pos != string::npos, nodep,
"Could not find array index in unlinked text: '"
<< m_unlinkedTxt << "' for node: " << nodep);
m_unlinkedTxt.replace(pos, replacestr.length(),
nodep->name() + "__BRA__" + index + "__KET__");
} else {
nodep->v3error("Could not expand constant selection inside dotted reference: "
<< nodep->selp()->prettyNameQ());
return;
}
}
// Generate Statements
virtual void visit(AstGenIf* nodep) override {
UINFO(9, " GENIF " << nodep << endl);
iterateAndNextNull(nodep->condp());
// We suppress errors when widthing params since short-circuiting in
// the conditional evaluation may mean these error can never occur. We
// then make sure that short-circuiting is used by constifyParamsEdit.
V3Width::widthGenerateParamsEdit(nodep); // Param typed widthing will
// NOT recurse the body.
V3Const::constifyGenerateParamsEdit(nodep->condp()); // condp may change
if (const AstConst* constp = VN_CAST(nodep->condp(), Const)) {
AstNode* keepp = (constp->isZero() ? nodep->elsesp() : nodep->ifsp());
if (keepp) {
keepp->unlinkFrBackWithNext();
nodep->replaceWith(keepp);
} else {
nodep->unlinkFrBack();
}
VL_DO_DANGLING(nodep->deleteTree(), nodep);
// Normal edit rules will now recurse the replacement
} else {
nodep->condp()->v3error("Generate If condition must evaluate to constant");
}
}
//! Parameter substitution for generated for loops.
//! @todo Unlike generated IF, we don't have to worry about short-circuiting the conditional
//! expression, since this is currently restricted to simple comparisons. If we ever do
//! move to more generic constant expressions, such code will be needed here.
virtual void visit(AstBegin* nodep) override {
if (nodep->genforp()) {
AstGenFor* forp = VN_CAST(nodep->genforp(), GenFor);
UASSERT_OBJ(forp, nodep, "Non-GENFOR under generate-for BEGIN");
// We should have a GENFOR under here. We will be replacing the begin,
// so process here rather than at the generate to avoid iteration problems
UINFO(9, " BEGIN " << nodep << endl);
UINFO(9, " GENFOR " << forp << endl);
V3Width::widthParamsEdit(forp); // Param typed widthing will NOT recurse the body
// Outer wrapper around generate used to hold genvar, and to ensure genvar
// doesn't conflict in V3LinkDot resolution with other genvars
// Now though we need to change BEGIN("zzz", GENFOR(...)) to
// a BEGIN("zzz__BRA__{loop#}__KET__")
const string beginName = nodep->name();
// Leave the original Begin, as need a container for the (possible) GENVAR
// Note V3Unroll will replace some AstVarRef's to the loop variable with constants
// Don't remove any deleted nodes in m_unroller until whole process finishes,
// (are held in m_unroller), as some AstXRefs may still point to old nodes.
VL_DO_DANGLING(m_unroller.unrollGen(forp, beginName), forp);
// Blocks were constructed under the special begin, move them up
// Note forp is null, so grab statements again
if (AstNode* stmtsp = nodep->genforp()) {
stmtsp->unlinkFrBackWithNext();
nodep->addNextHere(stmtsp);
// Note this clears nodep->genforp(), so begin is no longer special
}
} else {
VL_RESTORER(m_generateHierName);
m_generateHierName += "." + nodep->prettyName();
iterateChildren(nodep);
}
}
virtual void visit(AstGenFor* nodep) override { // LCOV_EXCL_LINE
nodep->v3fatalSrc("GENFOR should have been wrapped in BEGIN");
}
virtual void visit(AstGenCase* nodep) override {
UINFO(9, " GENCASE " << nodep << endl);
AstNode* keepp = nullptr;
iterateAndNextNull(nodep->exprp());
V3Case::caseLint(nodep);
V3Width::widthParamsEdit(nodep); // Param typed widthing will NOT recurse the body,
// don't trigger errors yet.
V3Const::constifyParamsEdit(nodep->exprp()); // exprp may change
AstConst* exprp = VN_CAST(nodep->exprp(), Const);
// Constify
for (AstCaseItem* itemp = nodep->itemsp(); itemp;
itemp = VN_CAST(itemp->nextp(), CaseItem)) {
for (AstNode* ep = itemp->condsp(); ep;) {
AstNode* nextp = ep->nextp(); // May edit list
iterateAndNextNull(ep);
VL_DO_DANGLING(V3Const::constifyParamsEdit(ep), ep); // ep may change
ep = nextp;
}
}
// Item match
for (AstCaseItem* itemp = nodep->itemsp(); itemp;
itemp = VN_CAST(itemp->nextp(), CaseItem)) {
if (!itemp->isDefault()) {
for (AstNode* ep = itemp->condsp(); ep; ep = ep->nextp()) {
if (const AstConst* ccondp = VN_CAST(ep, Const)) {
V3Number match(nodep, 1);
match.opEq(ccondp->num(), exprp->num());
if (!keepp && match.isNeqZero()) keepp = itemp->bodysp();
} else {
itemp->v3error("Generate Case item does not evaluate to constant");
}
}
}
}
// Else default match
for (AstCaseItem* itemp = nodep->itemsp(); itemp;
itemp = VN_CAST(itemp->nextp(), CaseItem)) {
if (itemp->isDefault()) {
if (!keepp) keepp = itemp->bodysp();
}
}
// Replace
if (keepp) {
keepp->unlinkFrBackWithNext();
nodep->replaceWith(keepp);
} else {
nodep->unlinkFrBack();
}
VL_DO_DANGLING(nodep->deleteTree(), nodep);
}
virtual void visit(AstNode* nodep) override { iterateChildren(nodep); }
public:
// CONSTRUCTORS
explicit ParamVisitor(AstNetlist* nodep)
: m_processor{nodep} {
// Relies on modules already being in top-down-order
iterate(nodep);
}
virtual ~ParamVisitor() override = default;
VL_UNCOPYABLE(ParamVisitor);
};
//######################################################################
// Param class functions
void V3Param::param(AstNetlist* rootp) {
UINFO(2, __FUNCTION__ << ": " << endl);
{ ParamVisitor visitor{rootp}; } // Destruct before checking
V3Global::dumpCheckGlobalTree("param", 0, v3Global.opt.dumpTreeLevel(__FILE__) >= 6);
}
| mballance/verilator | src/V3Param.cpp | C++ | lgpl-3.0 | 59,783 |
/*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.gui2;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import java.util.*;
/**
* BorderLayout imitates the BorderLayout class from AWT, allowing you to add a center component with optional
* components around it in top, bottom, left and right locations. The edge components will be sized at their preferred
* size and the center component will take up whatever remains.
* @author martin
*/
public class BorderLayout implements LayoutManager {
/**
* This type is what you use as the layout data for components added to a panel using {@code BorderLayout} for its
* layout manager. This values specified where inside the panel the component should be added.
*/
public enum Location implements LayoutData {
/**
* The component with this value as its layout data will occupy the center space, whatever is remaining after
* the other components (if any) have allocated their space.
*/
CENTER,
/**
* The component with this value as its layout data will occupy the left side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
LEFT,
/**
* The component with this value as its layout data will occupy the right side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
RIGHT,
/**
* The component with this value as its layout data will occupy the top side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
TOP,
/**
* The component with this value as its layout data will occupy the bottom side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
BOTTOM,
;
}
//When components don't have a location, we'll assign an available location based on this order
private static final List<Location> AUTO_ASSIGN_ORDER = Collections.unmodifiableList(Arrays.asList(
Location.CENTER,
Location.TOP,
Location.BOTTOM,
Location.LEFT,
Location.RIGHT));
@Override
public TerminalSize getPreferredSize(List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int preferredHeight =
(layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getRows() : 0)
+
Math.max(
layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getRows() : 0,
Math.max(
layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getRows() : 0,
layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getRows() : 0))
+
(layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getRows() : 0);
int preferredWidth =
Math.max(
(layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getColumns() : 0),
Math.max(
layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getColumns() : 0,
layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getColumns() : 0));
return new TerminalSize(preferredWidth, preferredHeight);
}
@Override
public void doLayout(TerminalSize area, List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int availableHorizontalSpace = area.getColumns();
int availableVerticalSpace = area.getRows();
//We'll need this later on
int topComponentHeight = 0;
int leftComponentWidth = 0;
//First allocate the top
if(layout.containsKey(Location.TOP)) {
Component topComponent = layout.get(Location.TOP);
topComponentHeight = Math.min(topComponent.getPreferredSize().getRows(), availableVerticalSpace);
topComponent.setPosition(TerminalPosition.TOP_LEFT_CORNER);
topComponent.setSize(new TerminalSize(availableHorizontalSpace, topComponentHeight));
availableVerticalSpace -= topComponentHeight;
}
//Next allocate the bottom
if(layout.containsKey(Location.BOTTOM)) {
Component bottomComponent = layout.get(Location.BOTTOM);
int bottomComponentHeight = Math.min(bottomComponent.getPreferredSize().getRows(), availableVerticalSpace);
bottomComponent.setPosition(new TerminalPosition(0, area.getRows() - bottomComponentHeight));
bottomComponent.setSize(new TerminalSize(availableHorizontalSpace, bottomComponentHeight));
availableVerticalSpace -= bottomComponentHeight;
}
//Now divide the remaining space between LEFT, CENTER and RIGHT
if(layout.containsKey(Location.LEFT)) {
Component leftComponent = layout.get(Location.LEFT);
leftComponentWidth = Math.min(leftComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
leftComponent.setPosition(new TerminalPosition(0, topComponentHeight));
leftComponent.setSize(new TerminalSize(leftComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= leftComponentWidth;
}
if(layout.containsKey(Location.RIGHT)) {
Component rightComponent = layout.get(Location.RIGHT);
int rightComponentWidth = Math.min(rightComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
rightComponent.setPosition(new TerminalPosition(area.getColumns() - rightComponentWidth, topComponentHeight));
rightComponent.setSize(new TerminalSize(rightComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= rightComponentWidth;
}
if(layout.containsKey(Location.CENTER)) {
Component centerComponent = layout.get(Location.CENTER);
centerComponent.setPosition(new TerminalPosition(leftComponentWidth, topComponentHeight));
centerComponent.setSize(new TerminalSize(availableHorizontalSpace, availableVerticalSpace));
}
//Set the remaining components to 0x0
for(Component component: components) {
if(component.isVisible() && !layout.containsValue(component)) {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
component.setSize(TerminalSize.ZERO);
}
}
}
private EnumMap<Location, Component> makeLookupMap(List<Component> components) {
EnumMap<Location, Component> map = new EnumMap<>(Location.class);
List<Component> unassignedComponents = new ArrayList<>();
for(Component component: components) {
if (!component.isVisible()) {
continue;
}
if(component.getLayoutData() instanceof Location) {
map.put((Location)component.getLayoutData(), component);
}
else {
unassignedComponents.add(component);
}
}
//Try to assign components to available locations
for(Component component: unassignedComponents) {
for(Location location: AUTO_ASSIGN_ORDER) {
if(!map.containsKey(location)) {
map.put(location, component);
break;
}
}
}
return map;
}
@Override
public boolean hasChanged() {
//No internal state
return false;
}
}
| mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/BorderLayout.java | Java | lgpl-3.0 | 9,401 |
package br.com.zpi.lrws.conn;
import java.io.Serializable;
public class DBParVal implements Serializable{
private static final long serialVersionUID = 1L;
public String param = null;
public String value = null;
}
| leonardoroese/LRWS | lrws/src/br/com/zpi/lrws/conn/DBParVal.java | Java | lgpl-3.0 | 220 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.security;
import org.sonar.api.database.BaseIdentifiable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* This JPA model maps the table user_roles
*
* @since 1.12
*/
@Entity
@Table(name = "user_roles")
public class UserRole extends BaseIdentifiable {
@Column(name = "user_id")
private Integer userId;
@Column(name = "role")
private String role;
@Column(name = "resource_id")
private Integer resourceId;
public UserRole(Integer userId, String role, Integer resourceId) {
this.userId = userId;
this.role = role;
this.resourceId = resourceId;
}
public UserRole() {
}
public Integer getUserId() {
return userId;
}
public UserRole setUserId(Integer userId) {
this.userId = userId;
return this;
}
public String getRole() {
return role;
}
public UserRole setRole(String role) {
this.role = role;
return this;
}
public Integer getResourceId() {
return resourceId;
}
public UserRole setResourceId(Integer resourceId) {
this.resourceId = resourceId;
return this;
}
}
| yangjiandong/appjruby | app-plugin-api/src/main/java/org/sonar/api/security/UserRole.java | Java | lgpl-3.0 | 1,994 |
/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.sample;
import java.util.Date;
import org.alfresco.web.bean.LoginBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CustomLoginBean extends LoginBean
{
private static final Log logger = LogFactory.getLog(CustomLoginBean.class);
@Override
public String login()
{
String outcome = super.login();
// log to the console who logged in and when
String username = this.getUsername();
if (username == null)
{
username = "Guest";
}
logger.info(username + " has logged in at " + new Date());
return outcome;
}
@Override
public String logout()
{
String outcome = super.logout();
// log to the console who logged out and when
String username = this.getUsername();
if (username == null)
{
username = "Guest";
}
logger.info(username + " logged out at " + new Date());
return outcome;
}
}
| loftuxab/community-edition-old | projects/sdk/samples/CustomLogin/source/org/alfresco/sample/CustomLoginBean.java | Java | lgpl-3.0 | 1,790 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\utils;
use LogLevel;
use pocketmine\Thread;
use pocketmine\Worker;
class MainLogger extends \AttachableThreadedLogger{
protected $logFile;
protected $logStream;
protected $shutdown;
protected $logDebug;
private $logResource;
/** @var MainLogger */
public static $logger = null;
/**
* @param string $logFile
* @param bool $logDebug
*
* @throws \RuntimeException
*/
public function __construct($logFile, $logDebug = false){
parent::__construct();
if(static::$logger instanceof MainLogger){
throw new \RuntimeException("MainLogger has been already created");
}
static::$logger = $this;
$this->logStream = new \Threaded;
$this->start();
}
/**
* @return MainLogger
*/
public static function getLogger(){
return static::$logger;
}
/**
* Assigns the MainLogger instance to the {@link MainLogger#logger} static property.
*
* WARNING: Because static properties are thread-local, this MUST be called from the body of every Thread if you
* want the logger to be accessible via {@link MainLogger#getLogger}.
*/
public function registerStatic(){
if(static::$logger === null){
static::$logger = $this;
}
}
public function emergency($message){
$this->send($message, \LogLevel::EMERGENCY, "EMERGENCY", TextFormat::RED);
}
public function alert($message){
$this->send($message, \LogLevel::ALERT, "ALERT", TextFormat::RED);
}
public function critical($message){
$this->send($message, \LogLevel::CRITICAL, "CRITICAL", TextFormat::RED);
}
public function error($message){
$this->send($message, \LogLevel::ERROR, "ERROR", TextFormat::DARK_RED);
}
public function warning($message){
$this->send($message, \LogLevel::WARNING, "WARNING", TextFormat::YELLOW);
}
public function notice($message){
$this->send($message, \LogLevel::NOTICE, "NOTICE", TextFormat::AQUA);
}
public function info($message){
$this->send($message, \LogLevel::INFO, "INFO", TextFormat::WHITE);
}
public function debug($message){
if($this->logDebug === false){
return;
}
$this->send($message, \LogLevel::DEBUG, "DEBUG", TextFormat::GRAY);
}
/**
* @param bool $logDebug
*/
public function setLogDebug($logDebug){
$this->logDebug = (bool) $logDebug;
}
public function logException(\Throwable $e, $trace = null){
if($trace === null){
$trace = $e->getTrace();
}
$errstr = $e->getMessage();
$errfile = $e->getFile();
$errno = $e->getCode();
$errline = $e->getLine();
$errorConversion = [
0 => "EXCEPTION",
E_ERROR => "E_ERROR",
E_WARNING => "E_WARNING",
E_PARSE => "E_PARSE",
E_NOTICE => "E_NOTICE",
E_CORE_ERROR => "E_CORE_ERROR",
E_CORE_WARNING => "E_CORE_WARNING",
E_COMPILE_ERROR => "E_COMPILE_ERROR",
E_COMPILE_WARNING => "E_COMPILE_WARNING",
E_USER_ERROR => "E_USER_ERROR",
E_USER_WARNING => "E_USER_WARNING",
E_USER_NOTICE => "E_USER_NOTICE",
E_STRICT => "E_STRICT",
E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
E_DEPRECATED => "E_DEPRECATED",
E_USER_DEPRECATED => "E_USER_DEPRECATED",
];
if($errno === 0){
$type = LogLevel::CRITICAL;
}else{
$type = ($errno === E_ERROR or $errno === E_USER_ERROR) ? LogLevel::ERROR : (($errno === E_USER_WARNING or $errno === E_WARNING) ? LogLevel::WARNING : LogLevel::NOTICE);
}
$errno = isset($errorConversion[$errno]) ? $errorConversion[$errno] : $errno;
if(($pos = strpos($errstr, "\n")) !== false){
$errstr = substr($errstr, 0, $pos);
}
$errfile = \pocketmine\cleanPath($errfile);
$this->log($type, get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline");
foreach(@\pocketmine\getTrace(1, $trace) as $i => $line){
$this->debug($line);
}
}
public function log($level, $message){
switch($level){
case LogLevel::EMERGENCY:
$this->emergency($message);
break;
case LogLevel::ALERT:
$this->alert($message);
break;
case LogLevel::CRITICAL:
$this->critical($message);
break;
case LogLevel::ERROR:
$this->error($message);
break;
case LogLevel::WARNING:
$this->warning($message);
break;
case LogLevel::NOTICE:
$this->notice($message);
break;
case LogLevel::INFO:
$this->info($message);
break;
case LogLevel::DEBUG:
$this->debug($message);
break;
}
}
public function shutdown(){
$this->shutdown = true;
}
protected function send($message, $level, $prefix, $color){
$now = time();
$thread = \Thread::getCurrentThread();
if($thread === null){
$threadName = "Server thread";
}elseif($thread instanceof Thread or $thread instanceof Worker){
$threadName = $thread->getThreadName() . " thread";
}else{
$threadName = (new \ReflectionClass($thread))->getShortName() . " thread";
}
$message = TextFormat::toANSI(TextFormat::AQUA . "[" . date("H:i:s", $now) . "] ". TextFormat::RESET . $color ."[" . $threadName . "/" . $prefix . "]:" . " " . $message . TextFormat::RESET);
$cleanMessage = TextFormat::clean($message);
if(!Terminal::hasFormattingCodes()){
echo $cleanMessage . PHP_EOL;
}else{
echo $message . PHP_EOL;
}
if($this->attachment instanceof \ThreadedLoggerAttachment){
$this->attachment->call($level, $message);
}
$this->logStream[] = date("Y-m-d", $now) . " " . $cleanMessage . "\n";
if($this->logStream->count() === 1){
$this->synchronized(function(){
$this->notify();
});
}
}
public function run(){
$this->shutdown = false;
}
} | ConflictPE/Extropy | src/pocketmine/utils/MainLogger.php | PHP | lgpl-3.0 | 6,162 |
/*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo 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.
*
* JLaTo 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 JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.internal.td.expr;
import org.jlato.internal.bu.expr.SBinaryExpr;
import org.jlato.internal.bu.expr.SExpr;
import org.jlato.internal.td.TDLocation;
import org.jlato.internal.td.TDTree;
import org.jlato.tree.Kind;
import org.jlato.tree.expr.BinaryExpr;
import org.jlato.tree.expr.BinaryOp;
import org.jlato.tree.expr.Expr;
import org.jlato.util.Mutation;
/**
* A binary expression.
*/
public class TDBinaryExpr extends TDTree<SBinaryExpr, Expr, BinaryExpr> implements BinaryExpr {
/**
* Returns the kind of this binary expression.
*
* @return the kind of this binary expression.
*/
public Kind kind() {
return Kind.BinaryExpr;
}
/**
* Creates a binary expression for the specified tree location.
*
* @param location the tree location.
*/
public TDBinaryExpr(TDLocation<SBinaryExpr> location) {
super(location);
}
/**
* Creates a binary expression with the specified child trees.
*
* @param left the left child tree.
* @param op the op child tree.
* @param right the right child tree.
*/
public TDBinaryExpr(Expr left, BinaryOp op, Expr right) {
super(new TDLocation<SBinaryExpr>(SBinaryExpr.make(TDTree.<SExpr>treeOf(left), op, TDTree.<SExpr>treeOf(right))));
}
/**
* Returns the left of this binary expression.
*
* @return the left of this binary expression.
*/
public Expr left() {
return location.safeTraversal(SBinaryExpr.LEFT);
}
/**
* Replaces the left of this binary expression.
*
* @param left the replacement for the left of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withLeft(Expr left) {
return location.safeTraversalReplace(SBinaryExpr.LEFT, left);
}
/**
* Mutates the left of this binary expression.
*
* @param mutation the mutation to apply to the left of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withLeft(Mutation<Expr> mutation) {
return location.safeTraversalMutate(SBinaryExpr.LEFT, mutation);
}
/**
* Returns the op of this binary expression.
*
* @return the op of this binary expression.
*/
public BinaryOp op() {
return location.safeProperty(SBinaryExpr.OP);
}
/**
* Replaces the op of this binary expression.
*
* @param op the replacement for the op of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withOp(BinaryOp op) {
return location.safePropertyReplace(SBinaryExpr.OP, op);
}
/**
* Mutates the op of this binary expression.
*
* @param mutation the mutation to apply to the op of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withOp(Mutation<BinaryOp> mutation) {
return location.safePropertyMutate(SBinaryExpr.OP, mutation);
}
/**
* Returns the right of this binary expression.
*
* @return the right of this binary expression.
*/
public Expr right() {
return location.safeTraversal(SBinaryExpr.RIGHT);
}
/**
* Replaces the right of this binary expression.
*
* @param right the replacement for the right of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withRight(Expr right) {
return location.safeTraversalReplace(SBinaryExpr.RIGHT, right);
}
/**
* Mutates the right of this binary expression.
*
* @param mutation the mutation to apply to the right of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withRight(Mutation<Expr> mutation) {
return location.safeTraversalMutate(SBinaryExpr.RIGHT, mutation);
}
}
| ptitjes/jlato | src/main/java/org/jlato/internal/td/expr/TDBinaryExpr.java | Java | lgpl-3.0 | 4,384 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char text[40], text2[40];
printf("necesito una buena palabra: ");
gets(text);
printf("voy a necesitar otra palabra, si es la misma sorpresa... \n");
gets(text2);
if (strcmp(text, text2) ==0)
printf("Correcto!! son iguales enhorabuena \n");
else
printf("pues nada son distintas, no haces caso... \n" );
return EXIT_SUCCESS;
}
| alexgcr33/C-on_my_own | arrays2/pass.cpp | C++ | lgpl-3.0 | 421 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.language.ws;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.regex.Pattern;
/**
* @since 5.1
*/
public class ListAction implements RequestHandler {
private static final String MATCH_ALL = ".*";
private final Languages languages;
public ListAction(Languages languages) {
this.languages = languages;
}
@Override
public void handle(Request request, Response response) throws Exception {
String query = request.param(Param.TEXT_QUERY);
int pageSize = request.mandatoryParamAsInt("ps");
JsonWriter json = response.newJsonWriter().beginObject().name("languages").beginArray();
for (Language language : listMatchingLanguages(query, pageSize)) {
json.beginObject().prop("key", language.getKey()).prop("name", language.getName()).endObject();
}
json.endArray().endObject().close();
}
void define(WebService.NewController controller) {
NewAction action = controller.createAction("list")
.setDescription("List supported programming languages")
.setSince("5.1")
.setHandler(this)
.setResponseExample(Resources.getResource(getClass(), "example-list.json"));
action.createParam(Param.TEXT_QUERY)
.setDescription("A pattern to match language keys/names against")
.setExampleValue("java");
action.createParam("ps")
.setDescription("The size of the list to return, 0 for all languages")
.setExampleValue("25")
.setDefaultValue("0");
}
private Collection<Language> listMatchingLanguages(@Nullable String query, int pageSize) {
Pattern pattern = Pattern.compile(query == null ? MATCH_ALL : MATCH_ALL + Pattern.quote(query) + MATCH_ALL, Pattern.CASE_INSENSITIVE);
SortedMap<String, Language> languagesByName = Maps.newTreeMap();
for (Language lang : languages.all()) {
if (pattern.matcher(lang.getKey()).matches() || pattern.matcher(lang.getName()).matches()) {
languagesByName.put(lang.getName(), lang);
}
}
List<Language> result = Lists.newArrayList(languagesByName.values());
if (pageSize > 0 && pageSize < result.size()) {
result = result.subList(0, pageSize);
}
return result;
}
}
| lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/language/ws/ListAction.java | Java | lgpl-3.0 | 3,630 |
package com.bsgcoach.web;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.wicket.Page;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import com.bsgcoach.web.footer.FooterPanel;
import com.bsgcoach.web.guide.RedirectToGuidePage;
import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarButton;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarComponents;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarExternalLink;
import de.invesdwin.nowicket.application.AWebPage;
import de.invesdwin.nowicket.application.auth.ABaseWebApplication;
import de.invesdwin.nowicket.application.filter.AWebApplication;
import de.invesdwin.nowicket.component.footer.AFooter;
@NotThreadSafe
public abstract class ABsgCoachWebPage extends AWebPage {
private static final boolean INVERTED_HEADER_AND_FOOTER = true;
private static final ResourceReference LOGO = new PackageResourceReference(ABsgCoachWebPage.class, "logo.png");
private static final PackageResourceReference BACKGROUND = new PackageResourceReference(ABsgCoachWebPage.class,
"bg.jpg");
public ABsgCoachWebPage(final IModel<?> model) {
super(model);
}
@Override
protected Navbar newNavbar(final String id) {
final Navbar navbar = super.newNavbar(id);
navbar.setBrandName(null);
navbar.setBrandImage(LOGO, Model.of("bsg-coach"));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT,
new NavbarButton<Void>(RedirectToGuidePage.class, Model.of("Home")).setIconType(GlyphIconType.home)));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT,
new NavbarButton<Void>(ABaseWebApplication.get().getHomePage(), Model.of("Get Feedback"))
.setIconType(GlyphIconType.upload)));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT,
new NavbarExternalLink(Model.of("mailto:gsubes@gmail.com"))
.setLabel(Model.of("Tell us what you think!")).setIconType(GlyphIconType.envelope)));
navbar.setInverted(INVERTED_HEADER_AND_FOOTER);
return navbar;
}
@Override
protected Class<? extends Page> getNavbarHomePage() {
return RedirectToGuidePage.class;
}
@Override
protected AFooter newFooter(final String id) {
return new FooterPanel(id);
}
@Override
public void renderHead(final IHeaderResponse response) {
super.renderHead(response);
final StringBuilder bgCss = new StringBuilder();
bgCss.append("body {\n");
bgCss.append(" background: url(");
bgCss.append(RequestCycle.get().urlFor(BACKGROUND, null));
bgCss.append(") no-repeat center center fixed;\n");
bgCss.append("}\n");
bgCss.append("nav {\n");
bgCss.append(" opacity: 0.75;\n");
bgCss.append("}\n");
bgCss.append(".footer .panel-footer {\n");
bgCss.append(" background-color: #222;\n");
bgCss.append(" border-color: #080808;\n");
bgCss.append(" opacity: 0.75;\n");
bgCss.append("}\n");
response.render(CssHeaderItem.forCSS(bgCss, "bsgBgCss"));
if (AWebApplication.get().usesDeploymentConfig()) {
//CHECKSTYLE:OFF fdate
response.render(JavaScriptHeaderItem
.forScript("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" //
+ "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," //
+ "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" //
+ "})(window,document,'script','//www.google-analytics.com/analytics.js','ga');" //
+ "ga('create', 'UA-75774568-1', 'auto');" //
+ "ga('send', 'pageview');", "googleAnalytics"));
//CHECKSTYLE:ON
}
}
}
| subes/invesdwin-nowicket | invesdwin-nowicket-examples/invesdwin-nowicket-examples-mvp-bsgcoach/src/main/java/com/bsgcoach/web/ABsgCoachWebPage.java | Java | lgpl-3.0 | 4,610 |
<?php
/**
* This file is part of the highcharts-bundle package.
*
* (c) 2017 WEBEWEB
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover;
use JsonSerializable;
use WBW\Library\Core\Utility\Argument\ArrayUtility;
/**
* Highcharts marker.
*
* @author webeweb <https://github.com/webeweb/>
* @package WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover
* @version 5.0.14
* @final
*/
final class HighchartsMarker implements JsonSerializable {
/**
* Enabled.
*
* @var boolean
*/
private $enabled;
/**
* Fill color.
*
* @var string
*/
private $fillColor;
/**
* Height.
*
* @var integer
* @since 4.0.4
*/
private $height;
/**
* Line color.
*
* @var string
*/
private $lineColor = "#ffffff";
/**
* Line width.
*
* @var integer
*/
private $lineWidth = 0;
/**
* Radius.
*
* @var integer
*/
private $radius = 4;
/**
* States.
*
* @var
*/
private $states;
/**
* Symbol.
*
* @var string
*/
private $symbol;
/**
* Width.
*
* @var integer
* @since 4.0.4
*/
private $width;
/**
* Constructor.
*
* @param boolean $ignoreDefaultValues Ignore the default values.
*/
public function __construct($ignoreDefaultValues = true) {
if (true === $ignoreDefaultValues) {
$this->clear();
}
}
/**
* Clear.
*
* @return void
*/
public function clear() {
// Clear the enabled.
$this->enabled = null;
// Clear the fill color.
$this->fillColor = null;
// Clear the height.
$this->height = null;
// Clear the line color.
$this->lineColor = null;
// Clear the line width.
$this->lineWidth = null;
// Clear the radius.
$this->radius = null;
// Clear the states.
$this->states = null;
// Clear the symbol.
$this->symbol = null;
// Clear the width.
$this->width = null;
}
/**
* Get the enabled.
*
* @return boolean Returns the enabled.
*/
public function getEnabled() {
return $this->enabled;
}
/**
* Get the fill color.
*
* @return string Returns the fill color.
*/
public function getFillColor() {
return $this->fillColor;
}
/**
* Get the height.
*
* @return integer Returns the height.
*/
public function getHeight() {
return $this->height;
}
/**
* Get the line color.
*
* @return string Returns the line color.
*/
public function getLineColor() {
return $this->lineColor;
}
/**
* Get the line width.
*
* @return integer Returns the line width.
*/
public function getLineWidth() {
return $this->lineWidth;
}
/**
* Get the radius.
*
* @return integer Returns the radius.
*/
public function getRadius() {
return $this->radius;
}
/**
* Get the states.
*
* @return Returns the states.
*/
public function getStates() {
return $this->states;
}
/**
* Get the symbol.
*
* @return string Returns the symbol.
*/
public function getSymbol() {
return $this->symbol;
}
/**
* Get the width.
*
* @return integer Returns the width.
*/
public function getWidth() {
return $this->width;
}
/**
* Serialize this instance.
*
* @return array Returns an array representing this instance.
*/
public function jsonSerialize() {
return $this->toArray();
}
/**
* Set the enabled.
*
* @param boolean $enabled The enabled.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setEnabled($enabled) {
$this->enabled = $enabled;
return $this;
}
/**
* Set the fill color.
*
* @param string $fillColor The fill color.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setFillColor($fillColor) {
$this->fillColor = $fillColor;
return $this;
}
/**
* Set the height.
*
* @param integer $height The height.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setHeight($height) {
$this->height = $height;
return $this;
}
/**
* Set the line color.
*
* @param string $lineColor The line color.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setLineColor($lineColor) {
$this->lineColor = $lineColor;
return $this;
}
/**
* Set the line width.
*
* @param integer $lineWidth The line width.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setLineWidth($lineWidth) {
$this->lineWidth = $lineWidth;
return $this;
}
/**
* Set the radius.
*
* @param integer $radius The radius.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setRadius($radius) {
$this->radius = $radius;
return $this;
}
/**
* Set the states.
*
* @param $states The states.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setStates($states) {
$this->states = $states;
return $this;
}
/**
* Set the symbol.
*
* @param string $symbol The symbol.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setSymbol($symbol) {
switch ($symbol) {
case null:
case "circle":
case "diamond":
case "square":
case "triangle":
case "triangle-down":
$this->symbol = $symbol;
break;
}
return $this;
}
/**
* Set the width.
*
* @param integer $width The width.
* @return \WBW\Bundle\HighchartsBundle\API\Chart\Series\Polygon\States\Hover\HighchartsMarker Returns the highcharts marker.
*/
public function setWidth($width) {
$this->width = $width;
return $this;
}
/**
* Convert into an array representing this instance.
*
* @return array Returns an array representing this instance.
*/
public function toArray() {
// Initialize the output.
$output = [];
// Set the enabled.
ArrayUtility::set($output, "enabled", $this->enabled, [null]);
// Set the fill color.
ArrayUtility::set($output, "fillColor", $this->fillColor, [null]);
// Set the height.
ArrayUtility::set($output, "height", $this->height, [null]);
// Set the line color.
ArrayUtility::set($output, "lineColor", $this->lineColor, [null]);
// Set the line width.
ArrayUtility::set($output, "lineWidth", $this->lineWidth, [null]);
// Set the radius.
ArrayUtility::set($output, "radius", $this->radius, [null]);
// Set the states.
ArrayUtility::set($output, "states", $this->states, [null]);
// Set the symbol.
ArrayUtility::set($output, "symbol", $this->symbol, [null]);
// Set the width.
ArrayUtility::set($output, "width", $this->width, [null]);
// Return the output.
return $output;
}
}
| webeweb/WBWHighchartsBundle | API/Chart/Series/Polygon/States/Hover/HighchartsMarker.php | PHP | lgpl-3.0 | 8,387 |
package Chapter7;
/**
* Created by PuFan on 2016/11/30.
*
* @author PuFan
*/
public class ThreadSleep {
static public void main(String[] args) {
Thread t1 = new Thread(new SleepRunner());
Thread t2 = new Thread(new SleepRunner1());
t1.start();
t2.start();
}
}
class SleepRunner implements Runnable {
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 1000; ++i)
System.out.println("Sleep " + i);
}
}
class SleepRunner1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; ++i)
System.out.println("Normal " + i);
}
} | luobuccc/JavaPD | Chapter7/src/Chapter7/ThreadSleep.java | Java | lgpl-3.0 | 761 |
#!/usr/bin/env python3
"""
This script edits your backends conf file by replacing stuff like:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = 78910
with:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = `pass show weboob/bnporc21`
"""
from __future__ import print_function
import os
import re
import shutil
import subprocess
import sys
import tempfile
FILE = os.getenv('WEBOOB_BACKENDS') or os.path.expanduser('~/.config/weboob/backends')
if not os.path.exists(FILE):
print('the backends file does not exist')
sys.exit(os.EX_NOINPUT)
if not shutil.which('pass'):
print('the "pass" tool could not be found')
sys.exit(os.EX_UNAVAILABLE)
errors = 0
seen = set()
backend = None
with open(FILE) as inp:
with tempfile.NamedTemporaryFile('w', delete=False, dir=os.path.dirname(FILE)) as outp:
for line in inp:
line = line.strip()
mtc = re.match(r'password\s*=\s*(\S.*)$', line)
if mtc and not mtc.group(1).startswith('`'):
cmd = ['pass', 'insert', 'weboob/%s' % backend]
stdin = 2 * ('%s\n' % mtc.group(1))
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.communicate(stdin.encode('utf-8'))
if proc.returncode == 0:
print('password = `pass show weboob/%s`' % backend, file=outp)
continue
else:
errors += 1
print('warning: could not store password for backend %r' % backend)
mtc = re.match(r'\[(.+)\]', line)
if mtc:
backend = mtc.group(1)
if backend in seen:
print('error: backend %r is present multiple times' % backend)
sys.exit(os.EX_DATAERR)
seen.add(backend)
print(line, file=outp)
os.rename(outp.name, FILE)
if errors:
print('%d errors were encountered when storing passwords securely' % errors)
sys.exit(2)
| vicnet/weboob | contrib/replace-backends-pass.py | Python | lgpl-3.0 | 2,065 |
# -*- coding: utf-8 -*-
import oauth2 # XXX pumazi: factor this out
from webob.multidict import MultiDict, NestedMultiDict
from webob.request import Request as WebObRequest
__all__ = ['Request']
class Request(WebObRequest):
"""The OAuth version of the WebOb Request.
Provides an easier way to obtain OAuth request parameters
(e.g. oauth_token) from the WSGI environment."""
def _checks_positive_for_oauth(self, params_var):
"""Simple check for the presence of OAuth parameters."""
checks = [ p.find('oauth_') >= 0 for p in params_var ]
return True in checks
@property
def str_oauth_header(self):
extracted = {}
# Check for OAuth in the Header
if 'authorization' in self.headers:
auth_header = self.headers['authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header.lstrip('OAuth ')
try:
# Extract the parameters from the header.
extracted = oauth2.Request._split_header(auth_header)
except:
raise Error('Unable to parse OAuth parameters from '
'the Authorization header.')
return extracted
@property
def str_oauth_POST(self):
extracted = {}
if self._checks_positive_for_oauth(self.str_POST):
extracted = dict([ (k, v,) for k, v in self.str_POST.iteritems()
if (k.find('oauth_') >= 0) ])
return extracted
@property
def str_oauth_GET(self):
extracted = {}
if self._checks_positive_for_oauth(self.str_GET):
extracted = dict([ (k, v,) for k, v in self.str_GET.iteritems()
if (k.find('oauth_') >= 0) ])
return extracted
def params(self):
params = WebObRequest.params.fget(self)
return NestedMultiDict(params, self.str_oauth_header)
params = property(params, doc=WebObRequest.params.__doc__)
@property
def oauth_params(self):
"""Simple way to get the OAuth parameters without sifting through
the entire stack of parameters.
We check the header first, because it is low hanging fruit.
However, it would be more efficient to check for the POSTed
parameters, because the specification defines the POST method as the
recommended request type before using GET or the Authorization
header."""
extracted = {}
# OAuth in the Header
extracted.update(self.str_oauth_header)
# OAuth in a GET or POST method
extracted.update(self.str_oauth_GET)
extracted.update(self.str_oauth_POST)
# Return the extracted oauth variables
return MultiDict(extracted)
@property
def nonoauth_params(self):
"""Simple way to get the non-OAuth parameters from the request."""
oauth_param_keys = self.oauth_params.keys()
return dict([(k, v) for k, v in self.params.iteritems() if k not in oauth_param_keys])
| karacos/karacos-wsgi | lib/wsgioauth/request.py | Python | lgpl-3.0 | 3,175 |
/****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
package edu.ucla.stat.SOCR.experiments;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import edu.ucla.stat.SOCR.core.*;
import edu.ucla.stat.SOCR.distributions.*;
import edu.ucla.stat.SOCR.util.*;
/** The basic casino craps game */
public class CrapsExperiment extends Experiment {
//Constants
public final static int PASS = 0, DONTPASS = 1, FIELD = 2, CRAPS = 3,
CRAPS2 = 4, CRAPS3 = 5, CRAPS12 = 6, SEVEN = 7, ELEVEN = 8, BIG6 = 9,
BIG8 = 10, HARDWAY4 = 11, HARDWAY6 = 12, HARDWAY8 = 13, HARDWAY10 = 14;
//Variables
private int x, y, u, v, point1, point2, win, rolls, betType = PASS;
private double[] prob = new double[] { 251.0 / 495, 0, 244.0 / 495 };
//Objects
private JPanel toolbar = new JPanel();
private DiceBoard diceBoard = new DiceBoard(4);
private JComboBox<String> betJComboBox = new JComboBox<>();
private FiniteDistribution dist = new FiniteDistribution(-1, 1, 1, prob);
private RandomVariable profitRV = new RandomVariable(dist, "W");
private RandomVariableGraph profitGraph = new RandomVariableGraph(profitRV);
private RandomVariableTable profitTable = new RandomVariableTable(profitRV);
/** Initialize the experiment */
public CrapsExperiment() {
setName("Craps Experiment");
//Event listeners
betJComboBox.addItemListener(this);
//Bet choice
betJComboBox.addItem("Pass");
betJComboBox.addItem("Don't Pass");
betJComboBox.addItem("Field");
betJComboBox.addItem("Craps");
betJComboBox.addItem("Craps 2");
betJComboBox.addItem("Craps 3");
betJComboBox.addItem("Craps 12");
betJComboBox.addItem("Seven");
betJComboBox.addItem("Eleven");
betJComboBox.addItem("Big 6");
betJComboBox.addItem("Big 8");
betJComboBox.addItem("Hardway 4");
betJComboBox.addItem("Hardway 6");
betJComboBox.addItem("Hardway 8");
betJComboBox.addItem("Hardway 10");
//toolbars
toolbar.setLayout(new FlowLayout(FlowLayout.CENTER));
toolbar.add(betJComboBox);
addToolbar(toolbar);
//Graphs
addGraph(diceBoard);
addGraph(profitGraph);
//Table
addTable(profitTable);
reset();
}
/**
* Perform the experiment: roll the dice, and depending on the bet,
* determine whether to roll the dice a second time. Finally, deterimine the
* outcome of the bet
*/
public void doExperiment() {
super.doExperiment();
rolls = 1;
x = (int) Math.ceil(6 * Math.random());
y = (int) Math.ceil(6 * Math.random());
point1 = x + y;
point2 = 0;
switch (betType) {
case PASS:
if (point1 == 7 | point1 == 11) win = 1;
else if (point1 == 2 | point1 == 3 | point1 == 12) win = -1;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = 1;
else win = -1;
}
break;
case DONTPASS:
if (point1 == 7 | point1 == 11) win = -1;
else if (point1 == 2 | point1 == 3) win = 1;
else if (point1 == 12) win = 0;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = -1;
else win = 1;
}
break;
case FIELD:
if (point1 == 3 | point1 == 4 | point1 == 9 | point1 == 10
| point1 == 11) win = 1;
else if (point1 == 2 | point1 == 12) win = 2;
else win = -1;
break;
case CRAPS:
if (point1 == 2 | point1 == 3 | point1 == 12) win = 7;
else win = -1;
break;
case CRAPS2:
if (point1 == 2) win = 30;
else win = -1;
break;
case CRAPS3:
if (point1 == 3) win = 15;
else win = -1;
break;
case CRAPS12:
if (point1 == 12) win = 30;
else win = -1;
break;
case SEVEN:
if (point1 == 7) win = 4;
else win = -1;
break;
case ELEVEN:
if (point1 == 11) win = 15;
else win = -1;
break;
case BIG6:
if (point1 == 6) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 6 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 6) win = 1;
else win = -1;
}
break;
case BIG8:
if (point1 == 8) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 8 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 8) win = 1;
else win = -1;
}
break;
case HARDWAY4:
if (x == 2 & y == 2) win = 7;
else if (point1 == 7 | point1 == 4) win = -1;
else {
while (point2 != 7 & point2 != 4) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 2 & v == 2) win = 7;
else win = -1;
}
break;
case HARDWAY6:
if (x == 3 & y == 3) win = 9;
else if (point1 == 7 | point1 == 6) win = -1;
else {
while (point2 != 7 & point2 != 6) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 3 & v == 3) win = 9;
else win = -1;
}
break;
case HARDWAY8:
if (x == 4 & y == 4) win = 9;
else if (point1 == 7 | point1 == 8) win = -1;
else {
while (point2 != 7 & point2 != 8) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 4 & v == 4) win = 9;
else win = -1;
}
break;
case HARDWAY10:
if (x == 5 & y == 5) win = 7;
else if (point1 == 7 | point1 == 10) win = -1;
else {
while (point2 != 7 & point2 != 10) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 5 & v == 5) win = 7;
else win = -1;
}
break;
}
profitRV.setValue(win);
}
/**
* This method runs the the experiment one time, and add sounds depending on
* the outcome of the experiment.
*/
public void step() {
doExperiment();
update();
try {
if (win == -1) play("sounds/0.au");
else play("sounds/1.au");
} catch (Exception e) {
;
}
}
//Reset
public void reset() {
super.reset();
diceBoard.showDice(0);
profitRV.reset();
getRecordTable().append("\t(X,Y)\t(U,V)\tN\tW");
profitGraph.reset();
profitTable.reset();
}
//Update
public void update() {
super.update();
String updateText;
diceBoard.getDie(0).setValue(x);
diceBoard.getDie(1).setValue(y);
if (rolls > 1) {
diceBoard.getDie(2).setValue(u);
diceBoard.getDie(3).setValue(v);
diceBoard.showDice(4);
} else diceBoard.showDice(2);
updateText = "\t(" + x + "," + y + ")";
if (rolls > 1) updateText = updateText + "\t(" + u + "," + v + ")";
else updateText = updateText + "\t(*,*)";
updateText = updateText + "\t" + rolls + "\t" + win;
getRecordTable().append(updateText);
profitGraph.repaint();
profitTable.update();
}
public void itemStateChanged(ItemEvent event) {
if (event.getSource() == betJComboBox) {
betType = betJComboBox.getSelectedIndex();
switch (betType) {
case PASS:
prob = new double[3];
prob[0] = 251.0 / 495;
prob[2] = 244.0 / 495;
dist.setParameters(-1, 1, 1, prob);
break;
case DONTPASS:
prob = new double[3];
prob[0] = 244.0 / 495;
prob[1] = 1.0 / 36;
prob[2] = 949.0 / 1980;
dist.setParameters(-1, 1, 1, prob);
break;
case FIELD:
prob = new double[4];
prob[0] = 5.0 / 9;
prob[2] = 7.0 / 18;
prob[3] = 1.0 / 18;
dist.setParameters(-1, 2, 1, prob);
break;
case CRAPS:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case CRAPS2:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case CRAPS3:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case CRAPS12:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case SEVEN:
prob = new double[6];
prob[0] = 5.0 / 6;
prob[5] = 1.0 / 6;
dist.setParameters(-1, 4, 1, prob);
break;
case ELEVEN:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case BIG6:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case BIG8:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case HARDWAY4:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case HARDWAY6:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY8:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY10:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
}
reset();
} else super.itemStateChanged(event);
}
}
| SOCR/HTML5_WebSite | SOCR2.8/src/edu/ucla/stat/SOCR/experiments/CrapsExperiment.java | Java | lgpl-3.0 | 14,111 |
/****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
/* created by annie che 20060915. */
package edu.ucla.stat.SOCR.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import edu.ucla.stat.SOCR.analyses.result.NormalPowerResult;
import edu.ucla.stat.SOCR.distributions.Domain;
import edu.ucla.stat.SOCR.distributions.IntervalData;
import edu.ucla.stat.SOCR.distributions.NormalDistribution;
import edu.ucla.stat.SOCR.modeler.Modeler;
import edu.ucla.stat.SOCR.modeler.gui.ModelerColor;
/**
* This class models an interactive histogram. The user can click on the horizontal axes to add points to the data set.
*/
public class NormalCurve extends ModelerHistogram {
protected boolean drawData = false;
protected double[] rawData = null;
protected NormalDistribution dataDist = null;
protected int[] freq = null;
protected int sampleSize;
protected Domain domain;
protected IntervalData intervalData;
protected double maxRelFreq = -1;
protected Frequency frequency = null;
protected HashMap map = null;
private double mu0;
private double muA;
private double sigma;
private double sampleSE;
private double ciLeft;
private double ciRight;
private NormalDistribution normal0 = null;
private NormalDistribution normalA = null;
private boolean fillArea = true;
private Color fillColor1 = Color.PINK;
private Color fillColor2 = fillColor1.brighter();
private Color fillColor3 = Color.YELLOW;
private Color fillColor4 = fillColor3.brighter();
private Color ciColor = Color.GREEN;
private double xIntersect;
private double yIntersect;
private boolean useSampleMean = false;
private String hypothesisType = null;
private static byte NORMAL_CURVE_THICKNESS = 1;
public NormalCurve(double a, double b, double w) {
super(a, b, w);
this.modelType = Modeler.CONTINUOUS_DISTRIBUTION_TYPE;
setDrawUserClicks(false);
}
public NormalCurve() {
super();
setDrawUserClicks(false);
}
/**
* @param rawData the rawData to set
* @uml.property name="rawData"
*/
public void setRawData(double[] input) {
sampleSize = input.length;
try {
this.rawData = input;
double dataMax = 0;
try {
dataMax = QSortAlgorithm.max(this.rawData);
} catch (Exception e) {
}
double dataMin = 0;
try {
dataMin = QSortAlgorithm.min(this.rawData);
} catch (Exception e) {
}
domain = new Domain(dataMin, dataMax, 1);
intervalData = new IntervalData(domain, null);
setIntervalData(intervalData);
frequency = new Frequency(rawData);
map = frequency.getMap();
frequency.computeFrequency();
maxRelFreq = frequency.getMaxRelFreq();
} catch (Exception e) {
}
}
public void setRawDataDistribution(NormalDistribution normal) {
this.dataDist = normal;
}
/**
* @return the rawData
* @uml.property name="rawData"
*/
public double[] getRawData() {
return this.rawData;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D G2 = (Graphics2D) g;
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS)); // how thick the pen it.
float[] HSBVal = new float[3];
double x = 0;
double width = .5;
double d = 1;
try {
if (rawData.length > 0) {
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
int freqSize = map.size();
int dataCount = -1;
String id = null;
while (iterator.hasNext()) {
id = (String)iterator.next();
dataCount = ((Integer)map.get(id)).intValue();;
x = Double.parseDouble(id);
double dataCountDouble = dataCount;
double sampleSizeDouble = sampleSize;
d = dataCountDouble/sampleSizeDouble;
g.setColor(Color.PINK);
drawBox(g, x - width / 2, 0, x + width / 2, d);
g.setColor(Color.PINK);
fillBox(g, x - width / 2, 0, x + width / 2, d);
}
}
} catch (Exception e) {
}
if (modelX1 != null && modelX1.length > 0 && modelX2 != null && modelX2.length > 0) {
double maxXVal1 = modelX1[0], maxYVal1 = modelY1[0];
int terms1 = modelY1.length; // how many dx.
double maxXVal2 = modelX2[0], maxYVal2 = modelY1[0];
int term2s = modelY2.length; // how many dx.
double xa, ya;
int subLth = 0;
subLth = (int) (modelX1.length / modelCount);
double x1 = 0;
double y1 = 0;
//for (int j = 0; j < modelCount; j++) {
int j = 0;
x1 = (double) modelX1[0 + j * subLth];
y1 = (double) modelY1[0 + j * subLth];
for (int i = 1; i < subLth; i++) {
xa = modelX1[i + j * subLth];
ya = modelY1[i + j * subLth];
x1 = xa;
y1 = ya;
}
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor2());
x1 = (double) modelX2[0 + j * subLth];
y1 = (double) modelY2[0 + j * subLth];
for (int i = 1; i < subLth; i++) {
xa = modelX2[i + j * subLth];
ya = modelY2[i + j * subLth];
if (fillArea) {
G2.setColor(Color.YELLOW);
G2.setStroke(new BasicStroke(3f));
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_GT) && (x1 > ciRight)) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa) && (x1 < ciLeft)) {
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_LT)&& (x1 < ciLeft)) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa));
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_NE)&& (((x1 > ciRight)) || (x1 < ciLeft))) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa));
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
}
}
x1 = xa;
y1 = ya;
}
// model curve
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor1());
x1 = (double) modelX1[0 + j * subLth];
y1 = (double) modelY1[0 + j * subLth];
////////////////////System.outprintln("NormalCurve mu0 = " + mu0);
for (int i = 1; i < subLth; i++) {
xa = modelX1[i + j * subLth];
ya = modelY1[i + j * subLth];
//if (x1 < mu0 + 5 * sigma || x1 > mu0 - 5 * sigma)
drawLine(G2, x1, y1, xa, ya); // when modelCount == any #
x1 = xa;
y1 = ya;
}
subLth = (int) (modelX2.length / modelCount);
// model curve
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor2());
x1 = (double) modelX2[0 + j * subLth];
y1 = (double) modelY2[0 + j * subLth];
////////////////////System.outprintln("NormalCurve muA = " + muA);
for (int i = 1; i < subLth; i++) {
xa = modelX2[i + j * subLth];
ya = modelY2[i + j * subLth];
//if (x1 < muA + 5 * sigma || x1 > muA - 5 * sigma)
drawLine(G2, x1, y1, xa, ya); // when modelCount == any #
x1 = xa;
y1 = ya;
}
}
// draw it second time (looks nicer)
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
g.setColor(Color.BLACK);
super.drawAxis(g, -yMax, yMax, 0.1 * yMax, xMin, VERTICAL); // 6 args
super.drawAxis(g, xMin, xMax, (xMax - xMin) / 10, 0, HORIZONTAL, axisType, listOfTicks); // c must be 0.
}
protected void drawAxisWithDomain(Graphics g, Domain domain, double c, int orientation, int type, ArrayList list){
double t;
double currentUpperBound = domain.getUpperBound(); // of the model (distribution)
double currentLowerBound = domain.getLowerBound();
int domainSize = domain.getSize();
if (orientation == HORIZONTAL){
this.drawLine(g, currentLowerBound, c, currentUpperBound, c);
//Draw tick marks, depending on type
for (int i = 0; i < domainSize; i++){
if (type == MIDPOINTS) {
t = domain.getValue(i);
} else {
t = domain.getBound(i);
}
g.setColor(ModelerColor.HISTOGRAM_TICKMARK);
//g.setStroke(new BasicStroke(3.05f));
//drawTick(g, t, c, VERTICAL);
}
if (type == BOUNDS) {
t = domain.getUpperBound();
drawTick(g, t, c, VERTICAL);
}
//Draw labels
if (type == MIDPOINTS) {
t = domain.getLowerValue();
} else {
t = domain.getLowerBound();
}
drawLabel(g, format(t), t, c, BELOW);
if (type == MIDPOINTS) {
t = domain.getUpperValue();
} else {
t = domain.getUpperBound();
}
drawLabel(g, format(t), t, c, BELOW);
//double mu0 = 0;
//double muA = 0;
//double sigma = 0;
//ciLeft = 0;
//ciRight = 0;
//double sampleSE = 0;
//NormalDistribution normal0 = null;
//NormalDistribution normalA = null;
if (list != null) {
//for (int i = 0; i < list.size(); i++) {
try {
mu0 = Double.parseDouble(((String)list.get(0)));
muA = Double.parseDouble(((String)list.get(1)));
sigma = Double.parseDouble(((String)list.get(2)));
////////////System.outprintln("NormalCurve mu0 = " + mu0);
////////////System.outprintln("NormalCurve muA = " + muA);
//sampleSE = Double.parseDouble(((String)list.get(3)));
normal0 = new NormalDistribution(mu0, sigma);
normalA = new NormalDistribution(muA, sigma);
//ciLeft = mu0 - 1.96 * sigma;
//ciRight = mu0 + 1.96 * sigma;
//t = Double.parseDouble(((String)list.get(i)));
drawLabel(g, format(mu0), mu0, c, BELOW);
drawLabel(g, format(muA), muA, c, BELOW);
Color oldColor = g.getColor();
g.setColor(this.getOutlineColor1());
drawLine(g, mu0, 0, mu0, normal0.getMaxDensity());
//drawLine(g, ciLeft, 0, ciLeft, normal0.getDensity(ciLeft));
//drawLine(g, ciRight, 0, ciRight, normal0.getDensity(ciRight));
g.setColor(this.getOutlineColor2());
drawLine(g, muA, 0, muA, normalA.getMaxDensity());
double density = 0;
if (hypothesisType == null)
hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve hypothesisType = " + hypothesisType);
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_NE)){
try {
g.setColor(this.getOutlineColor1());
ciLeft = Double.parseDouble(((String)list.get(3)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciLeft), normalA.getDensity(ciLeft));
g.setColor(ciColor);
drawLine(g, ciLeft, 0, ciLeft, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
//////////////System.outprintln("NormalCurve ciLeft = " + ciLeft + " density = " + density);
}
catch (Exception e) {
//////////////System.outprintln("NormalCurve e = " + e);
}
try {
g.setColor(this.getOutlineColor1());
ciRight = Double.parseDouble(((String)list.get(4)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciRight), normalA.getDensity(ciRight));
g.setColor(ciColor);
drawLine(g, ciRight, 0, ciRight, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
//////////////System.outprintln("NormalCurve ciRight = " + ciRight + " density = " + density);
}
catch (Exception e) {
//////////////System.outprintln("NormalCurve e = " + e);
}
}
else if (muA < mu0) {
hypothesisType = NormalPowerResult.HYPOTHESIS_TYPE_LT;
}
else if (muA > mu0) {
hypothesisType = NormalPowerResult.HYPOTHESIS_TYPE_GT;
}
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_LT)) {
try {
g.setColor(this.getOutlineColor1());
ciLeft = Double.parseDouble(((String)list.get(3)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciLeft), normalA.getDensity(ciLeft));
g.setColor(ciColor);
drawLine(g, ciLeft, 0, ciLeft, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve ciLeft = " + ciLeft + " density = " + density);
} catch (Exception e) {
////////System.outprintln("NormalCurve Exception e = " + e);
}
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_GT)) {
try {
g.setColor(this.getOutlineColor1());
ciRight = Double.parseDouble(((String)list.get(4)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciRight), normalA.getDensity(ciRight));
g.setColor(ciColor);
drawLine(g, ciRight, 0, ciRight, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve ciRight = " + ciRight + " density = " + density);
} catch (Exception e) {
////////System.outprintln("NormalCurve Exception e = " + e);
}
}
////////////System.outprintln("NormalCurve hypothesisType = " + hypothesisType);
double x1 = 0, y1 = 0, xa = 0;
g.setColor(oldColor);
} catch (Exception e) {
//////////////System.outprintln("NormalCurve last e = " + e);
}
//}
}
}
else{
//Draw thte line
drawLine(g, c, domain.getLowerBound(), c, domain.getUpperBound());
//drawLine(g, c, -10, c, 10);
//Draw tick marks, depending on type
for (int i = 0; i < domain.getSize(); i++){
if (type == MIDPOINTS) t = domain.getValue(i); else t = domain.getBound(i);
//drawTick(g, c, t, HORIZONTAL);
}
if (type == BOUNDS) drawTick(g, c, domain.getUpperBound(), HORIZONTAL);
//Draw labels
if (type == MIDPOINTS) t = domain.getLowerValue(); else t = domain.getLowerBound();
g.setColor(ModelerColor.HISTOGRAM_LABEL);
drawLabel(g, format(t), c, t, LEFT);
if (type == MIDPOINTS) t = domain.getUpperValue(); else t = domain.getUpperBound();
drawLabel(g, format(t), c, t, LEFT);
}
int sum = Math.abs(currentXUpperBound) + Math.abs(currentXLowerBound); //
int diff = Math.abs(currentXUpperBound) - Math.abs(currentXLowerBound); //
}
/**
* @return the maxRelFreq
* @uml.property name="maxRelFreq"
*/
public double getMaxRelFreq() {
return this.maxRelFreq;
}
/**
* @param fillArea the fillArea to set
* @uml.property name="fillArea"
*/
public void setFillArea(boolean fillArea) {
this.fillArea = fillArea;
}
/*
private void findIntersection(double[] x1, double[] y1, double[] x2, double[] y2) {
double numberTooSmall = 1E-10;
boolean[] willUse = new boolean[x1.length];
for (int i = 0; i < x1.length; i++) {
if (y1[i] < numberTooSmall || y2[i] < numberTooSmall) {
willUse[i] = false;
}
else {
willUse[i] = true;
}
}
}
*/
public void setSampleMeanOption(boolean input) {
this.useSampleMean = input;
}
public boolean withinSampleMeanCurve(double x, double y) {//, double scale) {
double f = normalA.getDensity(x);
//////////System.outprintln("NormailCurve x = " + x + ", y = " + y + ", f = " + f);
if (f <= y && f >= 0.0001) {
return true;
}
else {
return false;
}
}
public void resetHypotheseType() {
hypothesisType = null;
}
}
| SOCR/HTML5_WebSite | SOCR2.8/src/edu/ucla/stat/SOCR/util/NormalCurve.java | Java | lgpl-3.0 | 16,918 |
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2014
*/
package org.bitbucket.ucchy.delay;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Delay Command Plugin
* @author ucchy
*/
public class DelayCommandPlugin extends JavaPlugin {
/**
* @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ( args.length < 2 ) {
return false;
}
final ArrayList<String> commands = new ArrayList<String>();
boolean isAsync = false;
int ticks = 0;
if ( isDigit(args[0]) ) {
// /delay (ticks) (command...)
for ( int index=1; index<args.length; index++ ) {
commands.add(args[index]);
}
ticks = Integer.parseInt(args[0]);
} else if ( args[0].equalsIgnoreCase("async") && isDigit(args[1]) && args.length >= 3 ) {
// /delay async (ticks) (command...)
isAsync = true;
for ( int index=2; index<args.length; index++ ) {
commands.add(args[index]);
}
ticks = Integer.parseInt(args[1]);
} else {
return false;
}
final CommandSender comSender = sender;
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
StringBuilder builder = new StringBuilder();
for ( String com : commands ) {
builder.append(com + " ");
}
Bukkit.dispatchCommand(comSender, builder.toString().trim());
}
};
if ( isAsync ) {
runnable.runTaskLaterAsynchronously(this, ticks);
} else {
runnable.runTaskLater(this, ticks);
}
return true;
}
private boolean isDigit(String value) {
return value.matches("^[0-9]{1,9}$");
}
}
| ucchyocean/DelayCommand | src/main/java/org/bitbucket/ucchy/delay/DelayCommandPlugin.java | Java | lgpl-3.0 | 2,383 |
<?php
/****************************************************************************
* Name: rep_motivetypes.php *
* Project: Corsaro - Reporting *
* Version: 1.69 *
* Description: Arrows Oriented Modeling *
* Copyright (C): 2015 Rodolfo Calzetti *
* License GNU LESSER GENERAL PUBLIC LICENSE Version 3 *
* Contact: https://github.com/cambusa *
* postmaster@rudyz.net *
****************************************************************************/
include_once "_config.php";
include_once $tocambusa."sysconfig.php";
include_once $tocambusa."rypaper/rypaper.php";
include_once $tocambusa."ryquiver/quiversex.php";
if(isset($_POST["sessionid"]))
$sessionid=$_POST["sessionid"];
else
$sessionid="";
if(isset($_POST["env"]))
$env=$_POST["env"];
else
$env="";
if(isset($_POST["pdf"]))
$pdf=intval($_POST["pdf"]);
else
$pdf=0;
if(isset($_POST["keys"]))
$keys=$_POST["keys"];
else
$keys=array();
$paged=1;
$landscape=1;
$format="A4";
// APRO IL DATABASE
$maestro=maestro_opendb($env, false);
if(qv_validatesession($maestro, $sessionid, "quiver")){
$PAPER->setformat('{"headerheight":20,"paged":'.$paged.',"pdf":'.$pdf.',"landscape":'.$landscape.',"format":"'.$format.'","environ":"'.$temp_environ.'"}');
function myheader(){
global $cust_header;
global $PAPER;
$PAPER->write("<div class='report-company' style='position:absolute;top:0px;left:0px;width:100%;text-align:left;'>".$cust_header."</div>");
$PAPER->write("<div class='report-time' style='position:absolute;top:0px;left:0px;width:100%;text-align:right;'>".$PAPER->timereport()."</div>");
$PAPER->write("<div class='report-title' style='position:absolute;font-size:16px;top:25px;left:0px;width:100%;text-align:center;'>TIPI MOTIVO</div>");
};
$PAPER->header="myheader";
// INIZIO DEL DOCUMENTO
$PAPER->begindocument();
// INIZIO TABELLA
$PAPER->begintable(
'[
{"d":"Nome","w":40,"t":""},
{"d":"Descrizione","w":90,"t":""},
{"d":"Vista","w":40,"t":""},
{"d":"Tabella","w":40,"t":""},
{"d":"Gestione","w":20,"t":""},
{"d":"Estensione","w":40,"t":""}
]'
);
// QUERY REPERIMENTO DATI
$in="";
foreach($keys as $key => $SYSID){
if($in!="")
$in.=",";
$in.="'$SYSID'";
}
// ESEGUO LA QUERY
maestro_query($maestro, "SELECT * FROM QVMOTIVETYPES WHERE SYSID IN ($in)", $r);
for($i=0; $i<count($r); $i++){
$SYSID=$r[$i]["SYSID"];
maestro_query($maestro, "SELECT FIELDNAME FROM QVMOTIVEVIEWS WHERE TYPOLOGYID='$SYSID'", $d);
if(count($d)>0)
$FIELDNAME=$PAPER->getvalue($d, 0, "FIELDNAME");
else
$FIELDNAME="";
$PAPER->tablerow($PAPER->getvalue($r, $i, "NAME"),
$PAPER->getvalue($r, $i, "DESCRIPTION"),
$PAPER->getvalue($r, $i, "VIEWNAME"),
$PAPER->getvalue($r, $i, "TABLENAME"),
$PAPER->cboolean($r[$i]["DELETABLE"]),
$FIELDNAME
);
for($j=1; $j<count($d); $j++){
$PAPER->tablerow("", "....................", "....................", "....................", "....", $PAPER->getvalue($d, $j, "FIELDNAME"));
}
}
// FINE TABELLA
$PAPER->endtable();
// FINE DEL DOCUMENTO
$PAPER->enddocument();
// RESTITUISCO IL PERCORSO DEL DOCUMENTO
print $PAPER->pathfile;
}
// CHIUDO IL DATABASE
maestro_closedb($maestro);
?> | cambusa/corsaro | _master/customize/corsaro/reporting/rep_motivetypes.php | PHP | lgpl-3.0 | 3,889 |
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
* This file is part of Alfresco
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.po.share.enums;
import java.util.NoSuchElementException;
/**
* This enums used to describe the user roles.
*
* @author cbairaajoni
* @since v1.0
*/
public enum UserRole
{
ALL("All"),
MANAGER("Manager"),
EDITOR("Editor"),
CONSUMER("Consumer"),
COLLABORATOR("Collaborator"),
COORDINATOR("Coordinator"),
CONTRIBUTOR("Contributor"),
SITECONSUMER("Site Consumer"),
SITECONTRIBUTOR("Site Contributor"),
SITEMANAGER("Site Manager"),
SITECOLLABORATOR("Site Collaborator");
private String roleName;
private UserRole(String role)
{
roleName = role;
}
public String getRoleName()
{
return roleName;
}
public static UserRole getUserRoleforName(String name)
{
for (UserRole role : UserRole.values())
{
if (role.getRoleName().equalsIgnoreCase(name))
{
return role;
}
}
throw new NoSuchElementException("No Role for value - " + name);
}
} | loftuxab/community-edition-old | projects/share-po/src/main/java/org/alfresco/po/share/enums/UserRole.java | Java | lgpl-3.0 | 1,846 |
var sys = require('sys'),
child_process = require('child_process'),
vm = require('vm'),
http = require('http'),
querystring = require('querystring'),
Persistence = require('./persistence/persistence'),
request = require('request'),
xml2jsParser = require('xml2js').parseString;
function msToString(ms) {
var str = "";
if (ms > 3600000) {
var hours = Math.floor(ms/3600000);
str += hours + " hours, ";
ms = ms - (hours*3600000);
}
if (ms > 60000) {
var minutes = Math.floor(ms/60000);
str += minutes + " minutes, ";
ms = ms - (minutes*60000);
}
str += Math.floor(ms/1000) + " seconds";
return str;
}
function addBehaviors(bot, properties) {
var persistence = new Persistence(properties);
var userEval = 1;
// Rate to mix in yahoo answers with stored responses
// 0.75 = 75% Yahoo answers, 25% stored responses
var mix = 0.5;
bot.addMessageListener("logger", function(nick, message) {
// Check to see if this is from a nick we shouldn't log
if (properties.logger.ignoreNicks.filter(function (x) { return nick.indexOf(x) > -1; }).length > 0) {
return true;
}
if (! (/^!/).test(message)) {
persistence.saveMessage(nick, message);
}
return true;
});
var yahooAnswer = function(message) {
var url = 'http://answers.yahoo.com/AnswersService/V1/questionSearch?appid=' + properties.yahooId +
"&query=" + querystring.escape(message) + "&type=resolved&output=json";
sys.log("Calling " + url);
request(url, function(error, response, body) {
try {
var yahooResponse = JSON.parse(body);
if (yahooResponse.all.count > 0) {
var bestAnswer = yahooResponse.all.questions[0].ChosenAnswer;
bestAnswer = bestAnswer.substring(0, 400);
bot.say(bestAnswer);
} else {
persistence.getRandom(bot);
}
} catch (err) {
sys.log(err);
persistence.getRandom(bot);
}
});
};
bot.addMessageListener("listen for name", function (nick, message) {
var re = new RegExp(properties.bot.nick);
if (re.test(message)) {
if (Math.random() < mix && properties.yahooId) {
sys.log("mix = " + mix + ", serving from yahoo answers");
yahooAnswer(message.replace(re, ''));
} else {
sys.log("mix = " + mix + ", serving from mysql");
persistence.getRandom(bot);
}
return false;
} else {
return true;
}
});
bot.addCommandListener("!do [nick]", /!do ([0-9A-Za-z_\-]*)/, "random quote", function(doNick) {
persistence.getQuote(doNick, bot);
});
bot.addCommandListener("!msg [#]", /!msg ([0-9]*)/, "message recall", function(id) {
persistence.getMessage(id, bot);
});
bot.addCommandListener("!about [regex pattern]", /!about (.*)/, "random message with phrase", function(pattern) {
persistence.matchMessage(pattern, bot);
});
bot.addCommandListener("!uds", /!uds/, "random message about uds", function() {
persistence.matchMessage('uds', bot);
});
bot.addCommandListener("!aevans", /!aevans/, "so, message from aevans", function() {
persistence.matchMessageForNick('aevans', '^so(\\s|,)', bot);
});
bot.addCommandListener("!leaders [start index]", /!leaders\s*(\d*)/, "top users by message count", function(index) {
persistence.leaders(index, bot);
});
bot.addCommandListener("!playback start end", /!playback (\d+ \d+)/, "playback a series of messages", function(range) {
var match = range.match(/(\d+) (\d+)/);
if (match) {
var start = match[1];
var end = match[2];
if (end - start >= 10) {
bot.say("playback limited to 10 messages");
} else if (start >= end) {
bot.say("start must be less than end");
} else {
for (var i = start; i <= end; i++) {
persistence.getMessage(i, bot);
}
}
}
});
bot.addCommandListener("!stats nick", /!stats (.*)/, "stats about a user", function(nick) {
persistence.userStats(nick, bot);
});
bot.addCommandListener("!alarm <time> -m <message>", /!alarm (.* -m .*)/, "set an alarm, valid time examples: 5s, 5m, 5h, 10:00, 14:30, 2:30pm", function(timeString, nick) {
var matchInterval = timeString.match(/(\d+)([h|m|s]) -m (.*)/);
var matchTime = timeString.match(/(\d{1,2}):(\d{2})(am|pm){0,1} -m (.*)/);
if (matchInterval) {
var timeNumber = matchInterval[1];
var timeUnit = matchInterval[2];
var sleepTime = timeNumber;
if (timeUnit === 'h') {
sleepTime = sleepTime * 60 * 60 * 1000;
} else if (timeUnit === 'm') {
sleepTime = sleepTime * 60 * 1000;
} else if (timeUnit === 's') {
sleepTime = sleepTime * 1000;
}
if (sleepTime < 2147483647) {
bot.say("Alarm will go off in " + msToString(sleepTime));
setTimeout(function() {
bot.say(nick + ': ' + matchInterval[3]);
}, sleepTime);
} else {
bot.say("Delay exceeds maximum timeout, see: http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values");
}
} else if (matchTime) {
var hour = parseInt(matchTime[1]);
var minute = matchTime[2];
if (matchTime[3] === 'pm' && hour != 12) {
hour = hour + 12;
} else if (matchTime[3] === 'am' && hour === 12) {
hour = 0;
}
var now = new Date();
var sleepTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now;
if (sleepTime < 0) {
sleepTime += 86400000;
}
bot.say("Alarm will go off in " + msToString(sleepTime));
setTimeout(function() {
bot.say(nick + ': ' + matchTime[4]);
}, sleepTime);
} else {
bot.say("Unknown time format!");
}
});
bot.addCommandListener("!uname", /!uname/, "information about host", function() {
child_process.exec('uname -a', function(error, stdout, stderr) {
bot.say(stdout);
});
});
bot.addCommandListener("!version", /!version/, "report node version", function() {
bot.say("Node version = " + process.version);
});
bot.addCommandListener("!help <cmd>", /!help(.*)/, "command help", function(cmd) {
if (cmd) {
bot.helpCommand(cmd);
} else {
bot.listCommands();
}
});
bot.addCommandListener("!quote [symbol]", /!quote (.*)/, "get a stock quote", function(symbol) {
var url = 'https://api.iextrading.com/1.0/stock/' + symbol + '/batch?types=quote';
request(url, function(error, response, body) {
if (error) { console.log(error); }
var result = JSON.parse(body);
if (! error && result.quote && result.quote.latestPrice) {
var mktCap = result.quote.marketCap;
var mktCapString = "";
if (mktCap > 1000000000) {
mktCapString = "$" + ((mktCap/1000000000).toFixed(2)) + "B";
} else if (mktCap > 1000000) {
mktCapString = "$" + ((mktCap/1000000).toFixed(2)) + "M";
}
var changePrefix = (result.quote.change > 0) ? '+' : '';
bot.say(result.quote.companyName + ' ... ' +
'$' + String(result.quote.latestPrice) + ' ' +
changePrefix + String(result.quote.change) + ' ' +
changePrefix + String((result.quote.changePercent * 100).toFixed(2)) + '% ' +
mktCapString);
} else {
bot.say("Unable to get a quote for " + symbol);
}
});
});
bot.addMessageListener("toggle", function(nick, message) {
var check = message.match(/!toggle (.*)/);
if (check) {
var name = check[1];
var result = bot.toggleMessageListener(name);
if (result) {
bot.say("Message listener " + name + " is active");
} else {
bot.say("Message listener " + name + " is inactive");
}
return false;
}
return true;
});
bot.addMessageListener("eval", function(nick, message) {
var check = message.match(/!add (.*)/);
if (check) {
var msg = check[1];
var mlName = "user eval " + userEval++;
bot.addMessageListener(mlName, function(nick, message) {
var sandbox = { output: null, nick: nick, message: message };
vm.runInNewContext(msg, sandbox);
if (sandbox.output) {
bot.say(sandbox.output);
return false;
}
return true;
});
bot.say("Added message listener: " + mlName);
return false;
}
return true;
});
bot.addCommandListener("!define [phrase]", /!define (.*)/, "urban definition of a word or phrase", function(msg) {
var data = "";
var request = require('request');
request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
if (!error && response.statusCode == 200) {
var urbanresult = JSON.parse(body);
bot.say(urbanresult.list[0].definition);
}
})
});
bot.addCommandListener("!example [phrase]", /!example (.*)/, "Use of urban definition of a word or phrase in a sentence", function(msg) {
var data = "";
var request = require('request');
request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
if (!error && response.statusCode == 200) {
var urbanresult = JSON.parse(body);
bot.say(urbanresult.list[0].example);
}
})
});
bot.addCommandListener("!showerthought", /!showerthought/, "Return a reddit shower thought", function(msg) {
var data = "";
var request = require('request');
request("http://www.reddit.com/r/showerthoughts/.json", function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) // Print the results
var showerthought = JSON.parse(body);
// There are many returned in the json. Get a count
var showercount=showerthought.data.children.length
var randomthought=Math.floor((Math.random() * showercount) + 1);
console.log("Found " + showercount + " shower thoughts. Randomly returning number " + randomthought);
bot.say(showerthought.data.children[randomthought].data.title);
}
})
});
bot.addCommandListener("!firstworldproblems", /!firstworldproblems/, "Return a reddit first world problem", function(msg) {
var data = "";
var request = require('request');
request("http://www.reddit.com/r/firstworldproblems/.json", function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) // Print the results
var firstworldproblem = JSON.parse(body);
// There are many returned in the json. Get a count
var problemcount=firstworldproblem.data.children.length
var randomproblem=Math.floor((Math.random() * problemcount) + 1);
console.log("Found " + problemcount + " shower thoughts. Randomly returning number " + randomproblem);
bot.say(firstworldproblem.data.children[randomproblem].data.title);
}
})
});
}
module.exports = addBehaviors;
| mmattozzi/botboy | behaviors.js | JavaScript | lgpl-3.0 | 12,397 |
/*
*
* Copyright (c) 2011-2016 The University of Waikato, Hamilton, New Zealand.
* All rights reserved.
*
* This file is part of libprotoident.
*
* This code has been developed by the University of Waikato WAND
* research group. For further information please see http://www.wand.net.nz/
*
* libprotoident 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.
*
* libprotoident 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/>.
*
*
*/
#define __STDC_FORMAT_MACROS
#define __STDC_LIMIT_MACROS
#include <stdio.h>
#include <assert.h>
#include <libtrace.h>
#include <inttypes.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include "libprotoident.h"
#include "proto_manager.h"
bool init_called = false;
LPIModuleMap TCP_protocols;
LPIModuleMap UDP_protocols;
lpi_module_t *lpi_icmp = NULL;
lpi_module_t *lpi_unsupported = NULL;
lpi_module_t *lpi_unknown_tcp = NULL;
lpi_module_t *lpi_unknown_udp = NULL;
static LPINameMap lpi_names;
static LPIProtocolMap lpi_protocols;
static LPICategoryMap lpi_categories;
static LPICategoryProtocolMap lpi_category_protocols;
static int seq_cmp (uint32_t seq_a, uint32_t seq_b) {
if (seq_a == seq_b) return 0;
if (seq_a > seq_b)
return (int)(seq_a - seq_b);
else
/* WRAPPING */
return (int)(UINT32_MAX - ((seq_b - seq_a) - 1));
}
int lpi_init_library() {
if (init_called) {
fprintf(stderr, "WARNING: lpi_init_library has already been called\n");
return 0;
}
if (register_tcp_protocols(&TCP_protocols) == -1)
return -1;
if (register_udp_protocols(&UDP_protocols) == -1)
return -1;
init_other_protocols(&lpi_names, &lpi_protocols, &lpi_category_protocols);
register_names(&TCP_protocols, &lpi_names, &lpi_protocols, &lpi_category_protocols);
register_names(&UDP_protocols, &lpi_names, &lpi_protocols, &lpi_category_protocols);
register_category_names(&lpi_categories);
init_called = true;
if (TCP_protocols.empty() && UDP_protocols.empty()) {
fprintf(stderr, "WARNING: No protocol modules loaded\n");
return -1;
}
return 0;
}
void lpi_free_library() {
free_protocols(&TCP_protocols);
free_protocols(&UDP_protocols);
if (lpi_icmp != NULL) {
delete lpi_icmp;
lpi_icmp = NULL;
}
if (lpi_unsupported != NULL) {
delete lpi_unsupported;
lpi_unsupported = NULL;
}
if (lpi_unknown_tcp != NULL) {
delete lpi_unknown_tcp;
lpi_unknown_tcp = NULL;
}
if (lpi_unknown_udp != NULL) {
delete lpi_unknown_udp;
lpi_unknown_udp = NULL;
}
init_called = false;
}
void lpi_init_data(lpi_data_t *data) {
data->payload[0] = 0;
data->payload[1] = 0;
data->seen_syn[0] = false;
data->seen_syn[1] = false;
data->seqno[0] = 0;
data->seqno[1] = 0;
data->observed[0] = 0;
data->observed[1] = 0;
data->server_port = 0;
data->client_port = 0;
data->trans_proto = 0;
data->payload_len[0] = 0;
data->payload_len[1] = 0;
data->ips[0] = 0;
data->ips[1] = 0;
}
static int update_tcp_flow(lpi_data_t *data, libtrace_tcp_t *tcp, uint8_t dir,
uint32_t rem, uint32_t psize) {
uint32_t seq = 0;
if (rem < sizeof(libtrace_tcp_t))
return 0;
if (tcp->rst)
return 0;
if (data->server_port == 0) {
data->server_port = ntohs(tcp->dest);
data->client_port = ntohs(tcp->source);
}
seq = ntohl(tcp->seq);
if (tcp->syn && data->payload_len[dir] == 0) {
data->seqno[dir] = seq + 1;
data->seen_syn[dir] = true;
}
/* Ok, we've got some payload but we never saw the SYN for this
* direction. What do we do?
*
* Current idea: just assume this is the first payload bearing
* packet. Better than running around with an uninitialised seqno */
if (data->seen_syn[dir] == false && psize > 0) {
data->seqno[dir] = seq;
data->seen_syn[dir] = true;
}
if (seq_cmp(seq, data->seqno[dir]) != 0)
return 0;
//data->seqno[dir] = seq;
return 1;
}
static int update_udp_flow(lpi_data_t *data, libtrace_udp_t *udp,
uint32_t rem) {
if (rem < sizeof(libtrace_udp_t))
return 0;
if (data->server_port == 0) {
data->server_port = ntohs(udp->dest);
data->client_port = ntohs(udp->source);
}
return 1;
}
int lpi_update_data(libtrace_packet_t *packet, lpi_data_t *data, uint8_t dir) {
char *payload = NULL;
uint32_t psize = 0;
uint32_t rem = 0;
uint8_t proto = 0;
void *transport;
uint32_t four_bytes;
libtrace_ip_t *ip = NULL;
//tcp = trace_get_tcp(packet);
psize = trace_get_payload_length(packet);
/* Don't bother if we've observed 32k of data - the first packet must
* surely been within that. This helps us avoid issues with sequence
* number wrapping when doing the reordering check below */
if (data->observed[dir] > 32 * 1024)
return 0;
data->observed[dir] += psize;
/* If we're TCP, we have to wait to check that we haven't been
* reordered */
if (data->trans_proto != 6 && data->payload_len[dir] != 0)
return 0;
transport = trace_get_transport(packet, &proto, &rem);
if (data->trans_proto == 0)
data->trans_proto = proto;
if (transport == NULL || rem == 0)
return 0;
if (proto == 6) {
if (update_tcp_flow(data, (libtrace_tcp_t *)transport, dir, rem, psize) == 0)
return 0;
payload = (char *)trace_get_payload_from_tcp(
(libtrace_tcp_t *)transport, &rem);
}
if (proto == 17) {
if (update_udp_flow(data, (libtrace_udp_t *)transport, rem) == 0)
return 0;
payload = (char *)trace_get_payload_from_udp(
(libtrace_udp_t *)transport, &rem);
}
ip = trace_get_ip(packet);
if (payload == NULL)
return 0;
if (psize <= 0)
return 0;
four_bytes = (*(uint32_t *)payload);
if (psize < 4) {
four_bytes = (ntohl(four_bytes)) >> (8 * (4 - psize));
four_bytes = htonl(four_bytes << (8 * (4 - psize)));
}
data->payload[dir] = four_bytes;
data->payload_len[dir] = psize;
if (ip != NULL && data->ips[0] == 0) {
if (dir == 0) {
data->ips[0] = ip->ip_src.s_addr;
data->ips[1] = ip->ip_dst.s_addr;
} else {
data->ips[1] = ip->ip_src.s_addr;
data->ips[0] = ip->ip_dst.s_addr;
}
}
return 1;
}
static lpi_module_t *test_protocol_list(LPIModuleList *ml, lpi_data_t *data) {
LPIModuleList::iterator l_it;
/* Turns out naively looping through the modules is quicker
* than trying to do intelligent stuff with threads. Most
* callbacks complete very quickly so threading overhead is a
* major problem */
for (l_it = ml->begin(); l_it != ml->end(); l_it ++) {
lpi_module_t *module = *l_it;
/* To save time, I'm going to break on the first successful
* match. A threaded version would wait for all the modules
* to run, storing all successful results in a list of some
* sort and selecting an appropriate result from there.
*/
if (module->lpi_callback(data, module))
return module;
}
return NULL;
}
static lpi_module_t *guess_protocol(LPIModuleMap *modmap, lpi_data_t *data) {
lpi_module_t *proto = NULL;
LPIModuleMap::iterator m_it;
/* Deal with each priority in turn - want to match higher priority
* rules first.
*/
for (m_it = modmap->begin(); m_it != modmap->end(); m_it ++) {
LPIModuleList *ml = m_it->second;
proto = test_protocol_list(ml, data);
if (proto != NULL)
break;
}
return proto;
}
lpi_module_t *lpi_guess_protocol(lpi_data_t *data) {
lpi_module_t *p = NULL;
if (!init_called) {
fprintf(stderr, "lpi_init_library was never called - cannot guess the protocol\n");
return NULL;
}
switch(data->trans_proto) {
case TRACE_IPPROTO_ICMP:
return lpi_icmp;
case TRACE_IPPROTO_TCP:
p = guess_protocol(&TCP_protocols, data);
if (p == NULL)
p = lpi_unknown_tcp;
return p;
case TRACE_IPPROTO_UDP:
p = guess_protocol(&UDP_protocols, data);
if (p == NULL)
p = lpi_unknown_udp;
return p;
default:
return lpi_unsupported;
}
return p;
}
lpi_category_t lpi_categorise(lpi_module_t *module) {
if (module == NULL)
return LPI_CATEGORY_NO_CATEGORY;
return module->category;
}
const char *lpi_print_category(lpi_category_t category) {
switch(category) {
case LPI_CATEGORY_WEB:
return "Web";
case LPI_CATEGORY_MAIL:
return "Mail";
case LPI_CATEGORY_CHAT:
return "Chat";
case LPI_CATEGORY_P2P:
return "P2P";
case LPI_CATEGORY_P2P_STRUCTURE:
return "P2P_Structure";
case LPI_CATEGORY_KEY_EXCHANGE:
return "Key_Exchange";
case LPI_CATEGORY_ECOMMERCE:
return "ECommerce";
case LPI_CATEGORY_GAMING:
return "Gaming";
case LPI_CATEGORY_ENCRYPT:
return "Encryption";
case LPI_CATEGORY_MONITORING:
return "Measurement";
case LPI_CATEGORY_NEWS:
return "News";
case LPI_CATEGORY_MALWARE:
return "Malware";
case LPI_CATEGORY_SECURITY:
return "Security";
case LPI_CATEGORY_ANTISPAM:
return "Antispam";
case LPI_CATEGORY_VOIP:
return "VOIP";
case LPI_CATEGORY_TUNNELLING:
return "Tunnelling";
case LPI_CATEGORY_NAT:
return "NAT_Traversal";
case LPI_CATEGORY_STREAMING:
return "Streaming";
case LPI_CATEGORY_SERVICES:
return "Services";
case LPI_CATEGORY_DATABASES:
return "Databases";
case LPI_CATEGORY_FILES:
return "File_Transfer";
case LPI_CATEGORY_REMOTE:
return "Remote_Access";
case LPI_CATEGORY_TELCO:
return "Telco_Services";
case LPI_CATEGORY_P2PTV:
return "P2PTV";
case LPI_CATEGORY_RCS:
return "Revision_Control";
case LPI_CATEGORY_LOGGING:
return "Logging";
case LPI_CATEGORY_PRINTING:
return "Printing";
case LPI_CATEGORY_TRANSLATION:
return "Translation";
case LPI_CATEGORY_CDN:
return "CDN";
case LPI_CATEGORY_CLOUD:
return "Cloud";
case LPI_CATEGORY_NOTIFICATION:
return "Notification";
case LPI_CATEGORY_SERIALISATION:
return "Serialisation";
case LPI_CATEGORY_BROADCAST:
return "Broadcast";
case LPI_CATEGORY_LOCATION:
return "Location";
case LPI_CATEGORY_CACHING:
return "Caching";
case LPI_CATEGORY_ICS:
return "ICS";
case LPI_CATEGORY_MOBILE_APP:
return "Mobile App";
case LPI_CATEGORY_IPCAMERAS:
return "IP Cameras";
case LPI_CATEGORY_EDUCATIONAL:
return "Educational";
case LPI_CATEGORY_MESSAGE_QUEUE:
return "Message_Queuing";
case LPI_CATEGORY_ICMP:
return "ICMP";
case LPI_CATEGORY_MIXED:
return "Mixed";
case LPI_CATEGORY_NOPAYLOAD:
return "No_Payload";
case LPI_CATEGORY_UNKNOWN:
return "Unknown";
case LPI_CATEGORY_UNSUPPORTED:
return "Unsupported";
case LPI_CATEGORY_NO_CATEGORY:
return "Uncategorised";
case LPI_CATEGORY_LAST:
return "Invalid_Category";
}
return "Invalid_Category";
}
const char *lpi_print(lpi_protocol_t proto) {
LPINameMap::iterator it;
it = lpi_names.find(proto);
if (it == lpi_names.end()) {
return "NULL";
}
return (it->second);
}
lpi_protocol_t lpi_get_protocol_by_name(char *name) {
LPIProtocolMap::iterator it;
it = lpi_protocols.find(name);
if (it == lpi_protocols.end()) {
return LPI_PROTO_UNKNOWN;
}
return (it->second);
}
lpi_category_t lpi_get_category_by_name(char *name) {
LPICategoryMap::iterator it;
it = lpi_categories.find(name);
if (it == lpi_categories.end()) {
return LPI_CATEGORY_UNKNOWN;
}
return (it->second);
}
lpi_category_t lpi_get_category_by_protocol(lpi_protocol_t protocol) {
LPICategoryProtocolMap::iterator it;
it = lpi_category_protocols.find(protocol);
if (it == lpi_category_protocols.end()) {
return LPI_CATEGORY_UNKNOWN;
}
return (it->second);
}
bool lpi_is_protocol_inactive(lpi_protocol_t proto) {
LPINameMap::iterator it;
it = lpi_names.find(proto);
if (it == lpi_names.end()) {
return true;
}
return false;
}
| wanduow/libprotoident | lib/libprotoident.cc | C++ | lgpl-3.0 | 12,184 |
/**
*
*/
package inra.ijpb.binary.distmap;
/**
* Specialization of DistanceTransform based on the use of a chamfer mask.
*
* Provides methods for retrieving the mask, and the normalization weight.
*
* @author dlegland
*/
public interface ChamferDistanceTransform2D extends DistanceTransform
{
/**
* Return the chamfer mask used by this distance transform algorithm.
*
* @return the chamfer mask used by this distance transform algorithm.
*/
public ChamferMask2D mask();
}
| ijpb/MorphoLibJ | src/main/java/inra/ijpb/binary/distmap/ChamferDistanceTransform2D.java | Java | lgpl-3.0 | 495 |
/**
* Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
* <p>
* Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl-3.0.txt
* <p>
* 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 io.jpress.module.product.directive;
import com.jfinal.aop.Inject;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.utils.StrUtil;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jpress.module.product.model.Product;
import io.jpress.module.product.service.ProductService;
/**
* @author Michael Yang 杨福海 (fuhai999@gmail.com)
* @version V1.0
*/
@JFinalDirective("product")
public class ProductDirective extends JbootDirectiveBase {
@Inject
private ProductService service;
@Override
public void onRender(Env env, Scope scope, Writer writer) {
String idOrSlug = getPara(0, scope);
Product product = getProduct(idOrSlug);
if (product == null) {
return;
}
scope.setLocal("product", product);
renderBody(env, scope, writer);
}
private Product getProduct(String idOrSlug) {
return StrUtil.isNumeric(idOrSlug)
? service.findById(idOrSlug)
: service.findFirstBySlug(idOrSlug);
}
@Override
public boolean hasEnd() {
return true;
}
}
| JpressProjects/jpress | module-product/module-product-web/src/main/java/io/jpress/module/product/directive/ProductDirective.java | Java | lgpl-3.0 | 1,922 |
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ToastNotifications.Core;
namespace CustomNotificationsExample.CustomMessage
{
public class CustomNotification : NotificationBase, INotifyPropertyChanged
{
private CustomDisplayPart _displayPart;
public override NotificationDisplayPart DisplayPart => _displayPart ?? (_displayPart = new CustomDisplayPart(this));
public CustomNotification(string title, string message, MessageOptions messageOptions) : base(message, messageOptions)
{
Title = title;
Message = message;
}
#region binding properties
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged();
}
}
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
| raflop/ToastNotifications | Src/Examples/CustomNotificationsExample/CustomMessage/CustomNotification.cs | C# | lgpl-3.0 | 1,569 |
import { Secret } from '@aws-cdk/cdk'
import { config, SSM } from 'aws-sdk'
import * as lib from '../lib'
import { TokenParams } from '../types'
/**
* method to create and/or retrieve an SSM secret from aws.
*
* @param params can be either a new token from command line or an already existing token
**/
export async function handleSSMSecret(params: TokenParams) {
const { ssmHandler, tokenName, token } = params
if (tokenName === undefined) {
lib.noGithubTokenFound()
return { name: 'noToken', secret: new Secret('') }
}
// tslint:disable-next-line:no-unused-expression
token && (await ssmHandler.createParameter(tokenName, token))
const value = await ssmHandler.getParameter(tokenName)
return { name: tokenName, secret: new Secret(value) }
}
export class SSMHandler {
private ssm: SSM
constructor() {
const { credentials, region } = config
this.ssm = new SSM({ credentials, region })
}
async getParameter(ssmName: string) {
const params = { Name: ssmName, WithDecryption: true }
const ssmParam = await this.ssm.getParameter(params).promise()
return (ssmParam && ssmParam.Parameter && ssmParam.Parameter.Value) || ''
}
async createParameter(name: string, value: string) {
const type = 'SecureString'
const params = { Name: name, Overwrite: true, Type: type, Value: value }
await this.ssm.putParameter(params).promise()
}
}
| seagull-js/seagull | packages/deploy-aws/src/aws_sdk_handler/handle_ssm.ts | TypeScript | lgpl-3.0 | 1,401 |
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Loamen.Common
{
[StructLayout(LayoutKind.Sequential)]
public class OSVersionInfo
{
public int OSVersionInfoSize;
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string versionString;
}
[StructLayout(LayoutKind.Sequential)]
public struct OSVersionInfo2
{
public int OSVersionInfoSize;
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string versionString;
}
public class LibWrap
{
[DllImport("kernel32")]
public static extern bool GetVersionEx([In, Out] OSVersionInfo osvi);
[DllImport("kernel32", EntryPoint = "GetVersionEx")]
public static extern bool GetVersionEx2(ref OSVersionInfo2 osvi);
}
public class OSVersion
{
public static string VersionString
{
get
{
Console.WriteLine("\nPassing OSVersionInfo as class");
var osvi = new OSVersionInfo();
osvi.OSVersionInfoSize = Marshal.SizeOf(osvi);
LibWrap.GetVersionEx(osvi);
return string.Format("{0}(Builder {1}.{2}.{3})",
OpSysName(osvi.MajorVersion, osvi.MinorVersion, osvi.PlatformId), osvi.MajorVersion,
osvi.MinorVersion, osvi.BuildNumber);
}
}
/// <summary>
/// 获得IE版本
/// </summary>
public static string InternetExplorerVersion
{
get
{
string version = "";
using (
RegistryKey versionKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Internet Explorer"))
{
version = versionKey.GetValue("Version").ToString();
}
return version;
}
}
public static string OpSysName(int MajorVersion, int MinorVersion, int PlatformId)
{
String str_opn = String.Format("{0}.{1}", MajorVersion, MinorVersion);
switch (str_opn)
{
case "4.0":
return win95_nt40(PlatformId);
case "4.10":
return "Windows 98";
case "4.90":
return "Windows Me";
case "3.51":
return "Windows NT 3.51";
case "5.0":
return "Windows 2000";
case "5.1":
return "Windows XP";
case "5.2":
return "Windows Server 2003";
case "6.0":
return "Windows Vista";
case "6.1":
return "Windows 7";
case "6.2":
return "Windows 10";
default:
return "Unknown version";
}
}
public static string win95_nt40(int PlatformId)
{
switch (PlatformId)
{
case 1:
return "Windows 95";
case 2:
return "Windows NT 4.0";
default:
return "This windows version is not distinguish!";
}
}
}
} | loamen/ProxyHero | src/Loamen.Common/OSVersionInfo.cs | C# | lgpl-3.0 | 3,649 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.phd.thesis.activities;
import java.util.Optional;
import org.fenixedu.academic.domain.caseHandling.PreConditionNotValidException;
import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcess;
import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcessState;
import org.fenixedu.academic.domain.phd.conclusion.PhdConclusionProcess;
import org.fenixedu.academic.domain.phd.conclusion.PhdConclusionProcessBean;
import org.fenixedu.academic.domain.phd.thesis.PhdThesisProcess;
import org.fenixedu.bennu.core.domain.User;
import org.fenixedu.bennu.core.domain.UserLoginPeriod;
public class ConcludePhdProcess extends PhdThesisActivity {
@Override
protected void activityPreConditions(PhdThesisProcess process, User userView) {
if (!process.isAllowedToManageProcess(userView)) {
throw new PreConditionNotValidException();
}
if (!process.isConcluded()) {
throw new PreConditionNotValidException();
}
if (!isStudentCurricularPlanFinishedForPhd(process)) {
throw new PreConditionNotValidException();
}
}
/**
* TODO: phd-refactor
*
* Check if the root group of the phd student curricular plan is concluded is enough
* to be able to conclude the phd process.
*
* This should be changed when the phd process becomes itself a curriculum group.
*
* @param process the student's thesis process
* @return true if the root curriculum group has a conclusion process.
*/
private boolean isStudentCurricularPlanFinishedForPhd(PhdThesisProcess process) {
return Optional.ofNullable(process.getIndividualProgramProcess().getRegistration())
.map(r -> r.getLastStudentCurricularPlan().getRoot().isConclusionProcessed()).orElse(null);
}
@Override
protected PhdThesisProcess executeActivity(PhdThesisProcess process, User userView, Object object) {
PhdConclusionProcessBean bean = (PhdConclusionProcessBean) object;
PhdConclusionProcess.create(bean, userView.getPerson());
PhdIndividualProgramProcess individualProgramProcess = process.getIndividualProgramProcess();
if (!PhdIndividualProgramProcessState.CONCLUDED.equals(individualProgramProcess.getActiveState())) {
individualProgramProcess.createState(PhdIndividualProgramProcessState.CONCLUDED, userView.getPerson(), "");
}
UserLoginPeriod.createOpenPeriod(process.getPerson().getUser());
return process;
}
}
| cfscosta/fenix | src/main/java/org/fenixedu/academic/domain/phd/thesis/activities/ConcludePhdProcess.java | Java | lgpl-3.0 | 3,354 |
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* kdm/event/NextState.hpp
* Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es>
* Copyright (C) INCHRON GmbH 2016 <soeren.henning@inchron.com>
*
* EMF4CPP 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.
*
* EMF4CPP 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/>.
*/
#ifndef KDM_EVENT_NEXTSTATE_HPP
#define KDM_EVENT_NEXTSTATE_HPP
#include <ecorecpp/mapping_forward.hpp>
#include <kdm/dllKdm.hpp>
#include <kdm/event_forward.hpp>
#include <kdm/kdm_forward.hpp>
#include <kdm/event/AbstractEventRelationship.hpp>
#include "EventPackage.hpp"
/*PROTECTED REGION ID(NextState_pre) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
namespace kdm
{
namespace event
{
class EXPORT_KDM_DLL NextState : public virtual ::kdm::event::AbstractEventRelationship
{
public:
NextState();
virtual ~NextState();
virtual void _initialize();
// Operations
// Attributes
// References
virtual ::kdm::event::State_ptr getTo () const;
virtual void setTo (::kdm::event::State_ptr _to);
virtual ::kdm::event::Transition_ptr getFrom () const;
virtual void setFrom (::kdm::event::Transition_ptr _from);
/* This is the same value as getClassifierId() returns, but as a static
* value it can be used in template expansions. */
static const int classifierId = EventPackage::NEXTSTATE;
/*PROTECTED REGION ID(NextState) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
// EObjectImpl
virtual ::ecore::EJavaObject eGet ( ::ecore::EInt _featureID, ::ecore::EBoolean _resolve);
virtual void eSet ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue);
virtual ::ecore::EBoolean eIsSet ( ::ecore::EInt _featureID);
virtual void eUnset ( ::ecore::EInt _featureID);
virtual ::ecore::EClass_ptr _eClass ();
virtual void _inverseAdd ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue);
virtual void _inverseRemove ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _oldValue);
/*PROTECTED REGION ID(NextStateImpl) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
protected:
NextState_ptr _this()
{ return NextState_ptr(this);}
// Attributes
// References
::kdm::event::State_ptr m_to;
::kdm::event::Transition_ptr m_from;
};
}
// event
}// kdm
#endif // KDM_EVENT_NEXTSTATE_HPP
| catedrasaes-umu/emf4cpp | emf4cpp.tests/kdm/kdm/event/NextState.hpp | C++ | lgpl-3.0 | 3,452 |
<?php
namespace BlackBoxCode\Pando\TaxBundle\Model;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
trait RegionTrait
{
/**
* @var ArrayCollection<RegionTaxCategoryRateInterface>
*
* @ORM\OneToMany(targetEntity="RegionTaxCategoryRate", mappedBy="region")
*/
private $taxCategoryRates;
/**
* {@inheritdoc}
*/
public function getTaxCategoryRates()
{
if (is_null($this->taxCategoryRates)) $this->taxCategoryRates = new ArrayCollection();
return $this->taxCategoryRates;
}
/**
* {@inheritdoc}
*/
public function addTaxCategoryRate(RegionTaxCategoryRateInterface $taxCategoryRate)
{
if (is_null($this->taxCategoryRates)) $this->taxCategoryRates = new ArrayCollection();
$this->taxCategoryRates->add($taxCategoryRate);
return $this;
}
/**
* {@inheritdoc}
*/
public function removeTaxCategoryRate(RegionTaxCategoryRateInterface $taxCategoryRate)
{
if (is_null($this->taxCategoryRates)) $this->taxCategoryRates = new ArrayCollection();
$this->taxCategoryRates->removeElement($taxCategoryRate);
}
}
| BlackBoxRepo/PandoTaxBundle | Model/RegionTrait.php | PHP | lgpl-3.0 | 1,194 |
# -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon
#
# This file is part of a weboob module.
#
# This weboob module 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 weboob module 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 weboob module. If not, see <http://www.gnu.org/licenses/>.
import re
import json
from datetime import datetime
from weboob.browser.pages import LoggedPage, HTMLPage, JsonPage
from weboob.browser.elements import DictElement, ItemElement, method
from weboob.browser.filters.standard import Date, CleanDecimal, CleanText, Format, Field, Env, Regexp, Currency
from weboob.browser.filters.json import Dict
from weboob.capabilities import NotAvailable
from weboob.capabilities.bank import Account, Loan
from weboob.capabilities.contact import Advisor
from weboob.capabilities.profile import Profile
from weboob.capabilities.bill import DocumentTypes, Subscription, Document
from weboob.tools.capabilities.bank.transactions import FrenchTransaction
from weboob.exceptions import BrowserUnavailable
class Transaction(FrenchTransaction):
PATTERNS = [
(re.compile(r'^CB (?P<text>.*?) FACT (?P<dd>\d{2})(?P<mm>\d{2})(?P<yy>\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD),
(re.compile(r'^RET(RAIT)? DAB (?P<dd>\d+)-(?P<mm>\d+)-.*', re.IGNORECASE), FrenchTransaction.TYPE_WITHDRAWAL),
(re.compile(r'^RET(RAIT)? DAB (?P<text>.*?) (?P<dd>\d{2})(?P<mm>\d{2})(?P<yy>\d{2}) (?P<HH>\d{2})H(?P<MM>\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_WITHDRAWAL),
(re.compile(r'^VIR(EMENT)?(\.PERIODIQUE)? (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_TRANSFER),
(re.compile(r'^PRLV (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_ORDER),
(re.compile(r'^CHEQUE.*', re.IGNORECASE), FrenchTransaction.TYPE_CHECK),
(re.compile(r'^(CONVENTION \d+ )?COTIS(ATION)? (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_BANK),
(re.compile(r'^\* (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_BANK),
(re.compile(r'^REMISE (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_DEPOSIT),
(re.compile(r'^(?P<text>.*)( \d+)? QUITTANCE .*', re.IGNORECASE), FrenchTransaction.TYPE_ORDER),
(re.compile(r'^CB [\d\*]+ TOT DIF .*', re.IGNORECASE), FrenchTransaction.TYPE_CARD_SUMMARY),
(re.compile(r'^CB [\d\*]+ (?P<text>.*)', re.IGNORECASE), FrenchTransaction.TYPE_CARD),
(re.compile(r'^CB (?P<text>.*?) (?P<dd>\d{2})(?P<mm>\d{2})(?P<yy>\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD),
(re.compile(r'\*CB (?P<text>.*?) (?P<dd>\d{2})(?P<mm>\d{2})(?P<yy>\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD),
(re.compile(r'^FAC CB (?P<text>.*?) (?P<dd>\d{2})/(?P<mm>\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD),
]
class LoginPage(JsonPage):
def get_response(self):
return self.doc
class CenetLoginPage(HTMLPage):
def login(self, username, password, nuser, codeCaisse, _id, vkpass):
form = self.get_form(id='aspnetForm')
form['__EVENTTARGET'] = "btn_authentifier_securise"
form['__EVENTARGUMENT'] = '{"CodeCaisse":"%s","NumeroBad":"%s","NumeroUsager":"%s",\
"MotDePasse":"%s","IdentifiantClavier":"%s","ChaineConnexion":"%s"}' \
% (codeCaisse, username, nuser, password, _id, vkpass)
form.submit()
class CenetHomePage(LoggedPage, HTMLPage):
@method
class get_advisor(ItemElement):
klass = Advisor
obj_name = CleanText('//section[contains(@id, "ChargeAffaires")]//strong')
obj_email = CleanText('//li[contains(@id, "MailContact")]')
obj_phone = CleanText('//li[contains(@id, "TelAgence")]', replace=[('.', '')])
obj_mobile = NotAvailable
obj_agency = CleanText('//section[contains(@id, "Agence")]//strong')
obj_address = CleanText('//li[contains(@id, "AdresseAgence")]')
def obj_fax(self):
return CleanText('//li[contains(@id, "FaxAgence")]', replace=[('.', '')])(self) or NotAvailable
@method
class get_profile(ItemElement):
klass = Profile
obj_name = CleanText('//li[@class="identite"]/a/span')
class CenetJsonPage(JsonPage):
def __init__(self, browser, response, *args, **kwargs):
super(CenetJsonPage, self).__init__(browser, response, *args, **kwargs)
# Why you are so ugly....
self.doc = json.loads(self.doc['d'])
if self.doc['Erreur'] and (self.doc['Erreur']['Titre'] or self.doc['Erreur']['Code']):
self.logger.warning('error on %r: %s', self.url, self.doc['Erreur']['Titre'] or self.doc['Erreur']['Code'])
raise BrowserUnavailable(self.doc['Erreur']['Titre'] or self.doc['Erreur']['Description'])
self.doc['DonneesSortie'] = json.loads(self.doc['DonneesSortie'])
class CenetAccountsPage(LoggedPage, CenetJsonPage):
ACCOUNT_TYPES = {'CCP': Account.TYPE_CHECKING}
@method
class get_accounts(DictElement):
item_xpath = "DonneesSortie"
class item(ItemElement):
klass = Account
obj_id = CleanText(Dict('Numero'))
obj_label = CleanText(Dict('Intitule'))
obj_iban = CleanText(Dict('IBAN'))
def obj_balance(self):
absolut_amount = CleanDecimal(Dict('Solde/Valeur'))(self)
if CleanText(Dict('Solde/CodeSens'))(self) == 'D':
return -absolut_amount
return absolut_amount
def obj_currency(self):
return CleanText(Dict('Devise'))(self).upper()
def obj_type(self):
return self.page.ACCOUNT_TYPES.get(Dict('TypeCompte')(self), Account.TYPE_UNKNOWN)
def obj__formated(self):
return self.el
class CenetLoanPage(LoggedPage, CenetJsonPage):
@method
class get_accounts(DictElement):
item_xpath = "DonneesSortie"
class item(ItemElement):
klass = Loan
obj_id = CleanText(Dict('IdentifiantUniqueContrat'), replace=[(' ', '-')])
obj_label = CleanText(Dict('Libelle'))
obj_total_amount = CleanDecimal(Dict('MontantInitial/Valeur'))
obj_currency = Currency(Dict('MontantInitial/Devise'))
obj_type = Account.TYPE_LOAN
obj_duration = CleanDecimal(Dict('Duree'))
obj_rate = CleanDecimal.French(Dict('Taux'))
obj_next_payment_amount = CleanDecimal(Dict('MontantProchaineEcheance/Valeur'))
def obj_balance(self):
balance = CleanDecimal(Dict('CapitalRestantDu/Valeur'))(self)
if balance > 0:
balance *= -1
return balance
def obj_subscription_date(self):
sub_date = Dict('DateDebutEffet')(self)
if sub_date:
date = CleanDecimal().filter(sub_date) / 1000
return datetime.fromtimestamp(date).date()
return NotAvailable
def obj_maturity_date(self):
mat_date = Dict('DateDerniereEcheance')(self)
if mat_date:
date = CleanDecimal().filter(mat_date) / 1000
return datetime.fromtimestamp(date).date()
return NotAvailable
def obj_next_payment_date(self):
next_date = Dict('DateProchaineEcheance')(self)
if next_date:
date = CleanDecimal().filter(next_date) / 1000
return datetime.fromtimestamp(date).date()
return NotAvailable
class CenetCardsPage(LoggedPage, CenetJsonPage):
def get_cards(self):
cards = Dict('DonneesSortie')(self.doc)
# Remove dates to prevent bad parsing
def reword_dates(card):
tmp_card = card
for k, v in tmp_card.items():
if isinstance(v, dict):
v = reword_dates(v)
if k == "Date" and v is not None and "Date" in v:
card[k] = None
for card in cards:
reword_dates(card)
return cards
class CenetAccountHistoryPage(LoggedPage, CenetJsonPage):
TR_TYPES_LABEL = {
'VIR': Transaction.TYPE_TRANSFER,
'CHEQUE': Transaction.TYPE_CHECK,
'REMISE CHEQUE': Transaction.TYPE_CASH_DEPOSIT,
'PRLV': Transaction.TYPE_ORDER,
}
TR_TYPES_API = {
'VIR': Transaction.TYPE_TRANSFER,
'PE': Transaction.TYPE_ORDER, # PRLV
'CE': Transaction.TYPE_CHECK, # CHEQUE
'DE': Transaction.TYPE_CASH_DEPOSIT, # APPRO
'PI': Transaction.TYPE_CASH_DEPOSIT, # REMISE CHEQUE
}
@method
class get_history(DictElement):
item_xpath = "DonneesSortie"
class item(ItemElement):
klass = Transaction
obj_raw = Format('%s %s', Dict('Libelle'), Dict('Libelle2'))
obj_label = CleanText(Dict('Libelle'))
obj_date = Date(Dict('DateGroupImputation'), dayfirst=True)
obj_rdate = Date(Dict('DateGroupReglement'), dayfirst=True)
def obj_type(self):
ret = Transaction.TYPE_UNKNOWN
# The API may send the same key for 'PRLV' and 'VIR' transactions
# So the label is checked first, then the API key
for k, v in self.page.TR_TYPES_LABEL.items():
if Field('label')(self).startswith(k):
ret = v
break
if ret == Transaction.TYPE_UNKNOWN:
ret = self.page.TR_TYPES_API.get(Dict('TypeOperationDisplay')(self), Transaction.TYPE_UNKNOWN)
if ret != Transaction.TYPE_UNKNOWN:
return ret
for pattern, type in Transaction.PATTERNS:
if pattern.match(Field('raw')(self)):
return type
return Transaction.TYPE_UNKNOWN
def obj_amount(self):
amount = CleanDecimal(Dict('Montant/Valeur'))(self)
return -amount if Dict('Montant/CodeSens')(self) == "D" else amount
def next_offset(self):
offset = Dict('OffsetSortie')(self.doc)
if offset:
assert Dict('EstComplete')(self.doc) == 'false'
return offset
class CenetCardSummaryPage(LoggedPage, CenetJsonPage):
@method
class get_history(DictElement):
item_xpath = "DonneesSortie/OperationsCB"
class item(ItemElement):
klass = Transaction
obj_label = CleanText(Dict('Libelle'))
obj_date = Date(Dict('DateGroupImputation'), dayfirst=True)
obj_type = Transaction.TYPE_DEFERRED_CARD
def obj_raw(self):
label = Dict('Libelle')(self)
label2 = Dict('Libelle2')(self)
if label2 and label2 != 'None':
return '%s %s' % (label, label2)
else:
return label
def obj_rdate(self):
rdate = re.search('(FACT\s)(\d{6})', Field('label')(self))
if rdate.group(2):
return Date(dayfirst=True).filter(rdate.group(2))
return NotAvailable
def obj_amount(self):
amount = CleanDecimal(Dict('Montant/Valeur'))(self)
return -amount if Dict('Montant/CodeSens')(self) == "D" else amount
class _LogoutPage(HTMLPage):
def on_load(self):
raise BrowserUnavailable(CleanText('//*[@class="messErreur"]')(self.doc))
class ErrorPage(_LogoutPage):
pass
class UnavailablePage(HTMLPage):
def on_load(self):
raise BrowserUnavailable(CleanText('//div[@id="message_error_hs"]')(self.doc))
class SubscriptionPage(LoggedPage, CenetJsonPage):
@method
class iter_subscription(DictElement):
item_xpath = 'DonneesSortie'
class item(ItemElement):
klass = Subscription
obj_id = CleanText(Dict('Numero'))
obj_label = CleanText(Dict('Intitule'))
obj_subscriber = Env('subscriber')
@method
class iter_documents(DictElement):
item_xpath = 'DonneesSortie'
class item(ItemElement):
klass = Document
obj_id = Format('%s_%s_%s', Env('sub_id'), Dict('Numero'), CleanText(Env('french_date'), symbols='/'))
obj_format = 'pdf'
obj_type = DocumentTypes.OTHER
obj__numero = CleanText(Dict('Numero'))
obj__sub_id = Env('sub_id')
obj__sub_label = Env('sub_label')
obj__download_id = CleanText(Dict('IdDocument'))
def obj_date(self):
date = Regexp(Dict('DateArrete'), r'Date\((\d+)\)')(self)
date = int(date) // 1000
return datetime.fromtimestamp(date).date()
def obj_label(self):
return '%s %s' % (CleanText(Dict('Libelle'))(self), Env('french_date')(self))
def parse(self, el):
self.env['french_date'] = Field('date')(self).strftime('%d/%m/%Y')
class DownloadDocumentPage(LoggedPage, HTMLPage):
def download_form(self, document):
data = {
'Numero': document._numero,
'Libelle': document._sub_label.replace(' ', '+'),
'DateArrete': '',
'IdDocument': document._download_id
}
form = self.get_form(id='aspnetForm')
form['__EVENTTARGET'] = 'btn_telecharger'
form['__EVENTARGUMENT'] = json.dumps(data)
return form.submit()
| laurentb/weboob | modules/caissedepargne/cenet/pages.py | Python | lgpl-3.0 | 14,121 |
<?php
class shopKmphonemaskvalidatePlugin extends shopPlugin
{
private $enable;
private $where;
private $phone_mask;
private $phone_placeholder;
private $validate;
private $error_msg;
private $phone_input_names;
/***
* @var waSmarty3View|waView
*/
private $view;
public function getAllSettings()
{
$this->enable = $this->getSettings('enable') ? 1 : 0;
$this->where = $this->getSettings('where');
$this->phone_mask = $this->getSettings('phone_mask');
$this->phone_placeholder = $this->getSettings('phone_placeholder');
$this->error_msg = $this->getSettings('error_msg');
$this->error_msg = ifempty($this->error_msg, 'Неверный формат');
$this->validate = $this->getSettings('validate') ? 1 : 0;
$this->phone_input_names = $this->getSettings('phone_input_names');
if (empty($this->phone_input_names)) {
$this->phone_input_names = 'phone';
}
$this->view = wa()->getView();
if (!empty($this->phone_input_names)) {
$this->phone_input_names = explode(',', $this->getSettings('phone_input_names'));
foreach ($this->phone_input_names as $i => $phone) {
$this->phone_input_names[$i] = '[name*="[' . trim($phone) . ']"]';
}
$this->view->assign('phone_input_names', join(', ', $this->phone_input_names));
} else {
$this->phone_input_names = false;
}
$this->view->assign('where', $this->where);
$this->view->assign('error_msg', $this->error_msg);
$this->view->assign('phone_mask', $this->phone_mask);
$this->view->assign('phone_placeholder', $this->phone_placeholder);
$this->view->assign('validate', $this->validate);
}
public function frontendFooterHandler()
{
$this->getAllSettings();
if ($this->enable && $this->where == 'everywhere' && $this->phone_input_names) {
$this->addJs('js/jquery.mask.min.js', true);
return $this->view->fetch($this->path . '/templates/PhoneMaskAndValidate.html');
}
return false;
}
public function frontendCheckoutHandler()
{
$this->getAllSettings();
if ($this->enable && $this->where == 'checkout' && $this->phone_input_names) {
$this->addJs('js/jquery.mask.min.js', true);
return $this->view->fetch($this->path . '/templates/PhoneMaskAndValidate.html');
}
return false;
}
}
| aborz/webasyst | wa-apps/shop/plugins/kmphonemaskvalidate/lib/shopKmphonemaskvalidatePlugin.class.php | PHP | lgpl-3.0 | 2,557 |
//
// Created by tyler on 10/15/17.
//
#ifndef YAFEL_FVDOFM_HPP
#define YAFEL_FVDOFM_HPP
#include "yafel_globals.hpp"
#include "utils/DoFManager.hpp"
YAFEL_NAMESPACE_OPEN
/**
* \class FVDofm
* DoFManager-like class for finite volume methods
*
* Holds the required geometry information for Finite Volume simulations.
* - Linear Mesh Nodes
* - List of "full-dimension" (topodim == spatialDim) cells
* - Maps FV-indexes to Original element indices
* - Also store inverse mapping (with -1 in the invalid element slots)
* - Volumes of full-dimension elements
* - Centroids of FV cells
* - DoFM reference with faces built
*
*/
class FVDofm {
public:
FVDofm(DoFManager &dofm_, int8_t NSD);
DoFManager dofm;
int8_t nsd;
std::vector<int> original_cell_index; //map current index -> old_index
std::vector<int> reverse_index_map; //map old_index -> current index
std::vector<coordinate<>> centroids;
std::vector<double> volumes;
};
YAFEL_NAMESPACE_CLOSE
#endif //YAFEL_FVDOFM_HPP
| tjolsen/YAFEL | apps/FiniteVolume/FVDofm.hpp | C++ | lgpl-3.0 | 1,029 |
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* kdm/data/ChoiceContentImpl.cpp
* Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es>
* Copyright (C) INCHRON GmbH 2016 <soeren.henning@inchron.com>
*
* EMF4CPP 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.
*
* EMF4CPP 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/>.
*/
#include "ChoiceContent.hpp"
#include <kdm/data/DataPackage.hpp>
#include <kdm/data/ComplexContentType.hpp>
#include <kdm/kdm/Attribute.hpp>
#include <kdm/kdm/Annotation.hpp>
#include <kdm/kdm/Stereotype.hpp>
#include <kdm/kdm/ExtendedValue.hpp>
#include <kdm/source/SourceRef.hpp>
#include <kdm/data/AbstractDataRelationship.hpp>
#include <kdm/action/ActionElement.hpp>
#include <kdm/data/AbstractContentElement.hpp>
#include <kdm/core/KDMRelationship.hpp>
#include <kdm/core/AggregatedRelationship.hpp>
#include <kdm/core/KDMEntity.hpp>
#include <kdm/kdm/KDMModel.hpp>
#include <ecore/EObject.hpp>
#include <ecore/EClass.hpp>
#include <ecore/EStructuralFeature.hpp>
#include <ecore/EReference.hpp>
#include <ecore/EObject.hpp>
#include <ecorecpp/mapping.hpp>
/*PROTECTED REGION ID(ChoiceContentImpl.cpp) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
using namespace ::kdm::data;
void ChoiceContent::_initialize()
{
// Supertypes
::kdm::data::ComplexContentType::_initialize();
// References
/*PROTECTED REGION ID(ChoiceContentImpl__initialize) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
}
// Operations
// EObject
::ecore::EJavaObject ChoiceContent::eGet(::ecore::EInt _featureID,
::ecore::EBoolean _resolve)
{
::ecore::EJavaObject _any;
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
_any = m_attribute->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
_any = m_annotation->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
_any = m_stereotype->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
_any = m_taggedValue->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::core::CorePackage::KDMENTITY__NAME:
{
::ecorecpp::mapping::any_traits < ::kdm::core::String
> ::toAny(_any, m_name);
}
return _any;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__SOURCE:
{
_any = m_source->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__DATARELATION:
{
_any = m_dataRelation->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__ABSTRACTION:
{
_any = m_abstraction->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
case ::kdm::data::DataPackage::COMPLEXCONTENTTYPE__CONTENTELEMENT:
{
_any = m_contentElement->asEListOf< ::ecore::EObject_ptr >();
}
return _any;
}
throw "Error";
}
void ChoiceContent::eSet(::ecore::EInt _featureID,
::ecore::EJavaObject const& _newValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::Element::getAttribute().clear();
::kdm::core::Element::getAttribute().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::Element::getAnnotation().clear();
::kdm::core::Element::getAnnotation().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::ModelElement::getStereotype().clear();
::kdm::core::ModelElement::getStereotype().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::core::ModelElement::getTaggedValue().clear();
::kdm::core::ModelElement::getTaggedValue().insert_all(*_t0);
}
return;
case ::kdm::core::CorePackage::KDMENTITY__NAME:
{
::kdm::core::String _t0;
::ecorecpp::mapping::any_traits < ::kdm::core::String
> ::fromAny(_newValue, _t0);
::kdm::core::KDMEntity::setName(_t0);
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__SOURCE:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::data::AbstractDataElement::getSource().clear();
::kdm::data::AbstractDataElement::getSource().insert_all(*_t0);
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__DATARELATION:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::data::AbstractDataElement::getDataRelation().clear();
::kdm::data::AbstractDataElement::getDataRelation().insert_all(*_t0);
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__ABSTRACTION:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::data::AbstractDataElement::getAbstraction().clear();
::kdm::data::AbstractDataElement::getAbstraction().insert_all(*_t0);
}
return;
case ::kdm::data::DataPackage::COMPLEXCONTENTTYPE__CONTENTELEMENT:
{
::ecorecpp::mapping::EList< ::ecore::EObject_ptr >::ptr_type _t0 =
::ecorecpp::mapping::any::any_cast < ::ecorecpp::mapping::EList
< ::ecore::EObject_ptr > ::ptr_type > (_newValue);
::kdm::data::ComplexContentType::getContentElement().clear();
::kdm::data::ComplexContentType::getContentElement().insert_all(*_t0);
}
return;
}
throw "Error";
}
::ecore::EBoolean ChoiceContent::eIsSet(::ecore::EInt _featureID)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
return m_attribute && m_attribute->size();
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
return m_annotation && m_annotation->size();
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
return m_stereotype && m_stereotype->size();
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
return m_taggedValue && m_taggedValue->size();
case ::kdm::core::CorePackage::KDMENTITY__NAME:
return ::ecorecpp::mapping::set_traits < ::kdm::core::String
> ::is_set(m_name);
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__SOURCE:
return m_source && m_source->size();
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__DATARELATION:
return m_dataRelation && m_dataRelation->size();
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__ABSTRACTION:
return m_abstraction && m_abstraction->size();
case ::kdm::data::DataPackage::COMPLEXCONTENTTYPE__CONTENTELEMENT:
return m_contentElement && m_contentElement->size();
}
throw "Error";
}
void ChoiceContent::eUnset(::ecore::EInt _featureID)
{
switch (_featureID)
{
}
throw "Error";
}
::ecore::EClass_ptr ChoiceContent::_eClass()
{
static ::ecore::EClass_ptr _eclass =
dynamic_cast< ::kdm::data::DataPackage* >(::kdm::data::DataPackage::_instance().get())->getChoiceContent();
return _eclass;
}
/** Set the local end of a reference with an EOpposite property.
*/
void ChoiceContent::_inverseAdd(::ecore::EInt _featureID,
::ecore::EJavaObject const& _newValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__SOURCE:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__DATARELATION:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__ABSTRACTION:
{
}
return;
case ::kdm::data::DataPackage::COMPLEXCONTENTTYPE__CONTENTELEMENT:
{
}
return;
}
throw "Error: _inverseAdd() does not handle this featureID";
}
/** Unset the local end of a reference with an EOpposite property.
*/
void ChoiceContent::_inverseRemove(::ecore::EInt _featureID,
::ecore::EJavaObject const& _oldValue)
{
switch (_featureID)
{
case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE:
{
}
return;
case ::kdm::core::CorePackage::ELEMENT__ANNOTATION:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE:
{
}
return;
case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__SOURCE:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__DATARELATION:
{
}
return;
case ::kdm::data::DataPackage::ABSTRACTDATAELEMENT__ABSTRACTION:
{
}
return;
case ::kdm::data::DataPackage::COMPLEXCONTENTTYPE__CONTENTELEMENT:
{
}
return;
}
throw "Error: _inverseRemove() does not handle this featureID";
}
| catedrasaes-umu/emf4cpp | emf4cpp.tests/kdm/kdm/data/ChoiceContentImpl.cpp | C++ | lgpl-3.0 | 11,625 |
using System;
using System.Collections.Generic;
using System.Linq;
using umbraco.interfaces;
using umbraco.NodeFactory;
using Umbraco.Core.Events;
using Umbraco.Core.Services;
using umbraco.MacroEngines;
namespace Newsroom
{
public class EventHandler : IApplicationStartupHandler
{
readonly int newsRoot = new DynamicNode(-1).Descendants("NewsroomHome").Items[0].Id;
const string ARTICLE_ALIAS = "NewsroomPressRelease";
const string YEAR_ALIAS = "NewsroomArchiveYear";
const string MONTH_ALIAS = "NewsroomArchiveMonth";
public EventHandler()
{
ContentService.Saving += SavingEvent;
}
private void SavingEvent(IContentService sender, SaveEventArgs<Umbraco.Core.Models.IContent> e)
{
foreach (var node in e.SavedEntities)
{
if (node.ContentType.Alias == ARTICLE_ALIAS)
{
//default to today if no date is specified, or if date is invalid (date comes back as year 1, month 1, etc
if (node.GetValue("newsroomDate") == null || DateTime.Parse(node.GetValue("newsroomDate").ToString()).Year == 1)
{
node.SetValue("newsroomDate", DateTime.Now);
}
//abort if node half-exists, need a proper way of checking this
try { var test = (DateTime)node.GetValue("newsroomDate"); }
catch { break; }
DateTime pubDate = (DateTime)node.GetValue("newsroomDate");
string pubYear = pubDate.Year.ToString();//year in format like "2013"
string pubMonth = pubDate.ToString("MMMM");//month in format like "January"
int oldParentId = node.ParentId;
var homeNode = new Node(newsRoot);
//set year node if there already is one
int yearNodeId = (from childNode in homeNode.ChildrenAsList where childNode.Name == pubYear select childNode.Id).FirstOrDefault();
if (yearNodeId == 0)
{
//No year node, create one
var contentService = new ContentService();
var yearFolder = contentService.CreateContent(pubYear, newsRoot, YEAR_ALIAS);
contentService.SaveAndPublish(yearFolder);
//sort year folders into descending order
var sorter = new umbraco.presentation.webservices.nodeSorter();
//get a comma separated list of node id's of the years in order of their name - 2014, 2013, etc
var yearOrder = "";
Dictionary<string, int> yearDict = new Dictionary<string, int>();
foreach (var yearNode in new Node(newsRoot).ChildrenAsList)
{//order the year nodes
if (yearNode.NodeTypeAlias == YEAR_ALIAS)
{
yearDict.Add(yearNode.Name, yearNode.Id);
}
}
var yearList = yearDict.Keys.ToList();
yearList.Sort();
yearList.Reverse();
foreach (var otherNode in new Node(newsRoot).ChildrenAsList)
{//put all the other nodes at the bottom
if (otherNode.NodeTypeAlias != YEAR_ALIAS)
{
yearList.Add(otherNode.Name);
yearDict.Add(otherNode.Name, otherNode.Id);
}
}
foreach (var key in yearList)
{
yearOrder += yearDict[key] + ",";
}
//trim last comma
yearOrder = yearOrder.Substring(0, yearOrder.Length - 1);
sorter.UpdateSortOrder(newsRoot, yearOrder);
yearNodeId = yearFolder.Id;
}
//set mont node if there already is one
int monthNodeId = (from childNode in new Node(yearNodeId).ChildrenAsList where childNode.Name == pubMonth select childNode.Id).FirstOrDefault();
if (monthNodeId == 0)
{
//No month node, create one
var contentService = new ContentService();
var monthFolder = contentService.CreateContent(pubMonth, yearNodeId, MONTH_ALIAS);
contentService.SaveAndPublish(monthFolder);
//sort month folders into descending order
var sorter = new umbraco.presentation.webservices.nodeSorter();
//get a comma separated list of node id's of the months in order of their name - jan, feb, etc
string monthOrder = "";
for (int i = 12; i > 0; i--)
{
string monthName = new DateTime(1970, i, 1, 0, 0, 0).ToString("MMMM");
foreach (var monthNode in new Node(yearNodeId).ChildrenAsList)
{
if (monthNode.Name == monthName)
{
monthOrder += monthNode.Id + ",";
break;
}
}
}
//trim last comma
monthOrder = monthOrder.Substring(0, monthOrder.Length - 1);
sorter.UpdateSortOrder(yearNodeId, monthOrder);
monthNodeId = monthFolder.Id;
}
//Now we move the modified news story into the folder that matches its date property
bool movedMonth = node.ParentId != monthNodeId;
bool movedYear = node.ContentType.Alias != MONTH_ALIAS || new Node(node.ParentId).Parent.Id != yearNodeId;
if (movedMonth)
{
sender.Move(node, monthNodeId);
umbraco.BasePages.BasePage.Current.ClientTools.ChangeContentFrameUrl("editContent.aspx?id=" + node.Id);
}
}
}
}
}
} | HfdsCouncil/Newsroom | unpackaged/app_code/EventHandler.cs | C# | lgpl-3.0 | 5,476 |
"""
.15925 Editor
Copyright 2014 TechInvestLab.ru dot15926@gmail.com
.15925 Editor 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.0 of the License, or (at your option) any later version.
.15925 Editor 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 .15925 Editor.
"""
from iso15926.tools.environment import EnvironmentContext
from PySide.QtCore import *
from PySide.QtGui import *
import os
from framework.dialogs import Choice
class TestWindow(QDialog):
vis_label = tm.main.tests_title
tests_dir = 'tests'
def __init__(self):
QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.setWindowTitle(self.vis_label)
layout = QVBoxLayout(self)
box = QGroupBox(tm.main.tests_field, self)
self.tests_list = QListWidget(box)
boxlayout = QHBoxLayout(box)
boxlayout.addWidget(self.tests_list)
layout.addWidget(box)
for n in os.listdir(self.tests_dir):
if n.startswith(".") or not n.endswith('.py'):
continue
sp = os.path.splitext(n)
item = QListWidgetItem(sp[0], self.tests_list)
item.setCheckState(Qt.Unchecked)
self.btn_prepare = QPushButton(tm.main.prepare, self)
self.btn_prepare.setToolTip(tm.main.prepare_selected_tests)
self.btn_prepare.clicked.connect(self.OnPrepare)
self.btn_run = QPushButton(tm.main.run, self)
self.btn_run.setToolTip(tm.main.run_selected_tests)
self.btn_run.clicked.connect(self.OnRun)
self.btn_sel_all = QPushButton(tm.main.select_all, self)
self.btn_sel_all.clicked.connect(self.SelectAll)
self.btn_unsel_all = QPushButton(tm.main.unselect_all, self)
self.btn_unsel_all.clicked.connect(self.UnselectAll)
self.btn_cancel = QPushButton(tm.main.cancel, self)
self.btn_cancel.clicked.connect(self.reject)
btnlayout = QHBoxLayout()
btnlayout.addWidget(self.btn_sel_all)
btnlayout.addWidget(self.btn_unsel_all)
btnlayout.addStretch()
btnlayout.addWidget(self.btn_prepare)
btnlayout.addWidget(self.btn_run)
btnlayout.addWidget(self.btn_cancel)
layout.addLayout(btnlayout)
box = QGroupBox(tm.main.tests_result_field, self)
self.report = QPlainTextEdit(self)
boxlayout = QHBoxLayout(box)
boxlayout.addWidget(self.report)
layout.addWidget(box)
self.exec_()
def SelectAll(self):
self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)])
def UnselectAll(self):
self.tests_list.SetChecked([])
def OnPrepare(self):
if Choice(tm.main.tests_prepare_warning):
for k in self.tests_list.CheckedStrings:
self.report.AppendText(tm.main.tests_preparing.format(k))
locals = {'mode': 'prepare'}
ec = EnvironmentContext(None, locals)
ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py'))
self.report.AppendText(tm.main.tests_preparing_done)
def OnRun(self):
all_passed = True
self.report.appendPlainText(tm.main.tests_running)
count = 0
passed = 0
for i in xrange(self.tests_list.count()):
item = self.tests_list.item(i)
name = item.text()
if not item.checkState() == Qt.Checked:
continue
count += 1
locals = {'mode': 'run', 'passed': False}
ec = EnvironmentContext(None, locals)
ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py'))
if locals['passed']:
passed += 1
self.report.appendPlainText(tm.main.test_passed.format(name))
else:
self.report.appendPlainText(tm.main.test_failed.format(name))
self.report.appendPlainText(tm.main.tests_result)
self.report.appendPlainText(tm.main.tests_result_info.format(passed, count))
if os.path.exists(TestWindow.tests_dir):
@public('workbench.menu.help')
class xTestMenu:
vis_label = tm.main.menu_tests
@classmethod
def Do(cls):
TestWindow()
| TechInvestLab/dot15926 | editor_qt/iso15926/common/testing.py | Python | lgpl-3.0 | 4,639 |
/*
Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file
This file is part of libzmq, the ZeroMQ core engine in C++.
libzmq is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
As a special exception, the Contributors give you permission to link
this library with independent modules to produce an executable,
regardless of the license terms of these independent modules, and to
copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the
terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library.
If you modify this library, you must extend this exception to your
version of the library.
libzmq 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/>.
*/
#include <stddef.h>
#include "poller.hpp"
#include "proxy.hpp"
#include "likely.hpp"
// On AIX platform, poll.h has to be included first to get consistent
// definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
// instead of 'events' and 'revents' and defines macros to map from POSIX-y
// names to AIX-specific names).
#if defined ZMQ_POLL_BASED_ON_POLL
#include <poll.h>
#endif
// These headers end up pulling in zmq.h somewhere in their include
// dependency chain
#include "socket_base.hpp"
#include "err.hpp"
// zmq.h must be included *after* poll.h for AIX to build properly
#include "../include/zmq.h"
int capture(
class zmq::socket_base_t *capture_,
zmq::msg_t& msg_,
int more_ = 0)
{
// Copy message to capture socket if any
if (capture_) {
zmq::msg_t ctrl;
int rc = ctrl.init ();
if (unlikely (rc < 0))
return -1;
rc = ctrl.copy (msg_);
if (unlikely (rc < 0))
return -1;
rc = capture_->send (&ctrl, more_? ZMQ_SNDMORE: 0);
if (unlikely (rc < 0))
return -1;
}
return 0;
}
int forward(
class zmq::socket_base_t *from_,
class zmq::socket_base_t *to_,
class zmq::socket_base_t *capture_,
zmq::msg_t& msg_)
{
int more;
size_t moresz;
while (true) {
int rc = from_->recv (&msg_, 0);
if (unlikely (rc < 0))
return -1;
moresz = sizeof more;
rc = from_->getsockopt (ZMQ_RCVMORE, &more, &moresz);
if (unlikely (rc < 0))
return -1;
// Copy message to capture socket if any
rc = capture(capture_, msg_, more);
if (unlikely (rc < 0))
return -1;
rc = to_->send (&msg_, more? ZMQ_SNDMORE: 0);
if (unlikely (rc < 0))
return -1;
if (more == 0)
break;
}
return 0;
}
int zmq::proxy (
class socket_base_t *frontend_,
class socket_base_t *backend_,
class socket_base_t *capture_,
class socket_base_t *control_)
{
msg_t msg;
int rc = msg.init ();
if (rc != 0)
return -1;
// The algorithm below assumes ratio of requests and replies processed
// under full load to be 1:1.
int more;
size_t moresz;
zmq_pollitem_t items [] = {
{ frontend_, 0, ZMQ_POLLIN, 0 },
{ backend_, 0, ZMQ_POLLIN, 0 },
{ control_, 0, ZMQ_POLLIN, 0 }
};
int qt_poll_items = (control_ ? 3 : 2);
zmq_pollitem_t itemsout [] = {
{ frontend_, 0, ZMQ_POLLOUT, 0 },
{ backend_, 0, ZMQ_POLLOUT, 0 }
};
// Proxy can be in these three states
enum {
active,
paused,
terminated
} state = active;
while (state != terminated) {
// Wait while there are either requests or replies to process.
rc = zmq_poll (&items [0], qt_poll_items, -1);
if (unlikely (rc < 0))
return -1;
// Get the pollout separately because when combining this with pollin it maxes the CPU
// because pollout shall most of the time return directly
rc = zmq_poll (&itemsout [0], 2, 0);
if (unlikely (rc < 0))
return -1;
// Process a control command if any
if (control_ && items [2].revents & ZMQ_POLLIN) {
rc = control_->recv (&msg, 0);
if (unlikely (rc < 0))
return -1;
moresz = sizeof more;
rc = control_->getsockopt (ZMQ_RCVMORE, &more, &moresz);
if (unlikely (rc < 0) || more)
return -1;
// Copy message to capture socket if any
rc = capture(capture_, msg);
if (unlikely (rc < 0))
return -1;
if (msg.size () == 5 && memcmp (msg.data (), "PAUSE", 5) == 0)
state = paused;
else
if (msg.size () == 6 && memcmp (msg.data (), "RESUME", 6) == 0)
state = active;
else
if (msg.size () == 9 && memcmp (msg.data (), "TERMINATE", 9) == 0)
state = terminated;
else {
// This is an API error, we should assert
puts ("E: invalid command sent to proxy");
zmq_assert (false);
}
}
// Process a request
if (state == active
&& items [0].revents & ZMQ_POLLIN
&& itemsout [1].revents & ZMQ_POLLOUT) {
rc = forward(frontend_, backend_, capture_,msg);
if (unlikely (rc < 0))
return -1;
}
// Process a reply
if (state == active
&& items [1].revents & ZMQ_POLLIN
&& itemsout [0].revents & ZMQ_POLLOUT) {
rc = forward(backend_, frontend_, capture_,msg);
if (unlikely (rc < 0))
return -1;
}
}
return 0;
}
| minrk/zeromq4-1 | src/proxy.cpp | C++ | lgpl-3.0 | 6,350 |
package fr.inserm.ihm;
public class WizardPanelNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -1947507532224487459L;
public WizardPanelNotFoundException() {
super();
}
} | Biobanques/biobanques-etl-app | src/main/java/fr/inserm/ihm/WizardPanelNotFoundException.java | Java | lgpl-3.0 | 236 |
#include <ladspam-jack-0/instrument.h>
#include <ladspam1.pb.h>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <string>
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "Missing filename parameter" << std::endl;
return EXIT_FAILURE;
}
ladspam_proto1::Instrument instrument_pb;
std::ifstream input_file(argv[1], std::ios::in | std::ios::binary);
if (false == input_file.good())
{
std::cout << "Failed to open input stream" << std::endl;
return EXIT_FAILURE;
}
if (false == instrument_pb.ParseFromIstream(&input_file))
{
std::cout << "Failed to parse instrument definition file" << std::endl;
return EXIT_FAILURE;
}
ladspam_jack::instrument instrument("synth", instrument_pb, 32);
std::cout << "type anything and press enter to quit..." << std::endl;
std::string line;
std::cin >> line;
}
| fps/ladspa.m.jack | instrument.cc | C++ | lgpl-3.0 | 866 |
package apps.database.dnr2i.rssfeedreader.model;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.ArrayList;
import apps.database.dnr2i.rssfeedreader.FeedSelectorActivity;
import apps.database.dnr2i.rssfeedreader.R;
/**
* Class Adpater to prepare Display
* Created by Alexandre DUCREUX on 21/01/2017.
*/
public class RSSAdapter extends RecyclerView.Adapter<ArticleViewHolder> implements DocumentConsumer{
private ArrayList<FeedItems> rssFI = new ArrayList<>();
private Document _document;
private Context context;
public RSSAdapter(ArrayList<FeedItems> rssFI, Context context) {
this.rssFI = rssFI;
this.context = context;
}
@Override
public int getItemCount(){
int recordNumber = rssFI.size();
Log.i("AD", "Nombre d'enregistrement en base : "+recordNumber);
return recordNumber;
}
@Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.rss_selected_feed_details, parent, false);
return new ArticleViewHolder(view);
}
@Override
public void onBindViewHolder(ArticleViewHolder holder, int position){
FeedItems feedItemsList = rssFI.get(position);
holder.getTitle().setText(feedItemsList.getTitle());
holder.getDescription().setText(feedItemsList.getDescription());
holder.getLink().setText(feedItemsList.getLink());
holder.getDate().setText(feedItemsList.getDate());
}
@Override
public void setXMLDocument(Document document, int feedId) {
_document = document;
ItemEntity item = new ItemEntity(this.context);
if (document.getElementsByTagName("item").getLength() > 0)
{
item.emptyItemsById(feedId);
}
for (int i=0; i<document.getElementsByTagName("item").getLength(); i++)
{
Element element = (Element) _document.getElementsByTagName("item").item(i);
String title = element.getElementsByTagName("title").item(0).getTextContent();
String description = element.getElementsByTagName("description").item(0).getTextContent();
String date = element.getElementsByTagName("pubDate").item(0).getTextContent();
String link = element.getElementsByTagName("link").item(0).getTextContent();
item.setItem(title,description,date,link,feedId);
Log.i("valeur de title"," title = " +title);
}
notifyDataSetChanged();
Log.i("FIN","FIN");
}
}
| alimux/RssFeedReader | app/src/main/java/apps/database/dnr2i/rssfeedreader/model/RSSAdapter.java | Java | lgpl-3.0 | 2,847 |
# -*- coding: utf-8 -*-
shared_examples "a parameter type with 'in' validation" do |options|
test_route = options[:test_route]
in_key = options[:in_key]
in_val = options[:in_value]
fail_value = options[:fail_value]
describe "in (#{in_val.inspect})" do
context "with a value present the array provided" do
in_val.each { |allowed_value|
it "allows the value (#{allowed_value.inspect}) to go through" do
get(test_route, in_key => allowed_value)
result = body[in_key.to_s]
expect(result).to eq allowed_value
end
}
end
context "with a value not present in the array (#{fail_value.inspect}) provided" do
it "fails with a 400 status" do
get(test_route, in_key => fail_value)
expect(status).to eq 400
end
end
end
end
| axsh/sinatra-browse | spec/shared_examples/in_validation.rb | Ruby | lgpl-3.0 | 838 |
/* Copyright 2010 - 2013 by Brian Uri!
This file is part of DDMSence.
This library is free software; you can redistribute it and/or modify
it under the terms of version 3.0 of the GNU Lesser General Public
License as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with DDMSence. If not, see <http://www.gnu.org/licenses/>.
You can contact the author at ddmsence@urizone.net. The DDMSence
home page is located at http://ddmsence.urizone.net/
*/
package buri.ddmsence.ddms.summary.tspi;
import nu.xom.Element;
import buri.ddmsence.AbstractBaseComponent;
import buri.ddmsence.AbstractTspiShape;
import buri.ddmsence.ddms.IBuilder;
import buri.ddmsence.ddms.InvalidDDMSException;
import buri.ddmsence.util.DDMSVersion;
import buri.ddmsence.util.Util;
/**
* An immutable implementation of tspi:Circle.
* <br /><br />
* {@ddms.versions 00001}
*
* <p>For the initial support of DDMS 5.0 TSPI shapes, the DDMSence component will only return the raw XML of
* a shape. The TSPI specification is incredibly complex and multi-layered, and it is unclear how much
* value full-fledged classes would have. As use cases refine and more organizations adopt DDMS 5.0, the components
* can be revisited to provide more value-add.</p>
*
* {@table.header History}
* None.
* {@table.footer}
* {@table.header Nested Elements}
* None.
* {@table.footer}
* {@table.header Attributes}
* {@child.info gml:id|1|00001}
* {@child.info <<i>srsAttributes</i>>|0..*|00001}
* {@table.footer}
* {@table.header Validation Rules}
* {@ddms.rule Component must not be used before the DDMS version in which it was introduced.|Error|11111}
* {@ddms.rule The qualified name of this element must be correct.|Error|11111}
* {@ddms.rule The srsName must exist.|Error|11111}
* {@ddms.rule The gml:id must exist, and must be a valid NCName.|Error|11111}
* {@ddms.rule If the gml:pos has an srsName, it must match the srsName of this Point.|Error|11111}
* {@ddms.rule Warnings from any SRS attributes are claimed by this component.|Warning|11111}
* <p>No additional validation is done on the TSPI shape at this time.</p>
* {@table.footer}
*
* @author Brian Uri!
* @since 2.2.0
*/
public final class Circle extends AbstractTspiShape {
/**
* Constructor for creating a component from a XOM Element
*
* @param element the XOM element representing this
* @throws InvalidDDMSException if any required information is missing or malformed
*/
public Circle(Element element) throws InvalidDDMSException {
super(element);
}
/**
* @see AbstractBaseComponent#validate()
*/
protected void validate() throws InvalidDDMSException {
Util.requireQName(getXOMElement(), getNamespace(), Circle.getName(getDDMSVersion()));
super.validate();
}
/**
* @see AbstractBaseComponent#getOutput(boolean, String, String)
*/
public String getOutput(boolean isHTML, String prefix, String suffix) {
String localPrefix = buildPrefix(prefix, "", suffix);
StringBuffer text = new StringBuffer();
text.append(buildOutput(isHTML, localPrefix + "shapeType", getName()));
return (text.toString());
}
/**
* Builder for the element name of this component, based on the version of DDMS used
*
* @param version the DDMSVersion
* @return an element name
*/
public static String getName(DDMSVersion version) {
Util.requireValue("version", version);
return ("Circle");
}
/**
* @see Object#equals(Object)
*/
public boolean equals(Object obj) {
if (!super.equals(obj) || !(obj instanceof Circle))
return (false);
return (true);
}
/**
* Builder for this DDMS component.
*
* @see IBuilder
* @author Brian Uri!
* @since 2.2.0
*/
public static class Builder extends AbstractTspiShape.Builder {
private static final long serialVersionUID = 7750664735441105296L;
/**
* Empty constructor
*/
public Builder() {
super();
}
/**
* Constructor which starts from an existing component.
*/
public Builder(Circle address) {
super(address);
}
/**
* @see IBuilder#commit()
*/
public Circle commit() throws InvalidDDMSException {
if (isEmpty())
return (null);
return (new Circle(commitXml()));
}
}
} | imintel/ddmsence | src/main/java/buri/ddmsence/ddms/summary/tspi/Circle.java | Java | lgpl-3.0 | 4,720 |
package commands.executes;
import agents.Agent;
import agents.Robot;
import agents.Speed;
import agents.Vacuum;
import commands.AgentCommand;
import commands.AgentCommandVisitor;
import commands.FieldCommand;
import commands.NoFieldCommandException;
import commands.transmits.ChangeDirectionTransmit;
import field.Direction;
public class ChangeDirectionExecute extends AgentCommand {
private Direction direction;
public ChangeDirectionExecute(ChangeDirectionTransmit parent) {
super(parent);
this.direction = parent.getDirection();
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
@Override
public FieldCommand getFieldCommand() throws NoFieldCommandException {
throw new NoFieldCommandException();
}
@Override
public void accept(AgentCommandVisitor modifier) {
modifier.visit(this);
}
@Override
public void visit(Robot element) {
visitCommon(element);
}
@Override
public void visit(Vacuum element) {
visitCommon(element);
}
private void visitCommon(Agent element) {
if (!canExecute) {
result.pushNormal("irvalt 1 " + element);
return;
}
Speed newSpeed = element.getSpeed();
newSpeed.setDirection(direction);
element.setSpeed(newSpeed);
result.pushNormal("irvalt 0 " + element + " " + direction);
}
}
| istvanszoke/softlab4 | src/main/commands/executes/ChangeDirectionExecute.java | Java | lgpl-3.0 | 1,517 |
#
# $originalId: parser.rb,v 1.8 2006/07/06 11:42:07 aamine Exp $
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# As a special exception, when this code is copied by Racc
# into a Racc output file, you may use that output file
# without restriction.
#
unless defined?(NotImplementedError)
NotImplementedError = NotImplementError
end
module Racc
class ParseError < StandardError; end
end
unless defined?(::ParseError)
ParseError = Racc::ParseError
end
module Racc
unless defined?(Racc_No_Extentions)
Racc_No_Extentions = false
end
class Parser
Racc_Runtime_Version = '1.4.5'
Racc_Runtime_Revision = '$originalRevision: 1.8 $'.split[1]
Racc_Runtime_Core_Version_R = '1.4.5'
Racc_Runtime_Core_Revision_R = '$originalRevision: 1.8 $'.split[1]
begin
require 'racc/cparse'
# Racc_Runtime_Core_Version_C = (defined in extention)
Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
unless new.respond_to?(:_racc_do_parse_c, true)
raise LoadError, 'old cparse.so'
end
if Racc_No_Extentions
raise LoadError, 'selecting ruby version of racc runtime core'
end
Racc_Main_Parsing_Routine = :_racc_do_parse_c
Racc_YY_Parse_Method = :_racc_yyparse_c
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
Racc_Runtime_Type = 'c'
rescue LoadError
Racc_Main_Parsing_Routine = :_racc_do_parse_rb
Racc_YY_Parse_Method = :_racc_yyparse_rb
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
Racc_Runtime_Type = 'ruby'
end
def Parser.racc_runtime_type
Racc_Runtime_Type
end
private
def _racc_setup
@yydebug = false unless self.class::Racc_debug_parser
@yydebug = false unless defined?(@yydebug)
if @yydebug
@racc_debug_out = $stderr unless defined?(@racc_debug_out)
@racc_debug_out ||= $stderr
end
arg = self.class::Racc_arg
arg[13] = true if arg.size < 14
arg
end
def _racc_init_sysvars
@racc_state = [0]
@racc_tstack = []
@racc_vstack = []
@racc_t = nil
@racc_val = nil
@racc_read_next = true
@racc_user_yyerror = false
@racc_error_status = 0
end
###
### do_parse
###
def do_parse
__send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
end
def next_token
raise NotImplementedError, "#{self.class}\#next_token is not defined"
end
def _racc_do_parse_rb(arg, in_debug)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
_racc_init_sysvars
tok = act = i = nil
nerr = 0
catch(:racc_end_parse) {
while true
if i = action_pointer[@racc_state[-1]]
if @racc_read_next
if @racc_t != 0 # not EOF
tok, @racc_val = next_token()
unless tok # EOF
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
racc_read_token(@racc_t, tok, @racc_val) if @yydebug
@racc_read_next = false
end
end
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
else
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
}
end
###
### yyparse
###
def yyparse(recv, mid)
__send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
end
def _racc_yyparse_rb(recv, mid, arg, c_debug)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
_racc_init_sysvars
tok = nil
act = nil
i = nil
nerr = 0
catch(:racc_end_parse) {
until i = action_pointer[@racc_state[-1]]
while act = _racc_evalact(action_default[@racc_state[-1]], arg)
;
end
end
recv.__send__(mid) do |tok, val|
unless tok
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
@racc_val = val
@racc_read_next = false
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
while not (i = action_pointer[@racc_state[-1]]) or
not @racc_read_next or
@racc_t == 0 # $
unless i and i += @racc_t and
i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
end
}
end
###
### common
###
def _racc_evalact(act, arg)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
nerr = 0 # tmp
if act > 0 and act < shift_n
#
# shift
#
if @racc_error_status > 0
@racc_error_status -= 1 unless @racc_t == 1 # error token
end
@racc_vstack.push @racc_val
@racc_state.push act
@racc_read_next = true
if @yydebug
@racc_tstack.push @racc_t
racc_shift @racc_t, @racc_tstack, @racc_vstack
end
elsif act < 0 and act > -reduce_n
#
# reduce
#
code = catch(:racc_jump) {
@racc_state.push _racc_do_reduce(arg, act)
false
}
if code
case code
when 1 # yyerror
@racc_user_yyerror = true # user_yyerror
return -reduce_n
when 2 # yyaccept
return shift_n
else
raise '[Racc Bug] unknown jump code'
end
end
elsif act == shift_n
#
# accept
#
racc_accept if @yydebug
throw :racc_end_parse, @racc_vstack[0]
elsif act == -reduce_n
#
# error
#
case @racc_error_status
when 0
unless arg[21] # user_yyerror
nerr += 1
on_error @racc_t, @racc_val, @racc_vstack
end
when 3
if @racc_t == 0 # is $
throw :racc_end_parse, nil
end
@racc_read_next = true
end
@racc_user_yyerror = false
@racc_error_status = 3
while true
if i = action_pointer[@racc_state[-1]]
i += 1 # error token
if i >= 0 and
(act = action_table[i]) and
action_check[i] == @racc_state[-1]
break
end
end
throw :racc_end_parse, nil if @racc_state.size <= 1
@racc_state.pop
@racc_vstack.pop
if @yydebug
@racc_tstack.pop
racc_e_pop @racc_state, @racc_tstack, @racc_vstack
end
end
return act
else
raise "[Racc Bug] unknown action #{act.inspect}"
end
racc_next_state(@racc_state[-1], @racc_state) if @yydebug
nil
end
def _racc_do_reduce(arg, act)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
state = @racc_state
vstack = @racc_vstack
tstack = @racc_tstack
i = act * -3
len = reduce_table[i]
reduce_to = reduce_table[i+1]
method_id = reduce_table[i+2]
void_array = []
tmp_t = tstack[-len, len] if @yydebug
tmp_v = vstack[-len, len]
tstack[-len, len] = void_array if @yydebug
vstack[-len, len] = void_array
state[-len, len] = void_array
# tstack must be updated AFTER method call
if use_result
vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
else
vstack.push __send__(method_id, tmp_v, vstack)
end
tstack.push reduce_to
racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
k1 = reduce_to - nt_base
if i = goto_pointer[k1]
i += state[-1]
if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
return curstate
end
end
goto_default[k1]
end
def on_error(t, val, vstack)
raise ParseError, sprintf("\nparse error on value %s (%s)",
val.inspect, token_to_str(t) || '?')
end
def yyerror
throw :racc_jump, 1
end
def yyaccept
throw :racc_jump, 2
end
def yyerrok
@racc_error_status = 0
end
#
# for debugging output
#
def racc_read_token(t, tok, val)
@racc_debug_out.print 'read '
@racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
@racc_debug_out.puts val.inspect
@racc_debug_out.puts
end
def racc_shift(tok, tstack, vstack)
@racc_debug_out.puts "shift #{racc_token2str tok}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_reduce(toks, sim, tstack, vstack)
out = @racc_debug_out
out.print 'reduce '
if toks.empty?
out.print ' <none>'
else
toks.each {|t| out.print ' ', racc_token2str(t) }
end
out.puts " --> #{racc_token2str(sim)}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_accept
@racc_debug_out.puts 'accept'
@racc_debug_out.puts
end
def racc_e_pop(state, tstack, vstack)
@racc_debug_out.puts 'error recovering mode: pop token'
racc_print_states state
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_next_state(curstate, state)
@racc_debug_out.puts "goto #{curstate}"
racc_print_states state
@racc_debug_out.puts
end
def racc_print_stacks(t, v)
out = @racc_debug_out
out.print ' ['
t.each_index do |i|
out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
end
out.puts ' ]'
end
def racc_print_states(s)
out = @racc_debug_out
out.print ' ['
s.each {|st| out.print ' ', st }
out.puts ' ]'
end
def racc_token2str(tok)
self.class::Racc_token_to_s_table[tok] or
raise "[Racc Bug] can't convert token #{tok} to string"
end
def token_to_str(t)
self.class::Racc_token_to_s_table[t]
end
end
end
| jmecosta/VSSonarQubeQualityEditorPlugin | MSBuild/Gallio/bin/DLR/libs/IronRuby/lib/ruby/1.8/racc/parser.rb | Ruby | lgpl-3.0 | 12,172 |
/*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* HepTag was originally written by Mark Hepple, this version contains
* modifications by Valentin Tablan and Niraj Aswani.
*
* $Id: Rule_PREVTAG.java 15333 2012-02-07 13:18:33Z ian_roberts $
*/
package hepple.postag.rules;
import hepple.postag.*;
/**
* Title: HepTag
* Description: Mark Hepple's POS tagger
* Copyright: Copyright (c) 2001
* Company: University of Sheffield
* @author Mark Hepple
* @version 1.0
*/
public class Rule_PREVTAG extends Rule {
public Rule_PREVTAG() {
}
public boolean checkContext(POSTagger tagger) {
return (tagger.lexBuff[2][0].equals(context[0]));
}
} | liuhongchao/GATE_Developer_7.0 | src/hepple/postag/rules/Rule_PREVTAG.java | Java | lgpl-3.0 | 1,057 |
/*
* Copyright (C) Mike Espig
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// DKTSTruncation.cpp: Implementierung der Klasse DKTSTruncation.
//
//////////////////////////////////////////////////////////////////////
#include "DKTSTruncation.hpp"
DKTSTruncation::DKTSTruncation(const LongInt& d, const LongInt& r, const LongInt& R, const LongInt& n)
{
(*this)
.allocateDataSpace(d, r, R, n)
.generateRandomExample(d, r, R, n)
.setDefaultParameter()
;
}
DKTSTruncation::DKTSTruncation(const IString& fileName, const LongInt& r)
{
DKTS A;
A.readDataFrom(fileName);
const LongInt R = A.k();
attr_indexSet = (LongIntPointer) new LongInt[R];
attr_values = (LongRealPointer) new LongReal[R];
(*this)
.setInputFileName(fileName)
.prepareInputData(A)
.setInitialGuestBiggestSum(r)
.setDefaultParameter()
;
}
DKTSTruncation::DKTSTruncation(const IString& fileName, const IString& coFileName, const IString& ortFileName, const LongInt& r)
{
attr_Z
.readDataFrom(ortFileName)
;
attr_a
.readDataFrom(coFileName)
;
const LongInt R = attr_a.k();
(*this)
.setOriginalRank(R)
;
attr_indexSet = (LongIntPointer) new LongInt[R];
attr_values = (LongRealPointer) new LongReal[R];
(*this)
.setInputFileName(fileName)
.sortIndexSet()
//.computeMainPart(1.0e-16)
.setInitialGuestBiggestSum(r)
.setDefaultParameter()
;
}
DKTSTruncation::DKTSTruncation(const DKTS& A, const LongInt& r)
{
const LongInt R = A.k();
attr_indexSet = (LongIntPointer) new LongInt[R];
attr_values = (LongRealPointer) new LongReal[R];
(*this)
.prepareInputData(A)
.sortIndexSet()
.setInitialGuestBiggestSum(r)
.setDefaultParameter()
;
}
DKTSTruncation::DKTSTruncation(const DKTS& a, const DKTS& A, const DKTS& Z, const LongInt& r)
{
attr_a = a;
attr_Z = Z;
const LongInt R = attr_a.k();
attr_indexSet = (LongIntPointer) new LongInt[R];
attr_values = (LongRealPointer) new LongReal[R];
(*this)
.sortIndexSet()
.setInitialGuestBiggestSum(r)
.setDefaultParameter()
;
}
DKTSTruncation::~DKTSTruncation()
{
(*this)
.deleteDataSpace()
;
}
DKTSTruncation& DKTSTruncation::setDefaultParameter()
{
ProtocolFormat pF;
pF
.setTablePosition("H")
.setMaxTableSize(25)
;
ProtocolProperties pP(pF);
pP
.setTopicString("R1 Updates")
.setTeXFileName("lastRunR1.tex")
;
attr_truncationLogR1.setProperties(pP);
return (*this);
}
DKTSDIterationInfo DKTSTruncation::bestR1Truncation(const LongInt& r, DKTS& a, DKTS& x, const LongReal& normD)
{
Random rGenerator;
decomposer()
.setPrintCout(false)
;
LongReal error = 1.0e20;
LongReal errorMin = error;
Timer time;
const LongInt d = a.d();
const LongInt n = a.n();
x.resize(d, 1, n);
DKTS x0(x);
DKTSDIterationInfo infoEntry;
time.startTiming();
const LongInt R = attr_a.k();
const LongInt mR = MIN(7+1, R);
LongInt index = 0;
LongInt max = 0;
LongInt maxR = 23;
LongInt quality = -1;
bool noOne = true;
DKTSDDataBlock dataBlock;
addBeginTrancationR1(r, attr_truncationLogR1);
cout << "Initial guess : ";
for(LongInt i=1; i<mR || max==maxR; i++)
{
cout << ".";
addTrancationR1(i, r, attr_truncationLogR1);
const LongInt rIndex = rGenerator.randomLongInt(R);
index = rIndex;
x0.copyFromTo(attr_a, -index, index, index);
const LongReal normX0 = frobeniusNorm(x0);
x0 *= (normD/normX0);
dataBlock.removeAllEntrys();
infoEntry = attr_decomposer.decompose(a, x0, normD, dataBlock);
attr_truncationLogR1.add(dataBlock);
error = infoEntry.error();
if(1.0 < error && noOne)
{
i--;
}
else
{
if(error < errorMin)
{
noOne = false;
x = x0;
errorMin = error;
quality = attr_decomposer.quality();
if(errorMin < 0.92)
{
i = mR;
}
}
}
}
LongReal sec = time.elapsedTimeSec();
cout << errorMin << ", (" << quality << "), " << sec << "." << endl << endl;
addEndTrancation(infoEntry, r, attr_truncationLogR1);
infoEntry.setCalculationTime(sec);
decomposer()
.setPrintCout(true)
;
return infoEntry;
}
/*
DKTSDIterationInfo DKTSTruncation::bestR1Truncation(const LongInt& r, DKTS& a, DKTS& x, const LongReal& normD)
{
decomposer()
.setPrintCout(false)
;
LongReal error = 1.0e20;
Timer time;
const LongInt d = a.d();
const LongInt R = a.k();
const LongInt n = a.n();
LongInt quality = -1;
x.resize(d, 1, n);
for(LongInt mu=0; mu<d; mu++)
{
DKTVector& v = x(0,mu);
for(LongInt i=0; i<R; i++)
{
v += a(i,mu);
}
v.normalized();
}
//x *= normD;
DKTSDIterationInfo infoEntry;
time.startTiming();
DKTSDDataBlock dataBlock;
addBeginTrancationR1(r, attr_truncationLogR1);
cout << "Initial guess : ";
addTrancationR1(1, r, attr_truncationLogR1);
dataBlock.removeAllEntrys();
infoEntry = attr_decomposer.decompose(a, x, normD, dataBlock);
attr_truncationLogR1.add(dataBlock);
error = infoEntry.error();
quality = attr_decomposer.quality();
LongReal sec = time.elapsedTimeSec();
cout << error << ", (" << quality << "), " << sec << "." << endl << endl;
addEndTrancation(infoEntry, r, attr_truncationLogR1);
infoEntry.setCalculationTime(sec);
decomposer()
.setPrintCout(true)
;
return infoEntry;
}
*/
DKTSDIterationInfo DKTSTruncation::truncate2(const LongInt& rT, DKTS& a, DKTS& x, const LongReal& normA)//, Protocol& protocol)
{
const LongInt d = a.d();
const LongInt R = a.k();
const LongInt n = a.n();
DKTSDIterationInfo infoEntry;
DKTSDDataBlock dataBlock;
infoEntry = bestR1Truncation(1, a, x, normA);
LongReal error = infoEntry.error();
DKTS x0(d, 1, n), residuum(d, R, n);
for(LongInt r=1; r<rT; r++)
{
residuum.setSumOf(1.0, a, -1.0, x);
bestR1Truncation(r, residuum, x0, normA*error);
DKTS xt(x);
x.setSumOf(1.0, xt, 1.0, x0);
x.reScaled();
decomposer()
.setPrintCout(false)
;
infoEntry = attr_decomposer.decompose(a, x, normA, dataBlock);
error = infoEntry.error();
}
decomposer()
.setPrintCout(true)
;
return infoEntry;
}
DKTSDIterationInfo DKTSTruncation::startTruncation(DKTS& a, DKTS& x, const LongReal& normA)
{
DKTSDIterationInfo infoEntry;
Timer time;
DKTSDDataBlock dataBlock;
time.startTiming();
infoEntry = attr_decomposer.decompose(a, x, normA, dataBlock);
LongReal sec = time.elapsedTimeSec();
if(attr_decomposer.printCout())
{
cout << "Time [sec] = " << sec << endl;
}
infoEntry.setCalculationTime(sec);
addDataBlock(dataBlock, infoEntry, x.k(), attr_truncationLog);
return infoEntry;
}
DKTSDIterationInfo DKTSTruncation::truncate()
{
if(attr_decomposer.printCout())
{
writeParameter(cout);
}
return startTruncation(attr_a, attr_x, normA());
}
DKTSTruncation& DKTSTruncation::writeSolutionTo(const IString& fileName)
{
DKTS X;
X
.regeneratedBy(attr_x, attr_Z)
.reScaled()
.writeDataTo(fileName)
;
return (*this);
}
DKTSTruncation& DKTSTruncation::allocateDataSpace(const LongInt& d, const LongInt& r, const LongInt& R, const LongInt& n)
{
attr_indexSet = (LongIntPointer) new LongInt [R];
attr_values = (LongRealPointer) new LongReal[R];
attr_Z.resize(d, R, n);
attr_a.resize(d, R, R);
attr_x.resize(d, r, R);
return (*this);
}
DKTSTruncation& DKTSTruncation::deleteDataSpace()
{
delete [] attr_indexSet;
delete [] attr_values;
return (*this);
}
DKTSTruncation& DKTSTruncation::resize(const LongInt& d, const LongInt& r, const LongInt& R, const LongInt& n)
{
const LongReal d1 = attr_a.d();
const LongReal R1 = attr_a.k();
const LongReal r1 = attr_x.k();
const LongReal n1 = attr_Z.n();
if(d1==d && r1==r && R1==R && n1==n)
{
attr_a.setNull();
attr_x.setNull();
attr_Z.setNull();
}
else
{
(*this)
.deleteDataSpace()
.allocateDataSpace(d, r, R, n)
;
}
return (*this);
}
DKTSTruncation& DKTSTruncation::prepareInputData(const DKTS& A)
{
(*this)
.prepareInputData(A, 1)
;
return (*this);
}
DKTSTruncation& DKTSTruncation::prepareInputData(const DKTS& A, const LongInt& r)
{
const LongInt d = A.d();
const LongInt R = A.k();
const LongInt n = A.n();
(*this)
.resize(d, r, R, n)
.setOriginalRank(R)
;
Timer time;
time.startTiming();
IString date(time.date());
attr_Z.setOrthogonal2(A);
attr_a.setCoefficientsSystemOf(A, attr_Z);
const LongReal sec = time.elapsedTimeSec();
(*this)
.setPreCalculationTime(sec)
.sortIndexSet()
//.computeMainPart(1.0e-16);
;
return (*this);
}
DKTSTruncation& DKTSTruncation::computeMainPart(const LongReal& eps)
{
const LongInt R = attr_a.k();
// compute the new Rank
LongReal normA = DKTSTruncation::normA();
LongReal epsA = eps*normA;
LongReal rest = attr_values[attr_indexSet[R-1]];
LongInt diff = 0;
LongInt i = R-2;
while(rest<epsA && 0<i)
{
rest += attr_values[attr_indexSet[i]];
diff++;
i--;
}
const LongInt rNew = R - diff;
if(0<rNew)
{
setOriginalRank(R);
LongIntPointer indexSet = (LongIntPointer) new LongInt [rNew];
LongRealPointer values = (LongRealPointer) new LongReal[rNew];
for(i=0; i<rNew; i++)
{
indexSet[i] = attr_indexSet[i];
values[i] = attr_values[i];
}
delete [] attr_indexSet;
delete [] attr_values;
attr_indexSet = (LongIntPointer) new LongInt [rNew];
attr_values = (LongRealPointer) new LongReal[rNew];
for(i=0; i<rNew; i++)
{
attr_indexSet[i] = i;
attr_values[i] = values[i];
}
DKTS a(attr_a);
const LongInt d = a.d();
attr_a.resize(d, rNew, a.n());
for(LongInt mu=0; mu<d; mu++)
{
for(i=0; i<rNew; i++)
{
attr_a(i, mu) = a(indexSet[i], mu);
}
}
delete [] indexSet;
delete [] values;
}
return (*this);
}
DKTSTruncation& DKTSTruncation::prepareInputData(const DKTS& A, const DKTS& X)
{
const LongInt d = A.d();
const LongInt R = A.k();
const LongInt r = X.k();
const LongInt n = A.n();
(*this)
.resize(d, r, R, n)
;
Timer time;
time.startTiming();
IString date(time.date());
attr_Z.setOrthogonal2(A);
attr_a.setCoefficientsSystemOf(A, attr_Z);
attr_x.setCoefficientsSystemOf(X, attr_Z);
attr_x.reScaled();
const LongReal sec = time.elapsedTimeSec();
(*this)
.sortIndexSet()
.setPreCalculationTime(sec)
//.computeMainPart(1.0e-16);
;
return (*this);
}
DKTSTruncation& DKTSTruncation::generateRandomExample(const LongInt& d, const LongInt& r, const LongInt& R, const LongInt& n, const LongReal& eps)
{
DKTS A(d, R, n);
A
.setRand()
.scale(eps)
;
(*this)
.prepareInputData(A, r)
.setInitialGuestBiggestSum(r)
;
return (*this);
}
DKTSTruncation& DKTSTruncation::writePreComputationDataTo (const IString& fileNameCt, const IString& fileNameOb)
{
(*this)
.writeCoefficientSystemTo(fileNameCt)
.writeOrthogonalBasisTo(fileNameOb)
;
return (*this);
}
DKTSTruncation& DKTSTruncation::resizeInitialGuest(const LongInt& d, const LongInt& r, const LongInt& R, const LongInt& n)
{
const LongInt rank = MIN(r, R);
attr_x.resize(d, rank, n);
return (*this);
}
DKTSTruncation& DKTSTruncation::writeCoefficientSystemTo(const IString& fileName)
{
attr_a.writeDataTo(fileName);
return (*this);
}
DKTSTruncation& DKTSTruncation::writeOrthogonalBasisTo(const IString& fileName)
{
attr_Z.writeDataTo(fileName);
return (*this);
}
DKTSTruncation& DKTSTruncation::setInitialGuestBiggestSum(const LongInt& r)
{
resizeInitialGuest(attr_a.d(), r, attr_a.k(), attr_a.n());
const LongInt k = MIN(attr_x.k(), attr_a.k());
const LongInt d = attr_x.d();
for(LongInt j=0; j<k; j++)
{
const LongInt index = attr_indexSet[j];
for(LongInt mu=0; mu<d; mu++)
{
attr_x(j,mu) = attr_a(index,mu);
}
}
attr_x.reScaled();
return (*this);
}
DKTSTruncation& DKTSTruncation::readInitialGuestFrom(const IString& fileName)
{
DKTS X;
X.readDataFrom(fileName);
X.writeIndexSet(cout);
attr_x.setCoefficientsSystemOf(X, attr_Z);
attr_x.reScaled();
return (*this);
}
DKTSTruncation& DKTSTruncation::sortIndexSet()
{
const LongInt R = attr_a.k();
const LongReal normA = frobeniusNorm(attr_a);
(*this)
.setNormA(normA)
;
for(LongInt i=0; i<R; i++)
{
attr_values[i] = attr_a.frobeniusNormOfSummand(i);
attr_indexSet[i] = i;
}
quickSort(0, R-1, attr_values);
return (*this);
}
LongInt DKTSTruncation::partition(LongInt low, LongInt high, LongRealPointer f)
{
LongInt i,j;
LongReal pivot = f[attr_indexSet[low]];
i = low;
for(j=low+1; j<=high; j++)
{
if (pivot<=f[attr_indexSet[j]])
{
i++;
swapIndex(i, j);
}
}
swapIndex(i, low);
return i;
}
DKTSTruncation& DKTSTruncation::quickSort(LongInt low, LongInt high, LongRealPointer f)
{
LongInt m = 0;
if (low < high)
{
m = partition(low, high, f);
quickSort(low, m-1, f);
quickSort(m+1, high, f);
}
return (*this);
}
DKTSTruncation& DKTSTruncation::swapIndex (const LongInt& i, const LongInt& j)
{
LongInt& a_i = attr_indexSet[i];
LongInt& a_j = attr_indexSet[j];
const LongInt temp = a_i;
a_i = a_j;
a_j = temp;
return (*this);
}
bool DKTSTruncation::writeParameter(ostream& s) const
{
bool value = true;
const LongInt d = attr_x.d();
const LongInt k = attr_x.k();
const LongInt m = attr_x.n();
const LongInt l = originalRank();
const LongInt n = attr_Z.n();
s << "d = " << d << endl;
s << "R = " << l << endl;
s << "r = " << k << endl;
s << "N = " << n << endl;
s << "m = " << m << endl;
s << setprecision(2);
s << "Data Storage Memory = " << setw(4) << (LongReal)( (2*d*l*n + d*k*n + d*k*l + d*l*l)*sizeof(LongReal))/(LongReal)1048576 << " MByte" << endl;
return value;
}
DescriptionData DKTSTruncation::parameterDescription() const
{
DescriptionData dD;
const LongInt d = attr_x.d();
const LongInt k = attr_x.k();
const LongInt m = attr_x.n();
const LongInt l = attr_a.k();
const LongInt n = attr_Z.n();
dD.addString (IString("d ") + IString("$ = ") + IString(d) + IString("$,") + IString("\\hspace{15pt}")
+ IString("R ") + IString("$ = ") + IString(l) + IString("$,") + IString("\\hspace{15pt}")
+ IString("r ") + IString("$ = ") + IString(k) + IString("$,") + IString("\\hspace{15pt}")
+ IString("N ") + IString("$ = ") + IString(n) + IString("$,") + IString("\\hspace{15pt}")
+ IString("m ") + IString("$ = ") + IString(m) + IString("$"));
dD.addString ("");
return dD;
}
bool DKTSTruncation::writeNormsOfA(DescriptionData& dDIn) const
{
const LongInt R = attr_a.k();
for(LongInt i=0; i<R; i++)
{
dDIn.addString (IString(attr_indexSet[i]) + IString(" : ")
+ IString(attr_a.frobeniusNormOfSummand(attr_indexSet[i]))
+ IString("\\\\"));
}
return true;
}
bool DKTSTruncation::writeNormsOfA(ostream& s) const
{
const LongInt R = attr_a.k();
for(LongInt i=0; i<R; i++)
{
s << setw(5) << attr_indexSet[i] << " : " << attr_a.frobeniusNormOfSummand(attr_indexSet[i]) << endl;
}
return true;
}
DKTSTruncation& DKTSTruncation::addInputTensorInformation(const IString& date, Protocol& truncationLog)
{
const LongInt d = attr_a.d();
const LongInt R = attr_a.k();
const LongInt l = attr_a.n();
const LongInt k = attr_x.k();
const LongInt n = attr_Z.n();
const LongInt oR = originalRank();
DescriptionData dD;
dD.addString(IString("\\chapter{Input Tensor Sum Information}"));
dD.addString(IString("Date : ") + IString(date) + IString("\\\\"));
// toDo kein _ im FileName
dD.addString(IString("Reading Initial-Tensor from : ") + IString("$") + IString("tensor\\_input.ten") + IString("$"));
dD.addString(IString(""));
dD.addString(IString("Time for Data Precalculation [sec.]") + IString("$\\ =\\ ") + IString(preCalculationTime()) + IString("$"));
dD.addString(IString(""));
dD.addString( IString("$\\|A\\| = $") + IString(normA()));
dD.addString("");
dD.addString (IString("d ") + IString("$ = ") + IString(d) + IString(",$") + IString("\\hspace{15pt}")
+ IString("R ") + IString("$ = ") + IString(R) + IString(",$") + IString("\\hspace{15pt}")
+ IString("oR ") + IString("$ = ") + IString(oR) + IString(",$") + IString("\\hspace{15pt}")
+ IString("n ") + IString("$ = ") + IString(n) + IString("$"));
dD.addString("");
dD.addString( IString("Data\\ Storage\\ Memory\\ ") + IString("$\\ =\\ ")
+ IString((LongReal)( (2*d*l*n + d*k*n + d*k*l + d*l*l)*sizeof(LongReal))/(LongReal)1048576)
+ IString("$") + IString("\\ MByte"));
dD.addString("");
dD.addString(IString("$i:\\|A_i\\|$") + IString("\\\\"));
(*this)
.writeNormsOfA(dD)
;
dD.addString(IString(""));
dD.addString(IString("$i:\\|A_i\\|$") + IString("\\\\"));
attr_a.writeIndexSet(dD);
truncationLog.add(dD);
return (*this);
}
DKTSTruncation& DKTSTruncation::addBeginTrancation (const LongInt& r, Protocol& truncationLog)
{
DescriptionData dD;
dD.addString(IString("\\chapter{Best Rank ") + IString(r) + IString(" Truncation}"));
truncationLog.add(dD);
return (*this);
}
DKTSTruncation& DKTSTruncation::addBeginTrancationR1(const LongInt& r, Protocol& truncationLog)
{
DescriptionData dD;
dD.addString(IString("\\chapter{Compute Initial Guest for Best ") + IString(r) + IString(" Truncation}"));
truncationLog.add(dD);
return (*this);
}
DKTSTruncation& DKTSTruncation::addTrancationR1(const LongInt& run ,const LongInt& rank, Protocol& truncationLog)
{
DescriptionData dD;
dD.addString (IString("\\section{$ ") + IString(run) + IString(" ^{st}$ Test ")
+ IString("Best ") + IString(rank) + IString(" Truncation}"));
truncationLog.add(dD);
return (*this);
}
DKTSTruncation& DKTSTruncation::addDataBlock(const DKTSDDataBlock& dataBlock, const DKTSDIterationInfo& infoBlock,
const LongInt& k, Protocol& truncationLog)
{
addBeginTrancation(k, truncationLog);
truncationLog.add(dataBlock);
addEndTrancation(infoBlock, k, truncationLog);
return (*this);
}
DKTSTruncation& DKTSTruncation::addEndTrancation(const DKTSDIterationInfo& infoBlock, const LongInt& r, Protocol& truncationLog)
{
DescriptionData dD;
const LongInt nSte = infoBlock.numberOfNewtonSteps();
const LongReal dOld = infoBlock.startError();
const LongReal dNew = infoBlock.error();
const LongReal diff = dOld-dNew;
const LongReal time = infoBlock.calculationTime();
dD.addString(IString("Working Memory\\ \\ =\\ ") + IString("$\\ \\ ") + IString((LongReal)(attr_decomposer.memory()*sizeof(LongReal))/(LongReal)1048576) + IString("$ MByte"));
dD.addString("\\\\");
dD.addString(IString("Time\\ [sec]\\ =\\ ") + IString("$\\ \\ ") + IString(time) + IString("$"));
dD.addString("");
dD.addString( IString("$") + IString("\\frac{\\|A-X_0\\|}{\\|A\\|} = ") + IString(dOld) + IString("$") + IString("\\hspace{15pt}")
+ IString("$") + IString("\\frac{\\|A-X_{") + IString(nSte)
+ IString("}\\|}{\\|A\\|} = ") + IString(dNew) + IString("$") + IString("\\hspace{15pt}")
+ IString("\\\\"));
dD.addString( IString("diff ") + IString("$\\ =\\ ") + IString(diff) + IString("$") + IString("\\hspace{15pt}")
+ IString("diff[\\%] ") + IString("$\\ =\\ ") + IString(diff/dOld*100) + IString("$") + IString("\\%"));
dD.addString("");
dD.addMathString("i:\\|X_i\\|");
dD.addString("");
attr_x.writeIndexSet(dD);
//dD.addString(IString("Write Solution to\\ File\\ :\\ ") + IString("tensor\\_best\\_r=") + IString(r) + IString("\\_.ten"));
truncationLog.add(dD);
return (*this);
}
DKTSTruncation& DKTSTruncation::addInfoBlock(const DKTSDIterationInfoBlock& infoBlock, const LongReal& totalTime,
const LongReal& eps, const LongReal& epsN, const LongReal& preC)
{
const LongInt d = attr_a.d();
const LongInt R = originalRank();
const LongInt l = attr_a.n();
const LongInt k = attr_x.k();
const LongInt n = attr_Z.n();
DescriptionData dD, dE;
dD.addString(IString("\\chapter{Summary}"));
dE.addString (IString("d ") + IString("$ = ") + IString(d) + IString(",$") + IString("\\hspace{15pt}")
+ IString("R ") + IString("$ = ") + IString(R) + IString(",$") + IString("\\hspace{15pt}")
+ IString("n ") + IString("$ = ") + IString(n) + IString("$"));
dE.addString ("");
dE.addString (IString("eps ") + IString("$ = ") + IString(eps) + IString("$") + IString("\\\\"));
dE.addString (IString("minPrecision ") + IString("$ = ") + IString(preC) + IString("$") + IString("\\\\"));
dE.addString (IString("epsNewton ") + IString("$ = ") + IString(epsN) + IString("$") + IString("\\\\"));
dE.addString (IString("Total Time\\ [sec]\\ \\ ") + IString("$\\ =\\ ") + IString(totalTime) + IString("$"));
attr_truncationLog.add(dD);
attr_truncationLog.add(infoBlock);
attr_truncationLog.add(dE);
return (*this);
}
DKTSTruncation& DKTSTruncation::addInfoBlockR1(const DKTSDIterationInfoBlock& infoBlock)
{
DescriptionData dD;
dD.addString(IString("\\appendix"));
dD.addString(IString("\\chapter{Best Rank 1 Updates}"));
attr_truncationLog.add(dD);
attr_truncationLog.add(infoBlock);
return (*this);
}
| BackupTheBerlios/tensorcalculus | source/DKTS/KTSApp/DKTSTruncation.cpp | C++ | lgpl-3.0 | 25,260 |
#include "Wire.h"
PwmRPi::PwmRPi(unsigned char channel) {
this->channel = (channel & 0x01);
}
void PwmRPi::begin() {
pwm.address = PWM_ADDRESS;
Bcm2835::mapPeripheral(&pwm);
}
void PwmRPi::stop() {
Bcm2835::unmapPeripheral(&pwm);
}
PwmRPi Pwm0(0);
PwmRPi Pwm1(1);
| dalmirdasilva/RaspberryPwm | Pwm.cpp | C++ | lgpl-3.0 | 285 |
package org.jumbune.common.utils;
import static org.jumbune.common.utils.Constants.AT_OP;
import static org.jumbune.common.utils.Constants.COLON;
import static org.jumbune.common.utils.Constants.CPU_DUMP_FILE;
import static org.jumbune.common.utils.Constants.MEM_DUMP_FILE;
import static org.jumbune.common.utils.Constants.SPACE;
import static org.jumbune.common.utils.Constants.UNDERSCORE;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jumbune.common.beans.JumbuneInfo;
import org.jumbune.common.beans.cluster.Cluster;
import org.jumbune.common.beans.cluster.Workers;
import org.jumbune.common.job.JobConfig;
import org.jumbune.common.job.JumbuneRequest;
import org.jumbune.remoting.client.Remoter;
import org.jumbune.remoting.common.CommandType;
import org.jumbune.remoting.common.RemotingMethodConstants;
import org.jumbune.utils.exception.JumbuneException;
import org.jumbune.utils.exception.JumbuneRuntimeException;
/**
* This class provides methods to collect or distribute files from to/from
* master nodes.
*
*/
public class RemoteFileUtil {
/** The Constant LOGGER. */
private static final Logger LOGGER = LogManager
.getLogger(RemoteFileUtil.class);
/** The Constant SCP_R_CMD. */
private static final String SCP_R_CMD = "scp -r";
/** The Constant AGENT_HOME. */
private static final String AGENT_HOME = "AGENT_HOME";
/** The Constant MKDIR_P_CMD. */
private static final String MKDIR_P_CMD = "mkdir -p ";
private static final String RM_CMD = "rm";
/** The Constant TOP_DUMP_FILE. */
private static final String TOP_DUMP_FILE = "top.txt";
/**
* <p>
* Create a new instance of ClusterUtil.
* </p>
*/
public RemoteFileUtil() {
}
/**
* Copy remote log files
* @param masterLocation
* @param slaveDVLocation
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
@SuppressWarnings("unchecked")
public void copyRemoteLogFiles(JumbuneRequest jumbuneRequest, String slaveDVLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
String appHome = JumbuneInfo.getHome();
String relativePath = masterLocation.substring(appHome.length() - 1,
masterLocation.length());
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
// Creating local directories in Jumbune Working Dir
String mkdirCmd = MKDIR_P_CMD + masterLocation;
execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
LOGGER.debug("Starting to copy remote log files...");
for (String workerHost : workers.getHosts()) {
LOGGER.debug("Copy log files from: " + workerHost + ":" + slaveDVLocation);
String command ;
if(cluster.getAgents().getSshAuthKeysFile() != null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ slaveDVLocation + " " + AGENT_HOME + relativePath;}
else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ slaveDVLocation + " " + AGENT_HOME + relativePath;
}
CommandWritableBuilder copyBuilder = new CommandWritableBuilder(cluster, null);
copyBuilder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(copyBuilder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + string);
}
remoter.close();
}
/**
* Copy remote log files.
* @param masterLocation
* @param tempDirLocation
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
// TODO:
@SuppressWarnings("unchecked")
public void copyRemoteAjLogFiles(JumbuneRequest jumbuneRequest, String tempDirLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
String appHome = JumbuneInfo.getHome();
String relativePath = masterLocation.substring(appHome.length() - 1,
masterLocation.length());
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster, null);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
String mkdirCmd = MKDIR_P_CMD + masterLocation;
execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
for (String workerHost : workers.getHosts()) {
ConsoleLogUtil.LOGGER.debug("Copy log file from: [" + workerHost
+ "] to [" + tempDirLocation + "]");
LOGGER.debug("Copy log file from: [" + workerHost + "] to ["
+ tempDirLocation + "]");
StringBuilder lsSb = new StringBuilder()
.append("-")
.append(workerHost)
.append("-")
.append(tempDirLocation.substring(0,
tempDirLocation.indexOf("*.log*"))).append("-")
.append(relativePath);
builder.clear();
builder.addCommand(lsSb.toString(), false, null, CommandType.FS)
.setMethodToBeInvoked(RemotingMethodConstants.PROCESS_DB_OPT_STEPS);
remoter.fireCommandAndGetObjectResponse(builder
.getCommandWritable());
String command ;
if(cluster.getAgents().getSshAuthKeysFile()!=null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ tempDirLocation.substring(0,tempDirLocation.indexOf("*.log*")) + " " + AGENT_HOME + relativePath;
}else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ tempDirLocation.substring(0,tempDirLocation.indexOf("*.log*")) + " " + AGENT_HOME + relativePath;
}
builder.clear();
builder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + string);
}
for (String string : fileList) {
if (!string.contains("mrChain")) {
execute(new String[] { "unzip", string }, appHome + relativePath + "/");
execute(new String[] { "rm", string }, appHome + relativePath + "/");
}
}
}
/**
* Copy remote lib files to master.
*
* @param config
* the loader
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
public void copyRemoteLibFilesToMaster(
JumbuneRequest jumbuneRequest) throws IOException, InterruptedException {
JobConfig jobConfig = jumbuneRequest.getJobConfig();
String userLibLoc = jobConfig.getUserLibLocationAtMaster();
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String mkdir = MKDIR_P_CMD + userLibLoc;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(mkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
Workers workers= cluster.getWorkers();
if (workers.getHosts().isEmpty()) {
LOGGER.error("No Worker found in cluster");
return;
}
String workerHost = workers.getHosts().get(0);
List<String> fileList = ConfigurationUtil.getAllClasspathFiles(
jobConfig.getClasspathFolders(ClasspathUtil.USER_SUPPLIED),
jobConfig.getClasspathExcludes(ClasspathUtil.USER_SUPPLIED),
jobConfig.getClasspathFiles(ClasspathUtil.USER_SUPPLIED));
String hadoopFSUser = cluster.getHadoopUsers().getFsUser();
for (String file : fileList) {
String command = "scp " + workers.getUser() + "@" + workerHost + ":" + file
+ " " + hadoopFSUser + "@" + cluster.getNameNode()+ ":"
+ userLibLoc;
LOGGER.debug("Executing the cmd: " + command);
builder.clear();
builder.addCommand(command, false, null, CommandType.FS).populate(cluster, null).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
remoter.close();
}
/**
* Return rack id from IP.
*
* @param ip
* example: 192.168.169.52
* @return the rack id, example: 192.168.169
*/
public static String getRackId(String ip) {
int lastIndex = ip.lastIndexOf('.');
return ip.substring(0, lastIndex);
}
/**
* Return data centre id from IP.
*
* @param ip
* example: 192.168.169.52
* @return the data centre id, example: 192.168
*/
public static String getDataCentreId(String ip) {
String[] octats = ip.split("\\.");
if (octats.length > 0) {
return octats[0] + "." + octats[1];
} else {
return null;
}
}
/**
* Execute the given command.
*
* @param commands
* the commands
* @param directory
* the directory
*/
private void execute(String[] commands, String directory) {
ProcessBuilder processBuilder = new ProcessBuilder(commands);
if (directory != null && !directory.isEmpty()) {
processBuilder.directory(new File(directory));
} else {
processBuilder.directory(new File(JumbuneInfo.getHome()));
}
Process process = null;
InputStream inputStream = null;
BufferedReader bufferReader = null;
try {
process = processBuilder.start();
inputStream = process.getInputStream();
if (inputStream != null) {
bufferReader = new BufferedReader(new InputStreamReader(
inputStream));
String line = bufferReader.readLine();
while (line != null) {
line = bufferReader.readLine();
}
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
} finally {
try {
if (bufferReader != null) {
bufferReader.close();
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
}
}
}
/**
* Execute response list.
*
* @param commands
* the commands
* @param directory
* the directory
* @return the list
*/
public static List<String> executeResponseList(String[] commands,
String directory) {
List<String> responseList = new ArrayList<String>();
ProcessBuilder processBuilder = new ProcessBuilder(commands);
if (directory != null && !directory.isEmpty()) {
processBuilder.directory(new File(directory));
} else {
processBuilder.directory(new File(JumbuneInfo.getHome()));
}
Process process = null;
InputStream inputStream = null;
BufferedReader bufferReader = null;
try {
process = processBuilder.start();
inputStream = process.getInputStream();
if (inputStream != null) {
bufferReader = new BufferedReader(new InputStreamReader(
inputStream));
String line = bufferReader.readLine();
while (line != null) {
responseList.add(line);
line = bufferReader.readLine();
}
}
return responseList;
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
} finally {
try {
if (bufferReader != null) {
bufferReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
}
}
return responseList;
}
/**
* Copy System stats files from slaves to Jumbune deploy directory.
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
@SuppressWarnings("unchecked")
public void copyRemoteSysStatsFiles(Cluster cluster)
throws JumbuneException, IOException, InterruptedException {
// changing the namenode location to null as this method is not used currently.
String nameNodeLocation = null;
String appHome = JumbuneInfo.getHome();
String relativePath = nameNodeLocation.substring(appHome.length() - 1,
nameNodeLocation.length());
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
String mkdirCmd = MKDIR_P_CMD + nameNodeLocation;
execute(mkdirCmd.split(SPACE), appHome);
Workers workers = cluster.getWorkers();
String workerUser = workers.getUser();
// changing the worker location to null as this method is not used currently.
String workerLocation = null ;
for (String workerHost : workers.getHosts()) {
// copy cpu stats file from slaves
StringBuffer copyCpuFile = new StringBuffer(SCP_R_CMD);
copyCpuFile.append(SPACE).append(workerUser).append(AT_OP)
.append(workerHost).append(COLON).append(workerLocation)
.append(File.separator).append(CPU_DUMP_FILE)
.append(UNDERSCORE).append(workerHost).append(SPACE)
.append(AGENT_HOME).append(relativePath);
// copy memory stats file from slaves
StringBuffer copyMemFile = new StringBuffer(SCP_R_CMD);
copyMemFile.append(SPACE).append(workerUser).append(AT_OP)
.append(workerHost).append(COLON).append(workerLocation)
.append(File.separator).append(MEM_DUMP_FILE)
.append(UNDERSCORE).append(workerHost).append(SPACE)
.append(AGENT_HOME).append(relativePath);
String topDumpFile = workerLocation + File.separator
+ TOP_DUMP_FILE;
StringBuffer rmTopDumpFile = new StringBuffer(RM_CMD);
rmTopDumpFile.append(SPACE).append(topDumpFile);
StringBuffer rmCpuFile = new StringBuffer(RM_CMD);
rmCpuFile.append(SPACE).append(workerLocation)
.append(File.separator).append(CPU_DUMP_FILE)
.append(UNDERSCORE).append(workerHost);
// copy memory stats file from slaves
StringBuffer rmMemFile = new StringBuffer(SCP_R_CMD);
rmMemFile.append(SPACE).append(workerLocation)
.append(File.separator).append(MEM_DUMP_FILE)
.append(UNDERSCORE).append(workerHost);
builder.clear();
builder.addCommand(copyCpuFile.toString(), false, null,
CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES)
.addCommand(copyMemFile.toString(), false, null,
CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES)
.addCommand(rmCpuFile.toString(), false, null,
CommandType.FS)
.addCommand(rmMemFile.toString(), false, null,
CommandType.FS)
.addCommand(rmTopDumpFile.toString(), false, null,
CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + File.separator
+ string);
}
remoter.close();
}
/**
/**
* <p>
* This method collects all the log files from all the cluster nodes
* </p>
* .
* @param string
* @param slaveDVLocation
*
* @param logCollection
* log collection details
* @throws JumbuneException
* If any error occurred
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
public void copyLogFilesToMaster(JumbuneRequest jumbuneRequest, String slaveDVLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
copyRemoteLogFiles(jumbuneRequest,slaveDVLocation,masterLocation);
}
/**
* Gets the HDFS paths recursively. The output of this method depends on the output of command {@code hdfs dfs -ls -R }.
* Additionally, this parses and filters the output based on whether {@code includeDirs } flag is true or false, if true,
* this includes directory entries also in the resulting list.
*
* The output is a list of all the files/directories in the following format. </br></br>
*
* -rw-r--r-- 1 impadmin supergroup 2805600 2016-04-29 14:53 /Jumbune/Demo/input/PREPROCESSED/data1
*
* @param cluster the cluster
* @param parentPath the parent path
* @param includeDirs whether to include directory entries in resulting list
* @return the HDFS paths recursively
*/
public List<String> getHDFSPathsRecursively(Cluster cluster, String parentPath, boolean includeDirs) {
List<String> paths = null;
String response = fireLSRCommandOnHDFS(cluster, parentPath);
if (response != null && !response.isEmpty()) {
paths = new ArrayList<>();
String attrib[] = null;
try (BufferedReader br = new BufferedReader(new StringReader(response))) {
for (String line = br.readLine(); line != null; line = br.readLine()) {
attrib = line.split(Constants.SPACE_REGEX);
if (attrib.length == 8) {
if (includeDirs) {
paths.add(line);
} else {
if (!attrib[0].startsWith("d")) {
paths.add(line);
}
}
}
}
} catch (IOException e) {
LOGGER.error("unable to parse response of lsr command fired on HDFS for path " + parentPath);
}
}
return paths;
}
/**
* Fires {@code hdfs dfs -ls -R }command on hdfs on the given path.
*
* @param cluster the cluster
* @param parentPath the parent path
* @return the string
*/
private String fireLSRCommandOnHDFS(Cluster cluster, String parentPath) {
Remoter remoter = RemotingUtil.getRemoter(cluster, null);
StringBuilder command = new StringBuilder().append(Constants.HADOOP_HOME).append(Constants.BIN_HDFS)
.append(Constants.DFS_LSR).append(parentPath);
CommandWritableBuilder commandWritableBuilder = new CommandWritableBuilder(cluster);
commandWritableBuilder.addCommand(command.toString(), false, null, CommandType.HADOOP_FS);
return (String) remoter.fireCommandAndGetObjectResponse(commandWritableBuilder.getCommandWritable());
}
/**
* Copies the validation files to Jumbune home
*
* @param cluster the cluster
* @param jumbuneRequest the jumbune request
*/
public void copyLogFilesToMasterForDV(JumbuneRequest jumbuneRequest) {
JobConfig jobConfig = jumbuneRequest.getJobConfig();
String nameNodeLocation = jobConfig.getMasterConsolidatedDVLocation();
String appHome = JumbuneInfo.getHome();
Cluster cluster = jumbuneRequest.getCluster();
String relativePath = nameNodeLocation.substring(appHome.length() - 1,
nameNodeLocation.length());
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
// Creating local directories in Jumbune Working Dir
//String mkdirCmd = MKDIR_P_CMD + nameNodeLocation;
//execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
String workerLocation = jobConfig.getTempDirectory() + Constants.JOB_JARS_LOC + jobConfig.getFormattedJumbuneJobName()+ Constants.SLAVE_DV_LOC;
LOGGER.debug("Starting to copy remote log files...");
for (String workerHost : workers.getHosts()) {
LOGGER.debug("Copy log files from: " + workerHost + ":" + workerLocation);
String command ;
if(cluster.getAgents().getSshAuthKeysFile() != null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ workerLocation + " " + AGENT_HOME + relativePath;
}else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ workerLocation + " " + AGENT_HOME + relativePath;
}
CommandWritableBuilder copyBuilder = new CommandWritableBuilder(cluster, null);
copyBuilder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(copyBuilder.getCommandWritable());
}
try {
accumulateFileOutput(jumbuneRequest.getJobConfig().getHdfsInputPath(), jumbuneRequest.getJobConfig(), cluster);
} catch (IOException e) {
LOGGER.error(e);
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String file : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + file);
}
}
/**
* Accumulate file output into single file with sorted first thousand keys mantained.
*
* @param inputPath the input path
* @param jobConfig the job config
* @param cluster the cluster
* @throws IOException Signals that an I/O exception has occurred.
*/
public void accumulateFileOutput(String inputPath, JobConfig jobConfig, Cluster cluster) throws IOException {
String dataValidationDirPath = null;
StringBuilder stringBuilder = new StringBuilder();
StringBuilder DtPath = new StringBuilder();
List<String> dataViolationTypes = new ArrayList<>();
dataViolationTypes.add(Constants.NUM_OF_FIELDS_CHECK);
dataViolationTypes.add(Constants.USER_DEFINED_NULL_CHECK);
dataViolationTypes.add(Constants.USER_DEFINED_DATA_TYPE);
dataViolationTypes.add(Constants.USER_DEFINED_REGEX_CHECK);
CommandWritableBuilder builder = null;
Remoter remoter = null;
String filePaths = getInputPaths(inputPath, jobConfig, getLsrCommandResponse(inputPath, cluster));
String[] listofFilesFromHDFS = filePaths.split(Constants.COMMA);
for (String fileFromList : listofFilesFromHDFS) {
for (String violationType : dataViolationTypes) {
DtPath.append("AGENT_HOME").append(Constants.JOB_JARS_LOC).append(jobConfig.getFormattedJumbuneJobName()).append("dv/")
.append(violationType).append(Constants.FORWARD_SLASH);
stringBuilder.append("if ! [ `ls ").append(DtPath).append(" | wc -l` == 0 ]; then ").append("cat ").append(DtPath)
.append(fileFromList.replaceFirst("\\.", "").trim()).append("-*").append(" >> ").append(DtPath)
.append("a1 && sort -n -t \"|\" -k 1 ").append(DtPath).append("a1 -o ").
append(DtPath).append("a1 && head -n 1000 ").append(DtPath).append("a1 >> ").append(DtPath).append(fileFromList.replaceFirst("\\.", "").trim()).append("&& rm ")
.append(DtPath).append("a1 ")
.append(DtPath).append(fileFromList.replaceFirst("\\.", "").trim()).append("-*;")
.append(" else echo \"No files found hence exiting\"; fi");
dataValidationDirPath = stringBuilder.toString();
builder = new CommandWritableBuilder(cluster);
builder.addCommand(dataValidationDirPath.trim(), false, null, CommandType.FS).populate(cluster, cluster.getNameNode());
remoter = RemotingUtil.getRemoter(cluster);
remoter.fireAndForgetCommand(builder.getCommandWritable());
DtPath.delete(0, DtPath.length());
stringBuilder.delete(0, stringBuilder.length());
}
}
}
/**
* Gets the lsr command response containing all the files in the given path.
*
* @param hdfsFilePath the hdfs file path
* @param cluster the cluster
* @return the lsr command response
*/
private String getLsrCommandResponse(String hdfsFilePath,
Cluster cluster) {
Remoter remoter = RemotingUtil.getRemoter(cluster, null);
StringBuilder stringBuilder = new StringBuilder().append(Constants.HADOOP_HOME).append(Constants.BIN_HDFS).append(Constants.DFS_LSR).append(hdfsFilePath)
.append(" | sed 's/ */ /g' | cut -d\\ -f 1,8 --output-delimiter=',' | grep ^- | cut -d, -f2 ");
CommandWritableBuilder commandWritableBuilder = new CommandWritableBuilder(cluster, null);
commandWritableBuilder.addCommand(stringBuilder.toString(), false, null, CommandType.HADOOP_FS);
String commmandResponse = (String) remoter.fireCommandAndGetObjectResponse(commandWritableBuilder.getCommandWritable());
return commmandResponse;
}
/**
* Gets the input paths.
*
* @param hdfsFilePath the hdfs file path
* @param jobConfig the job config
* @param commandResponse the command response
* @return the input paths
* @throws IOException Signals that an I/O exception has occurred.
*/
private String getInputPaths(String hdfsFilePath,JobConfig jobConfig, String commandResponse) throws IOException{
List<String> listOfFiles = new ArrayList<String>();
String[] fileResponse = commandResponse.split(Constants.NEW_LINE);
String filePath = null ;
for (int i = 0; i < fileResponse.length; i++) {
String [] eachFileResponse = fileResponse[i].split("\\s+");
filePath = eachFileResponse[eachFileResponse.length-1];
if(filePath.contains(hdfsFilePath)){
filePath = filePath.replaceAll(File.separator, Constants.DOT);
listOfFiles.add(filePath);
}
}
return listOfFiles.toString().substring(1, listOfFiles.toString().length()-1);
}
}
| impetus-opensource/jumbune | common/src/main/java/org/jumbune/common/utils/RemoteFileUtil.java | Java | lgpl-3.0 | 27,308 |
/**
* GetAllUsersResponse.java
* Created by pgirard at 2:07:29 PM on Aug 19, 2010
* in the com.qagwaai.starmalaccamax.shared.services.action package
* for the StarMalaccamax project
*/
package com.qagwaai.starmalaccamax.client.service.action;
import java.util.ArrayList;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.qagwaai.starmalaccamax.shared.model.MarketDTO;
/**
* @author pgirard
*
*/
public final class GetAllMarketsResponse extends AbstractResponse implements IsSerializable {
/**
*
*/
private ArrayList<MarketDTO> markets;
/**
*
*/
private int totalMarkets;
/**
* @return the users
*/
public ArrayList<MarketDTO> getMarkets() {
return markets;
}
/**
* @return the totalMarkets
*/
public int getTotalMarkets() {
return totalMarkets;
}
/**
* @param markets
* the users to set
*/
public void setMarkets(final ArrayList<MarketDTO> markets) {
this.markets = markets;
}
/**
* @param totalMarkets
* the totalMarkets to set
*/
public void setTotalMarkets(final int totalMarkets) {
this.totalMarkets = totalMarkets;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "GetAllMarketsResponse [markets=" + markets + ", totalMarkets=" + totalMarkets + "]";
}
}
| qagwaai/StarMalaccamax | src/com/qagwaai/starmalaccamax/client/service/action/GetAllMarketsResponse.java | Java | lgpl-3.0 | 1,492 |
/*
* Copyright (c) 2005-2010 Substance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Substance Kirill Grouchnikov nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.internal.ui;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EnumSet;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicSpinnerUI;
import javax.swing.text.JTextComponent;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.SubstanceConstants.Side;
import org.pushingpixels.substance.internal.utils.*;
import org.pushingpixels.substance.internal.utils.SubstanceCoreUtilities.TextComponentAware;
import org.pushingpixels.substance.internal.utils.border.SubstanceTextComponentBorder;
import org.pushingpixels.substance.internal.utils.icon.TransitionAwareIcon;
/**
* UI for spinners in <b>Substance</b> look and feel.
*
* @author Kirill Grouchnikov
*/
public class SubstanceSpinnerUI extends BasicSpinnerUI {
/**
* Tracks changes to editor, removing the border as necessary.
*/
protected PropertyChangeListener substancePropertyChangeListener;
/**
* The next (increment) button.
*/
protected SubstanceSpinnerButton nextButton;
/**
* The previous (decrement) button.
*/
protected SubstanceSpinnerButton prevButton;
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#createUI(javax.swing.JComponent)
*/
public static ComponentUI createUI(JComponent comp) {
SubstanceCoreUtilities.testComponentCreationThreadingViolation(comp);
return new SubstanceSpinnerUI();
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
c.putClientProperty(SubstanceCoreUtilities.TEXT_COMPONENT_AWARE,
new TextComponentAware<JSpinner>() {
@Override
public JTextComponent getTextComponent(JSpinner t) {
JComponent editor = t.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
return ((JSpinner.DefaultEditor) editor)
.getTextField();
}
return null;
}
});
}
@Override
public void uninstallUI(JComponent c) {
c.putClientProperty(SubstanceCoreUtilities.TEXT_COMPONENT_AWARE, null);
super.uninstallUI(c);
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#createNextButton()
*/
@Override
protected Component createNextButton() {
this.nextButton = new SubstanceSpinnerButton(this.spinner,
SwingConstants.NORTH);
this.nextButton.setFont(this.spinner.getFont());
this.nextButton.setName("Spinner.nextButton");
Icon icon = new TransitionAwareIcon(this.nextButton,
new TransitionAwareIcon.Delegate() {
public Icon getColorSchemeIcon(SubstanceColorScheme scheme) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(nextButton);
return SubstanceImageCreator.getArrowIcon(
SubstanceSizeUtils
.getSpinnerArrowIconWidth(fontSize),
SubstanceSizeUtils
.getSpinnerArrowIconHeight(fontSize),
SubstanceSizeUtils
.getArrowStrokeWidth(fontSize),
SwingConstants.NORTH, scheme);
}
}, "substance.spinner.nextButton");
this.nextButton.setIcon(icon);
int spinnerButtonSize = SubstanceSizeUtils
.getScrollBarWidth(SubstanceSizeUtils
.getComponentFontSize(spinner));
this.nextButton.setPreferredSize(new Dimension(spinnerButtonSize,
spinnerButtonSize));
this.nextButton.setMinimumSize(new Dimension(5, 5));
this.nextButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_OPEN_SIDE_PROPERTY, EnumSet
.of(Side.BOTTOM));
this.nextButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, EnumSet
.of(Side.BOTTOM));
this.installNextButtonListeners(this.nextButton);
Color spinnerBg = this.spinner.getBackground();
if (!(spinnerBg instanceof UIResource)) {
this.nextButton.setBackground(spinnerBg);
}
return this.nextButton;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#createPreviousButton()
*/
@Override
protected Component createPreviousButton() {
this.prevButton = new SubstanceSpinnerButton(this.spinner,
SwingConstants.SOUTH);
this.prevButton.setFont(this.spinner.getFont());
this.prevButton.setName("Spinner.previousButton");
Icon icon = new TransitionAwareIcon(this.prevButton,
new TransitionAwareIcon.Delegate() {
public Icon getColorSchemeIcon(SubstanceColorScheme scheme) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(prevButton);
float spinnerArrowIconHeight = SubstanceSizeUtils
.getSpinnerArrowIconHeight(fontSize);
return SubstanceImageCreator.getArrowIcon(
SubstanceSizeUtils
.getSpinnerArrowIconWidth(fontSize),
spinnerArrowIconHeight, SubstanceSizeUtils
.getArrowStrokeWidth(fontSize),
SwingConstants.SOUTH, scheme);
}
}, "substance.spinner.prevButton");
this.prevButton.setIcon(icon);
int spinnerButtonSize = SubstanceSizeUtils
.getScrollBarWidth(SubstanceSizeUtils
.getComponentFontSize(this.prevButton));
this.prevButton.setPreferredSize(new Dimension(spinnerButtonSize,
spinnerButtonSize));
this.prevButton.setMinimumSize(new Dimension(5, 5));
this.prevButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_OPEN_SIDE_PROPERTY, EnumSet
.of(Side.TOP));
this.prevButton
.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY,
EnumSet.of(Side.TOP));
this.installPreviousButtonListeners(this.prevButton);
Color spinnerBg = this.spinner.getBackground();
if (!(spinnerBg instanceof UIResource)) {
this.nextButton.setBackground(spinnerBg);
}
return this.prevButton;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#installDefaults()
*/
@Override
protected void installDefaults() {
super.installDefaults();
JComponent editor = this.spinner.getEditor();
if ((editor != null) && (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor).getTextField();
if (tf != null) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(this.spinner);
Insets ins = SubstanceSizeUtils
.getSpinnerTextBorderInsets(fontSize);
tf.setBorder(new EmptyBorder(ins.top, ins.left, ins.bottom,
ins.right));
tf.setFont(spinner.getFont());
tf.setOpaque(false);
}
}
if (editor != null) {
editor.setOpaque(false);
}
Border b = this.spinner.getBorder();
if (b == null || b instanceof UIResource) {
this.spinner.setBorder(new SubstanceTextComponentBorder(
SubstanceSizeUtils
.getSpinnerBorderInsets(SubstanceSizeUtils
.getComponentFontSize(this.spinner))));
}
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#installListeners()
*/
@Override
protected void installListeners() {
super.installListeners();
this.substancePropertyChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("editor".equals(evt.getPropertyName())) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (spinner == null)
return;
JComponent editor = spinner.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor)
.getTextField();
if (tf != null) {
Insets ins = SubstanceSizeUtils
.getSpinnerTextBorderInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
tf.setBorder(new EmptyBorder(ins.top,
ins.left, ins.bottom, ins.right));
tf.revalidate();
}
}
}
});
}
if ("font".equals(evt.getPropertyName())) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (spinner != null) {
spinner.updateUI();
}
}
});
}
if ("background".equals(evt.getPropertyName())) {
JComponent editor = spinner.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor)
.getTextField();
if (tf != null) {
// Use SubstanceColorResource to distingish between
// color set by application and color set
// (propagated)
// by Substance. In the second case we can replace
// that color (even though it's not a UIResource).
Color tfBackground = tf.getBackground();
boolean canReplace = SubstanceCoreUtilities
.canReplaceChildBackgroundColor(tfBackground);
// fix for issue 387 - if spinner background
// is null, do nothing
if (spinner.getBackground() == null)
canReplace = false;
if (canReplace) {
tf.setBackground(new SubstanceColorResource(
spinner.getBackground()));
}
}
}
nextButton.setBackground(spinner.getBackground());
prevButton.setBackground(spinner.getBackground());
}
}
};
this.spinner
.addPropertyChangeListener(this.substancePropertyChangeListener);
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#uninstallListeners()
*/
@Override
protected void uninstallListeners() {
this.spinner
.removePropertyChangeListener(this.substancePropertyChangeListener);
this.substancePropertyChangeListener = null;
super.uninstallListeners();
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#paint(java.awt.Graphics,
* javax.swing.JComponent)
*/
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Graphics2D graphics = (Graphics2D) g.create();
int width = this.spinner.getWidth();
int height = this.spinner.getHeight();
int componentFontSize = SubstanceSizeUtils
.getComponentFontSize(this.spinner);
int borderDelta = (int) Math.floor(SubstanceSizeUtils
.getBorderStrokeWidth(componentFontSize));
Shape contour = SubstanceOutlineUtilities
.getBaseOutline(
width,
height,
Math.max(
0,
2.0f
* SubstanceSizeUtils
.getClassicButtonCornerRadius(componentFontSize)
- borderDelta), null, borderDelta);
graphics.setColor(SubstanceTextUtilities
.getTextBackgroundFillColor(this.spinner));
graphics.fill(contour);
graphics.dispose();
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.plaf.ComponentUI#getPreferredSize(javax.swing.JComponent)
*/
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension nextD = this.nextButton.getPreferredSize();
Dimension previousD = this.prevButton.getPreferredSize();
Dimension editorD = spinner.getEditor().getPreferredSize();
Dimension size = new Dimension(editorD.width, editorD.height);
size.width += Math.max(nextD.width, previousD.width);
Insets insets = this.spinner.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#update(java.awt.Graphics,
* javax.swing.JComponent)
*/
@Override
public void update(Graphics g, JComponent c) {
SubstanceTextUtilities.paintTextCompBackground(g, c);
this.paint(g, c);
}
@Override
protected LayoutManager createLayout() {
return new SpinnerLayoutManager();
}
/**
* Layout manager for the spinner.
*
* @author Kirill Grouchnikov
*/
protected class SpinnerLayoutManager implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension minimumLayoutSize(Container parent) {
return this.preferredLayoutSize(parent);
}
public Dimension preferredLayoutSize(Container parent) {
Dimension nextD = nextButton.getPreferredSize();
Dimension previousD = prevButton.getPreferredSize();
Dimension editorD = spinner.getEditor().getPreferredSize();
/*
* Force the editors height to be a multiple of 2
*/
editorD.height = ((editorD.height + 1) / 2) * 2;
Dimension size = new Dimension(editorD.width, editorD.height);
size.width += Math.max(nextD.width, previousD.width);
Insets insets = parent.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
Insets buttonInsets = SubstanceSizeUtils
.getSpinnerArrowButtonInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
size.width += (buttonInsets.left + buttonInsets.right);
return size;
}
public void layoutContainer(Container parent) {
int width = parent.getWidth();
int height = parent.getHeight();
Insets insets = parent.getInsets();
Dimension nextD = nextButton.getPreferredSize();
Dimension previousD = prevButton.getPreferredSize();
int buttonsWidth = Math.max(nextD.width, previousD.width);
int editorHeight = height - (insets.top + insets.bottom);
Insets buttonInsets = SubstanceSizeUtils
.getSpinnerArrowButtonInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
/*
* Deal with the spinner's componentOrientation property.
*/
int editorX, editorWidth, buttonsX;
if (parent.getComponentOrientation().isLeftToRight()) {
editorX = insets.left;
editorWidth = width - insets.left - buttonsWidth;
buttonsX = width - buttonsWidth;// - buttonInsets.right;
} else {
buttonsX = 0;// buttonInsets.left;
editorX = buttonsX + buttonsWidth;
editorWidth = width - editorX - insets.right;
}
int nextY = 0;// buttonInsets.top;
int nextHeight = (height / 2) + (height % 2) - nextY;
int previousY = 0 * buttonInsets.top + nextHeight;
int previousHeight = height - previousY;// - buttonInsets.bottom;
spinner.getEditor().setBounds(editorX, insets.top, editorWidth,
editorHeight);
nextButton.setBounds(buttonsX, nextY, buttonsWidth, nextHeight);
prevButton.setBounds(buttonsX, previousY, buttonsWidth,
previousHeight);
// System.out.println("next : " + nextButton.getBounds());
// System.out.println("prev : " + prevButton.getBounds());
}
}
}
| Depter/JRLib | NetbeansProject/jreserve-dummy/substance/src/main/java/org/pushingpixels/substance/internal/ui/SubstanceSpinnerUI.java | Java | lgpl-3.0 | 15,881 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace lwshostsvc
{
[RunInstaller(true)]
public partial class HostServiceInstaller : System.Configuration.Install.Installer
{
public HostServiceInstaller()
{
InitializeComponent();
}
/// <summary>
/// Installs or uninstalls the lwshost service
///
/// Source: https://groups.google.com/forum/#!topic/microsoft.public.dotnet.languages.csharp/TUXp6lRxy6Q
/// </summary>
/// <param name="undo">revert installation</param>
public static EHostServiceInstallState Install(bool undo = false)
{
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, new string[0]))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
return EHostServiceInstallState.UninstalCompleted;
}
else
{
inst.Install(state);
inst.Commit(state);
return EHostServiceInstallState.InstallAndCommitCompleted;
}
}
catch
{
try
{
inst.Rollback(state);
return EHostServiceInstallState.RollbackCompleted;
}
catch
{
return EHostServiceInstallState.RollbackFailed;
}
}
}
}
public enum EHostServiceInstallState : byte
{
InstallationFailed,
UninstalCompleted,
InstallAndCommitCompleted,
RollbackCompleted,
RollbackFailed
}
}
}
| rainerzufalldererste/LamestWebserver | LamestWebserver/lwshostsvc/HostServiceInstaller.cs | C# | lgpl-3.0 | 2,191 |
import os
import struct
from binascii import unhexlify
from shutil import copy as copyfile
from twisted.internet.defer import inlineCallbacks
from Tribler.Core.CacheDB.SqliteCacheDBHandler import TorrentDBHandler, MyPreferenceDBHandler, ChannelCastDBHandler
from Tribler.Core.CacheDB.sqlitecachedb import str2bin
from Tribler.Core.Category.Category import Category
from Tribler.Core.TorrentDef import TorrentDef
from Tribler.Core.leveldbstore import LevelDbStore
from Tribler.Test.Core.test_sqlitecachedbhandler import AbstractDB
from Tribler.Test.common import TESTS_DATA_DIR
S_TORRENT_PATH_BACKUP = os.path.join(TESTS_DATA_DIR, 'bak_single.torrent')
M_TORRENT_PATH_BACKUP = os.path.join(TESTS_DATA_DIR, 'bak_multiple.torrent')
class TestTorrentFullSessionDBHandler(AbstractDB):
def setUpPreSession(self):
super(TestTorrentFullSessionDBHandler, self).setUpPreSession()
self.config.set_megacache_enabled(True)
@inlineCallbacks
def setUp(self):
yield super(TestTorrentFullSessionDBHandler, self).setUp()
self.tdb = TorrentDBHandler(self.session)
def test_initialize(self):
self.tdb.initialize()
self.assertIsNone(self.tdb.mypref_db)
self.assertIsNone(self.tdb.votecast_db)
self.assertIsNone(self.tdb.channelcast_db)
class TestTorrentDBHandler(AbstractDB):
def addTorrent(self):
old_size = self.tdb.size()
old_tracker_size = self.tdb._db.size('TrackerInfo')
s_infohash = unhexlify('44865489ac16e2f34ea0cd3043cfd970cc24ec09')
m_infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98')
single_torrent_file_path = os.path.join(self.getStateDir(), 'single.torrent')
multiple_torrent_file_path = os.path.join(self.getStateDir(), 'multiple.torrent')
copyfile(S_TORRENT_PATH_BACKUP, single_torrent_file_path)
copyfile(M_TORRENT_PATH_BACKUP, multiple_torrent_file_path)
single_tdef = TorrentDef.load(single_torrent_file_path)
self.assertEqual(s_infohash, single_tdef.get_infohash())
multiple_tdef = TorrentDef.load(multiple_torrent_file_path)
self.assertEqual(m_infohash, multiple_tdef.get_infohash())
self.tdb.addExternalTorrent(single_tdef)
self.tdb.addExternalTorrent(multiple_tdef)
single_torrent_id = self.tdb.getTorrentID(s_infohash)
multiple_torrent_id = self.tdb.getTorrentID(m_infohash)
self.assertEqual(self.tdb.getInfohash(single_torrent_id), s_infohash)
single_name = 'Tribler_4.1.7_src.zip'
multiple_name = 'Tribler_4.1.7_src'
self.assertEqual(self.tdb.size(), old_size + 2)
new_tracker_table_size = self.tdb._db.size('TrackerInfo')
self.assertLess(old_tracker_size, new_tracker_table_size)
sname = self.tdb.getOne('name', torrent_id=single_torrent_id)
self.assertEqual(sname, single_name)
mname = self.tdb.getOne('name', torrent_id=multiple_torrent_id)
self.assertEqual(mname, multiple_name)
s_size = self.tdb.getOne('length', torrent_id=single_torrent_id)
self.assertEqual(s_size, 1583233)
m_size = self.tdb.getOne('length', torrent_id=multiple_torrent_id)
self.assertEqual(m_size, 5358560)
cat = self.tdb.getOne('category', torrent_id=multiple_torrent_id)
self.assertEqual(cat, u'xxx')
s_status = self.tdb.getOne('status', torrent_id=single_torrent_id)
self.assertEqual(s_status, u'unknown')
m_comment = self.tdb.getOne('comment', torrent_id=multiple_torrent_id)
comments = 'www.tribler.org'
self.assertGreater(m_comment.find(comments), -1)
comments = 'something not inside'
self.assertEqual(m_comment.find(comments), -1)
m_trackers = self.tdb.getTrackerListByInfohash(m_infohash)
self.assertEqual(len(m_trackers), 8)
self.assertIn('http://tpb.tracker.thepiratebay.org/announce', m_trackers)
s_torrent = self.tdb.getTorrent(s_infohash)
m_torrent = self.tdb.getTorrent(m_infohash)
self.assertEqual(s_torrent['name'], 'Tribler_4.1.7_src.zip')
self.assertEqual(m_torrent['name'], 'Tribler_4.1.7_src')
self.assertEqual(m_torrent['last_tracker_check'], 0)
def updateTorrent(self):
m_infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98')
self.tdb.updateTorrent(m_infohash, relevance=3.1415926, category=u'Videoclips',
status=u'good', seeder=123, leecher=321,
last_tracker_check=1234567,
other_key1='abcd', other_key2=123)
multiple_torrent_id = self.tdb.getTorrentID(m_infohash)
category = self.tdb.getOne('category', torrent_id=multiple_torrent_id)
self.assertEqual(category, u'Videoclips')
status = self.tdb.getOne('status', torrent_id=multiple_torrent_id)
self.assertEqual(status, u'good')
seeder = self.tdb.getOne('num_seeders', torrent_id=multiple_torrent_id)
self.assertEqual(seeder, 123)
leecher = self.tdb.getOne('num_leechers', torrent_id=multiple_torrent_id)
self.assertEqual(leecher, 321)
last_tracker_check = self.tdb.getOne('last_tracker_check', torrent_id=multiple_torrent_id)
self.assertEqual(last_tracker_check, 1234567)
def setUpPreSession(self):
super(TestTorrentDBHandler, self).setUpPreSession()
self.config.set_megacache_enabled(True)
self.config.set_torrent_store_enabled(True)
@inlineCallbacks
def setUp(self):
yield super(TestTorrentDBHandler, self).setUp()
from Tribler.Core.APIImplementation.LaunchManyCore import TriblerLaunchMany
from Tribler.Core.Modules.tracker_manager import TrackerManager
self.session.lm = TriblerLaunchMany()
self.session.lm.tracker_manager = TrackerManager(self.session)
self.tdb = TorrentDBHandler(self.session)
self.tdb.torrent_dir = TESTS_DATA_DIR
self.tdb.category = Category()
self.tdb.mypref_db = MyPreferenceDBHandler(self.session)
@inlineCallbacks
def tearDown(self):
self.tdb.mypref_db.close()
self.tdb.mypref_db = None
self.tdb.close()
self.tdb = None
yield super(TestTorrentDBHandler, self).tearDown()
def test_hasTorrent(self):
infohash_str = 'AA8cTG7ZuPsyblbRE7CyxsrKUCg='
infohash = str2bin(infohash_str)
self.assertTrue(self.tdb.hasTorrent(infohash))
self.assertTrue(self.tdb.hasTorrent(infohash)) # cache will trigger
fake_infohash = 'fake_infohash_100000'
self.assertFalse(self.tdb.hasTorrent(fake_infohash))
def test_get_infohash(self):
self.assertTrue(self.tdb.getInfohash(1))
self.assertFalse(self.tdb.getInfohash(1234567))
def test_add_update_torrent(self):
self.addTorrent()
self.updateTorrent()
def test_update_torrent_from_metainfo(self):
# Add torrent first
infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98')
# Only infohash is added to the database
self.tdb.addOrGetTorrentID(infohash)
# Then update the torrent with metainfo
metainfo = {'info': {'files': [{'path': ['Something.something.pdf'], 'length': 123456789},
{'path': ['Another-thing.jpg'], 'length': 100000000}],
'piece length': 2097152,
'name': '\xc3Something awesome (2015)',
'pieces': ''},
'seeders': 0, 'initial peers': [],
'leechers': 36, 'download_exists': False, 'nodes': []}
self.tdb.update_torrent_with_metainfo(infohash, metainfo)
# Check updates are correct
torrent_id = self.tdb.getTorrentID(infohash)
name = self.tdb.getOne('name', torrent_id=torrent_id)
self.assertEqual(name, u'\xc3Something awesome (2015)')
num_files = self.tdb.getOne('num_files', torrent_id=torrent_id)
self.assertEqual(num_files, 2)
length = self.tdb.getOne('length', torrent_id=torrent_id)
self.assertEqual(length, 223456789)
def test_add_external_torrent_no_def_existing(self):
infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=')
self.tdb.addExternalTorrentNoDef(infohash, "test torrent", [], [], 1234)
self.assertTrue(self.tdb.hasTorrent(infohash))
def test_add_external_torrent_no_def_no_files(self):
infohash = unhexlify('48865489ac16e2f34ea0cd3043cfd970cc24ec09')
self.tdb.addExternalTorrentNoDef(infohash, "test torrent", [], [], 1234)
self.assertFalse(self.tdb.hasTorrent(infohash))
def test_add_external_torrent_no_def_one_file(self):
infohash = unhexlify('49865489ac16e2f34ea0cd3043cfd970cc24ec09')
self.tdb.addExternalTorrentNoDef(infohash, "test torrent", [("file1", 42)],
['http://localhost/announce'], 1234)
self.assertTrue(self.tdb.getTorrentID(infohash))
def test_add_external_torrent_no_def_more_files(self):
infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09')
self.tdb.addExternalTorrentNoDef(infohash, "test torrent", [("file1", 42), ("file2", 43)],
[], 1234, extra_info={"seeder": 2, "leecher": 3})
self.assertTrue(self.tdb.getTorrentID(infohash))
def test_add_external_torrent_no_def_invalid(self):
infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09')
self.tdb.addExternalTorrentNoDef(infohash, "test torrent", [("file1", {}), ("file2", 43)],
[], 1234)
self.assertFalse(self.tdb.getTorrentID(infohash))
def test_add_get_torrent_id(self):
infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=')
self.assertEqual(self.tdb.addOrGetTorrentID(infohash), 1)
new_infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09')
self.assertEqual(self.tdb.addOrGetTorrentID(new_infohash), 4859)
def test_add_get_torrent_ids_return(self):
infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=')
new_infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09')
tids, inserted = self.tdb.addOrGetTorrentIDSReturn([infohash, new_infohash])
self.assertEqual(tids, [1, 4859])
self.assertEqual(len(inserted), 1)
def test_index_torrent_existing(self):
self.tdb._indexTorrent(1, "test", [])
def test_getCollectedTorrentHashes(self):
res = self.tdb.getNumberCollectedTorrents()
self.assertEqual(res, 4847)
def test_freeSpace(self):
# Manually set the torrent store because register is not called.
self.session.lm.torrent_store = LevelDbStore(self.session.config.get_torrent_store_dir())
old_res = self.tdb.getNumberCollectedTorrents()
self.tdb.freeSpace(20)
res = self.tdb.getNumberCollectedTorrents()
self.session.lm.torrent_store.close()
self.assertEqual(res, old_res-20)
def test_get_search_suggestions(self):
self.assertEqual(self.tdb.getSearchSuggestion(["content", "cont"]), ["content 1"])
def test_get_autocomplete_terms(self):
self.assertEqual(len(self.tdb.getAutoCompleteTerms("content", 100)), 0)
def test_get_recently_randomly_collected_torrents(self):
self.assertEqual(len(self.tdb.getRecentlyCollectedTorrents(limit=10)), 10)
self.assertEqual(len(self.tdb.getRandomlyCollectedTorrents(100000000, limit=10)), 3)
def test_get_recently_checked_torrents(self):
self.assertEqual(len(self.tdb.getRecentlyCheckedTorrents(limit=5)), 5)
def test_select_torrents_to_collect(self):
infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=')
self.assertEqual(len(self.tdb.select_torrents_to_collect(infohash)), 0)
def test_get_torrents_stats(self):
self.assertEqual(self.tdb.getTorrentsStats(), (4847, 6519179841442, 187195))
def test_get_library_torrents(self):
self.assertEqual(len(self.tdb.getLibraryTorrents(['infohash'])), 12)
def test_search_names_no_sort(self):
"""
Test whether the right amount of torrents are returned when searching for torrents in db
"""
columns = ['T.torrent_id', 'infohash', 'status', 'num_seeders']
self.tdb.channelcast_db = ChannelCastDBHandler(self.session)
self.assertEqual(len(self.tdb.searchNames(['content'], keys=columns, doSort=False)), 4849)
self.assertEqual(len(self.tdb.searchNames(['content', '1'], keys=columns, doSort=False)), 1)
def test_search_names_sort(self):
"""
Test whether the right amount of sorted torrents are returned when searching for torrents in db
"""
columns = ['T.torrent_id', 'infohash', 'status', 'num_seeders']
self.tdb.channelcast_db = ChannelCastDBHandler(self.session)
results = self.tdb.searchNames(['content'], keys=columns)
self.assertEqual(len(results), 4849)
self.assertEqual(results[0][3], 493785)
def test_search_local_torrents(self):
"""
Test the search procedure in the local database when searching for torrents
"""
results = self.tdb.search_in_local_torrents_db('content', ['infohash', 'num_seeders'])
self.assertEqual(len(results), 4849)
self.assertNotEqual(results[0][-1], 0.0) # Relevance score of result should not be zero
results = self.tdb.search_in_local_torrents_db('fdsafasfds', ['infohash'])
self.assertEqual(len(results), 0)
def test_rel_score_remote_torrent(self):
self.tdb.latest_matchinfo_torrent = struct.pack("I" * 12, *([1] * 12)), "torrent"
self.assertNotEqual(self.tdb.relevance_score_remote_torrent("my-torrent.iso"), 0.0)
| Captain-Coder/tribler | Tribler/Test/Core/test_sqlitecachedbhandler_torrents.py | Python | lgpl-3.0 | 13,903 |
package br.com.zalem.ymir.client.android.entity.data.openmobster.cursor;
import android.database.Cursor;
import br.com.zalem.ymir.client.android.entity.data.cursor.IEntityRecordCursor;
/**
* Base para cursores de dados baseados no OpenMobster.<br>
* Apenas engloba um {@link android.database.Cursor} e repassa para ele as funções básicas de um cursor, como mover-se, obter a contagem,
* fechar, etc.
*
* @see android.database.Cursor
*
* @author Thiago Gesser
*/
public abstract class AbstractMobileBeanCursor implements IEntityRecordCursor {
protected final Cursor dbCursor;
public AbstractMobileBeanCursor(Cursor dbCursor) {
this.dbCursor = dbCursor;
}
@Override
public int getCount() {
return dbCursor.getCount();
}
@Override
public int getPosition() {
return dbCursor.getPosition();
}
@Override
public boolean move(int offset) {
return dbCursor.move(offset);
}
@Override
public boolean moveToPosition(int position) {
return dbCursor.moveToPosition(position);
}
@Override
public boolean moveToFirst() {
return dbCursor.moveToFirst();
}
@Override
public boolean moveToLast() {
return dbCursor.moveToLast();
}
@Override
public boolean moveToNext() {
return dbCursor.moveToNext();
}
@Override
public boolean moveToPrevious() {
return dbCursor.moveToPrevious();
}
@Override
public boolean isFirst() {
return dbCursor.isFirst();
}
@Override
public boolean isLast() {
return dbCursor.isLast();
}
@Override
public boolean isBeforeFirst() {
return dbCursor.isBeforeFirst();
}
@Override
public boolean isAfterLast() {
return dbCursor.isAfterLast();
}
@Override
public void close() {
dbCursor.close();
}
@Override
public boolean isClosed() {
return dbCursor.isClosed();
}
}
| ZalemSoftware/Ymir | ymir.client-android.entity.data-openmobster/src/main/java/br/com/zalem/ymir/client/android/entity/data/openmobster/cursor/AbstractMobileBeanCursor.java | Java | lgpl-3.0 | 1,776 |
/**
* Copyright (C) 2015 Swift Navigation Inc.
* Contact: Joshua Gross <josh@swift-nav.com>
* This source is subject to the license found in the file 'LICENSE' which must
* be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var Readable = require('stream').Readable;
var dispatch = require(path.resolve(__dirname, '../sbp/')).dispatch;
var MsgPosLlh = require(path.resolve(__dirname, '../sbp/navigation')).MsgPosLlh;
var MsgVelEcef = require(path.resolve(__dirname, '../sbp/navigation')).MsgVelEcef;
var framedMessage = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94];
var corruptedMessageTooShort = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x12, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94];
var corruptedMessageTooLong = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x16, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94];
var corruptedMessageExtraPreamble = [0x55, 0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94];
describe('dispatcher', function () {
it('should read stream of bytes and dispatch callback for single framed message', function (done) {
var rs = new Readable();
rs.push(new Buffer(framedMessage));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
it('should read stream of bytes and dispatch callback for two framed message', function (done) {
var rs = new Readable();
rs.push(new Buffer(framedMessage));
rs.push(new Buffer(framedMessage));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 2) {
assert.equal(validMessages, 2);
done();
}
});
});
it('should read stream of bytes and dispatch callback for two framed message, with garbage in between', function (done) {
var rs = new Readable();
rs.push(new Buffer(framedMessage));
rs.push(new Buffer([0x54, 0x53, 0x00, 0x01]));
rs.push(new Buffer(framedMessage));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 2) {
assert.equal(validMessages, 2);
done();
}
});
});
it('should read stream of bytes and dispatch callback for three framed messages, with garbage before first message and last', function (done) {
var rs = new Readable();
rs.push(new Buffer(framedMessage.slice(2)));
rs.push(new Buffer(framedMessage));
rs.push(new Buffer(framedMessage.slice(1)));
rs.push(new Buffer(framedMessage));
rs.push(new Buffer(framedMessage.slice(3)));
rs.push(new Buffer(framedMessage));
rs.push(new Buffer(framedMessage.slice(4)));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 3) {
assert.equal(validMessages, 3);
done();
}
});
});
it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt message', function (done) {
var rs = new Readable();
rs.push(new Buffer(corruptedMessageTooShort));
rs.push(new Buffer(framedMessage));
rs.push(new Buffer(corruptedMessageTooLong));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt preamble', function (done) {
var rs = new Readable();
rs.push(new Buffer(corruptedMessageExtraPreamble));
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
it('should whitelist messages properly - no whitelist', function (done) {
var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64');
var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64');
var rs = new Readable();
rs.push(msgLlhPayload);
rs.push(msgVelEcefPayload);
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, function (err, framedMessage) {
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 2) {
assert.equal(validMessages, 2);
done();
}
});
});
it('should whitelist messages properly - array whitelist', function (done) {
var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64');
var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64');
var rs = new Readable();
rs.push(msgVelEcefPayload);
rs.push(msgLlhPayload);
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, [MsgPosLlh.prototype.msg_type], function (err, framedMessage) {
assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type);
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
it('should whitelist messages properly - mask whitelist', function (done) {
var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64');
var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64');
var rs = new Readable();
rs.push(msgVelEcefPayload);
rs.push(msgLlhPayload);
rs.push(null);
var callbacks = 0;
var validMessages = 0;
dispatch(rs, ~MsgVelEcef.prototype.msg_type, function (err, framedMessage) {
assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type);
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
it('should whitelist messages properly - function whitelist', function (done) {
var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64');
var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64');
var rs = new Readable();
rs.push(msgVelEcefPayload);
rs.push(msgLlhPayload);
rs.push(null);
var callbacks = 0;
var validMessages = 0;
var whitelist = function (msgType) {
return msgType === MsgVelEcef.prototype.msg_type;
};
dispatch(rs, whitelist, function (err, framedMessage) {
assert.equal(framedMessage.msg_type, MsgVelEcef.prototype.msg_type);
if (framedMessage && framedMessage.fields && framedMessage.fields.tow) {
validMessages++;
}
if ((++callbacks) === 1) {
assert.equal(validMessages, 1);
done();
}
});
});
});
| swift-nav/libsbp | javascript/tests/test_dispatch.js | JavaScript | lgpl-3.0 | 8,674 |
import br.com.etyllica.EtyllicaFrame;
import br.com.etyllica.core.context.Application;
import br.com.runaway.menu.MainMenu;
public class TombRunaway extends EtyllicaFrame {
private static final long serialVersionUID = 1L;
public TombRunaway() {
super(800, 600);
}
public static void main(String[] args){
TombRunaway map = new TombRunaway();
map.init();
}
public Application startApplication() {
initialSetup("../");
/*JoystickLoader.getInstance().start(1);
new Thread(JoystickLoader.getInstance()).start();*/
return new MainMenu(w, h);
}
}
| yuripourre/runaway | src/main/java/TombRunaway.java | Java | lgpl-3.0 | 578 |
package com.mingweisamuel.zyra.matchV4;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.lang.Object;
import java.lang.Override;
/**
* ParticipantStats.<br><br>
*
* This class was automatically generated from the <a href="http://www.mingweisamuel.com/riotapi-schema/openapi-3.0.0.min.json">Riot API reference</a>. */
public class ParticipantStats implements Serializable {
public final int altarsCaptured;
public final int altarsNeutralized;
public final int assists;
public final int champLevel;
public final int combatPlayerScore;
public final long damageDealtToObjectives;
public final long damageDealtToTurrets;
public final long damageSelfMitigated;
public final int deaths;
public final int doubleKills;
public final boolean firstBloodAssist;
public final boolean firstBloodKill;
public final boolean firstInhibitorAssist;
public final boolean firstInhibitorKill;
public final boolean firstTowerAssist;
public final boolean firstTowerKill;
public final int goldEarned;
public final int goldSpent;
public final int inhibitorKills;
public final int item0;
public final int item1;
public final int item2;
public final int item3;
public final int item4;
public final int item5;
public final int item6;
public final int killingSprees;
public final int kills;
public final int largestCriticalStrike;
public final int largestKillingSpree;
public final int largestMultiKill;
public final int longestTimeSpentLiving;
public final long magicDamageDealt;
public final long magicDamageDealtToChampions;
public final long magicalDamageTaken;
public final int neutralMinionsKilled;
public final int neutralMinionsKilledEnemyJungle;
public final int neutralMinionsKilledTeamJungle;
public final int nodeCapture;
public final int nodeCaptureAssist;
public final int nodeNeutralize;
public final int nodeNeutralizeAssist;
public final int objectivePlayerScore;
public final int participantId;
public final int pentaKills;
/**
* Primary path keystone rune. */
public final int perk0;
/**
* Post game rune stats. */
public final int perk0Var1;
/**
* Post game rune stats. */
public final int perk0Var2;
/**
* Post game rune stats. */
public final int perk0Var3;
/**
* Primary path rune. */
public final int perk1;
/**
* Post game rune stats. */
public final int perk1Var1;
/**
* Post game rune stats. */
public final int perk1Var2;
/**
* Post game rune stats. */
public final int perk1Var3;
/**
* Primary path rune. */
public final int perk2;
/**
* Post game rune stats. */
public final int perk2Var1;
/**
* Post game rune stats. */
public final int perk2Var2;
/**
* Post game rune stats. */
public final int perk2Var3;
/**
* Primary path rune. */
public final int perk3;
/**
* Post game rune stats. */
public final int perk3Var1;
/**
* Post game rune stats. */
public final int perk3Var2;
/**
* Post game rune stats. */
public final int perk3Var3;
/**
* Secondary path rune. */
public final int perk4;
/**
* Post game rune stats. */
public final int perk4Var1;
/**
* Post game rune stats. */
public final int perk4Var2;
/**
* Post game rune stats. */
public final int perk4Var3;
/**
* Secondary path rune. */
public final int perk5;
/**
* Post game rune stats. */
public final int perk5Var1;
/**
* Post game rune stats. */
public final int perk5Var2;
/**
* Post game rune stats. */
public final int perk5Var3;
/**
* Primary rune path */
public final int perkPrimaryStyle;
/**
* Secondary rune path */
public final int perkSubStyle;
public final long physicalDamageDealt;
public final long physicalDamageDealtToChampions;
public final long physicalDamageTaken;
public final int playerScore0;
public final int playerScore1;
public final int playerScore2;
public final int playerScore3;
public final int playerScore4;
public final int playerScore5;
public final int playerScore6;
public final int playerScore7;
public final int playerScore8;
public final int playerScore9;
public final int quadraKills;
public final int sightWardsBoughtInGame;
public final int teamObjective;
public final long timeCCingOthers;
public final long totalDamageDealt;
public final long totalDamageDealtToChampions;
public final long totalDamageTaken;
public final long totalHeal;
public final int totalMinionsKilled;
public final int totalPlayerScore;
public final int totalScoreRank;
public final int totalTimeCrowdControlDealt;
public final int totalUnitsHealed;
public final int tripleKills;
public final long trueDamageDealt;
public final long trueDamageDealtToChampions;
public final long trueDamageTaken;
public final int turretKills;
public final int unrealKills;
public final long visionScore;
public final int visionWardsBoughtInGame;
public final int wardsKilled;
public final int wardsPlaced;
public final boolean win;
public ParticipantStats(final int altarsCaptured, final int altarsNeutralized, final int assists,
final int champLevel, final int combatPlayerScore, final long damageDealtToObjectives,
final long damageDealtToTurrets, final long damageSelfMitigated, final int deaths,
final int doubleKills, final boolean firstBloodAssist, final boolean firstBloodKill,
final boolean firstInhibitorAssist, final boolean firstInhibitorKill,
final boolean firstTowerAssist, final boolean firstTowerKill, final int goldEarned,
final int goldSpent, final int inhibitorKills, final int item0, final int item1,
final int item2, final int item3, final int item4, final int item5, final int item6,
final int killingSprees, final int kills, final int largestCriticalStrike,
final int largestKillingSpree, final int largestMultiKill, final int longestTimeSpentLiving,
final long magicDamageDealt, final long magicDamageDealtToChampions,
final long magicalDamageTaken, final int neutralMinionsKilled,
final int neutralMinionsKilledEnemyJungle, final int neutralMinionsKilledTeamJungle,
final int nodeCapture, final int nodeCaptureAssist, final int nodeNeutralize,
final int nodeNeutralizeAssist, final int objectivePlayerScore, final int participantId,
final int pentaKills, final int perk0, final int perk0Var1, final int perk0Var2,
final int perk0Var3, final int perk1, final int perk1Var1, final int perk1Var2,
final int perk1Var3, final int perk2, final int perk2Var1, final int perk2Var2,
final int perk2Var3, final int perk3, final int perk3Var1, final int perk3Var2,
final int perk3Var3, final int perk4, final int perk4Var1, final int perk4Var2,
final int perk4Var3, final int perk5, final int perk5Var1, final int perk5Var2,
final int perk5Var3, final int perkPrimaryStyle, final int perkSubStyle,
final long physicalDamageDealt, final long physicalDamageDealtToChampions,
final long physicalDamageTaken, final int playerScore0, final int playerScore1,
final int playerScore2, final int playerScore3, final int playerScore4,
final int playerScore5, final int playerScore6, final int playerScore7,
final int playerScore8, final int playerScore9, final int quadraKills,
final int sightWardsBoughtInGame, final int teamObjective, final long timeCCingOthers,
final long totalDamageDealt, final long totalDamageDealtToChampions,
final long totalDamageTaken, final long totalHeal, final int totalMinionsKilled,
final int totalPlayerScore, final int totalScoreRank, final int totalTimeCrowdControlDealt,
final int totalUnitsHealed, final int tripleKills, final long trueDamageDealt,
final long trueDamageDealtToChampions, final long trueDamageTaken, final int turretKills,
final int unrealKills, final long visionScore, final int visionWardsBoughtInGame,
final int wardsKilled, final int wardsPlaced, final boolean win) {
this.altarsCaptured = altarsCaptured;
this.altarsNeutralized = altarsNeutralized;
this.assists = assists;
this.champLevel = champLevel;
this.combatPlayerScore = combatPlayerScore;
this.damageDealtToObjectives = damageDealtToObjectives;
this.damageDealtToTurrets = damageDealtToTurrets;
this.damageSelfMitigated = damageSelfMitigated;
this.deaths = deaths;
this.doubleKills = doubleKills;
this.firstBloodAssist = firstBloodAssist;
this.firstBloodKill = firstBloodKill;
this.firstInhibitorAssist = firstInhibitorAssist;
this.firstInhibitorKill = firstInhibitorKill;
this.firstTowerAssist = firstTowerAssist;
this.firstTowerKill = firstTowerKill;
this.goldEarned = goldEarned;
this.goldSpent = goldSpent;
this.inhibitorKills = inhibitorKills;
this.item0 = item0;
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
this.item6 = item6;
this.killingSprees = killingSprees;
this.kills = kills;
this.largestCriticalStrike = largestCriticalStrike;
this.largestKillingSpree = largestKillingSpree;
this.largestMultiKill = largestMultiKill;
this.longestTimeSpentLiving = longestTimeSpentLiving;
this.magicDamageDealt = magicDamageDealt;
this.magicDamageDealtToChampions = magicDamageDealtToChampions;
this.magicalDamageTaken = magicalDamageTaken;
this.neutralMinionsKilled = neutralMinionsKilled;
this.neutralMinionsKilledEnemyJungle = neutralMinionsKilledEnemyJungle;
this.neutralMinionsKilledTeamJungle = neutralMinionsKilledTeamJungle;
this.nodeCapture = nodeCapture;
this.nodeCaptureAssist = nodeCaptureAssist;
this.nodeNeutralize = nodeNeutralize;
this.nodeNeutralizeAssist = nodeNeutralizeAssist;
this.objectivePlayerScore = objectivePlayerScore;
this.participantId = participantId;
this.pentaKills = pentaKills;
this.perk0 = perk0;
this.perk0Var1 = perk0Var1;
this.perk0Var2 = perk0Var2;
this.perk0Var3 = perk0Var3;
this.perk1 = perk1;
this.perk1Var1 = perk1Var1;
this.perk1Var2 = perk1Var2;
this.perk1Var3 = perk1Var3;
this.perk2 = perk2;
this.perk2Var1 = perk2Var1;
this.perk2Var2 = perk2Var2;
this.perk2Var3 = perk2Var3;
this.perk3 = perk3;
this.perk3Var1 = perk3Var1;
this.perk3Var2 = perk3Var2;
this.perk3Var3 = perk3Var3;
this.perk4 = perk4;
this.perk4Var1 = perk4Var1;
this.perk4Var2 = perk4Var2;
this.perk4Var3 = perk4Var3;
this.perk5 = perk5;
this.perk5Var1 = perk5Var1;
this.perk5Var2 = perk5Var2;
this.perk5Var3 = perk5Var3;
this.perkPrimaryStyle = perkPrimaryStyle;
this.perkSubStyle = perkSubStyle;
this.physicalDamageDealt = physicalDamageDealt;
this.physicalDamageDealtToChampions = physicalDamageDealtToChampions;
this.physicalDamageTaken = physicalDamageTaken;
this.playerScore0 = playerScore0;
this.playerScore1 = playerScore1;
this.playerScore2 = playerScore2;
this.playerScore3 = playerScore3;
this.playerScore4 = playerScore4;
this.playerScore5 = playerScore5;
this.playerScore6 = playerScore6;
this.playerScore7 = playerScore7;
this.playerScore8 = playerScore8;
this.playerScore9 = playerScore9;
this.quadraKills = quadraKills;
this.sightWardsBoughtInGame = sightWardsBoughtInGame;
this.teamObjective = teamObjective;
this.timeCCingOthers = timeCCingOthers;
this.totalDamageDealt = totalDamageDealt;
this.totalDamageDealtToChampions = totalDamageDealtToChampions;
this.totalDamageTaken = totalDamageTaken;
this.totalHeal = totalHeal;
this.totalMinionsKilled = totalMinionsKilled;
this.totalPlayerScore = totalPlayerScore;
this.totalScoreRank = totalScoreRank;
this.totalTimeCrowdControlDealt = totalTimeCrowdControlDealt;
this.totalUnitsHealed = totalUnitsHealed;
this.tripleKills = tripleKills;
this.trueDamageDealt = trueDamageDealt;
this.trueDamageDealtToChampions = trueDamageDealtToChampions;
this.trueDamageTaken = trueDamageTaken;
this.turretKills = turretKills;
this.unrealKills = unrealKills;
this.visionScore = visionScore;
this.visionWardsBoughtInGame = visionWardsBoughtInGame;
this.wardsKilled = wardsKilled;
this.wardsPlaced = wardsPlaced;
this.win = win;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ParticipantStats)) return false;
final ParticipantStats other = (ParticipantStats) obj;
return true
&& Objects.equal(altarsCaptured, other.altarsCaptured)
&& Objects.equal(altarsNeutralized, other.altarsNeutralized)
&& Objects.equal(assists, other.assists)
&& Objects.equal(champLevel, other.champLevel)
&& Objects.equal(combatPlayerScore, other.combatPlayerScore)
&& Objects.equal(damageDealtToObjectives, other.damageDealtToObjectives)
&& Objects.equal(damageDealtToTurrets, other.damageDealtToTurrets)
&& Objects.equal(damageSelfMitigated, other.damageSelfMitigated)
&& Objects.equal(deaths, other.deaths)
&& Objects.equal(doubleKills, other.doubleKills)
&& Objects.equal(firstBloodAssist, other.firstBloodAssist)
&& Objects.equal(firstBloodKill, other.firstBloodKill)
&& Objects.equal(firstInhibitorAssist, other.firstInhibitorAssist)
&& Objects.equal(firstInhibitorKill, other.firstInhibitorKill)
&& Objects.equal(firstTowerAssist, other.firstTowerAssist)
&& Objects.equal(firstTowerKill, other.firstTowerKill)
&& Objects.equal(goldEarned, other.goldEarned)
&& Objects.equal(goldSpent, other.goldSpent)
&& Objects.equal(inhibitorKills, other.inhibitorKills)
&& Objects.equal(item0, other.item0)
&& Objects.equal(item1, other.item1)
&& Objects.equal(item2, other.item2)
&& Objects.equal(item3, other.item3)
&& Objects.equal(item4, other.item4)
&& Objects.equal(item5, other.item5)
&& Objects.equal(item6, other.item6)
&& Objects.equal(killingSprees, other.killingSprees)
&& Objects.equal(kills, other.kills)
&& Objects.equal(largestCriticalStrike, other.largestCriticalStrike)
&& Objects.equal(largestKillingSpree, other.largestKillingSpree)
&& Objects.equal(largestMultiKill, other.largestMultiKill)
&& Objects.equal(longestTimeSpentLiving, other.longestTimeSpentLiving)
&& Objects.equal(magicDamageDealt, other.magicDamageDealt)
&& Objects.equal(magicDamageDealtToChampions, other.magicDamageDealtToChampions)
&& Objects.equal(magicalDamageTaken, other.magicalDamageTaken)
&& Objects.equal(neutralMinionsKilled, other.neutralMinionsKilled)
&& Objects.equal(neutralMinionsKilledEnemyJungle, other.neutralMinionsKilledEnemyJungle)
&& Objects.equal(neutralMinionsKilledTeamJungle, other.neutralMinionsKilledTeamJungle)
&& Objects.equal(nodeCapture, other.nodeCapture)
&& Objects.equal(nodeCaptureAssist, other.nodeCaptureAssist)
&& Objects.equal(nodeNeutralize, other.nodeNeutralize)
&& Objects.equal(nodeNeutralizeAssist, other.nodeNeutralizeAssist)
&& Objects.equal(objectivePlayerScore, other.objectivePlayerScore)
&& Objects.equal(participantId, other.participantId)
&& Objects.equal(pentaKills, other.pentaKills)
&& Objects.equal(perk0, other.perk0)
&& Objects.equal(perk0Var1, other.perk0Var1)
&& Objects.equal(perk0Var2, other.perk0Var2)
&& Objects.equal(perk0Var3, other.perk0Var3)
&& Objects.equal(perk1, other.perk1)
&& Objects.equal(perk1Var1, other.perk1Var1)
&& Objects.equal(perk1Var2, other.perk1Var2)
&& Objects.equal(perk1Var3, other.perk1Var3)
&& Objects.equal(perk2, other.perk2)
&& Objects.equal(perk2Var1, other.perk2Var1)
&& Objects.equal(perk2Var2, other.perk2Var2)
&& Objects.equal(perk2Var3, other.perk2Var3)
&& Objects.equal(perk3, other.perk3)
&& Objects.equal(perk3Var1, other.perk3Var1)
&& Objects.equal(perk3Var2, other.perk3Var2)
&& Objects.equal(perk3Var3, other.perk3Var3)
&& Objects.equal(perk4, other.perk4)
&& Objects.equal(perk4Var1, other.perk4Var1)
&& Objects.equal(perk4Var2, other.perk4Var2)
&& Objects.equal(perk4Var3, other.perk4Var3)
&& Objects.equal(perk5, other.perk5)
&& Objects.equal(perk5Var1, other.perk5Var1)
&& Objects.equal(perk5Var2, other.perk5Var2)
&& Objects.equal(perk5Var3, other.perk5Var3)
&& Objects.equal(perkPrimaryStyle, other.perkPrimaryStyle)
&& Objects.equal(perkSubStyle, other.perkSubStyle)
&& Objects.equal(physicalDamageDealt, other.physicalDamageDealt)
&& Objects.equal(physicalDamageDealtToChampions, other.physicalDamageDealtToChampions)
&& Objects.equal(physicalDamageTaken, other.physicalDamageTaken)
&& Objects.equal(playerScore0, other.playerScore0)
&& Objects.equal(playerScore1, other.playerScore1)
&& Objects.equal(playerScore2, other.playerScore2)
&& Objects.equal(playerScore3, other.playerScore3)
&& Objects.equal(playerScore4, other.playerScore4)
&& Objects.equal(playerScore5, other.playerScore5)
&& Objects.equal(playerScore6, other.playerScore6)
&& Objects.equal(playerScore7, other.playerScore7)
&& Objects.equal(playerScore8, other.playerScore8)
&& Objects.equal(playerScore9, other.playerScore9)
&& Objects.equal(quadraKills, other.quadraKills)
&& Objects.equal(sightWardsBoughtInGame, other.sightWardsBoughtInGame)
&& Objects.equal(teamObjective, other.teamObjective)
&& Objects.equal(timeCCingOthers, other.timeCCingOthers)
&& Objects.equal(totalDamageDealt, other.totalDamageDealt)
&& Objects.equal(totalDamageDealtToChampions, other.totalDamageDealtToChampions)
&& Objects.equal(totalDamageTaken, other.totalDamageTaken)
&& Objects.equal(totalHeal, other.totalHeal)
&& Objects.equal(totalMinionsKilled, other.totalMinionsKilled)
&& Objects.equal(totalPlayerScore, other.totalPlayerScore)
&& Objects.equal(totalScoreRank, other.totalScoreRank)
&& Objects.equal(totalTimeCrowdControlDealt, other.totalTimeCrowdControlDealt)
&& Objects.equal(totalUnitsHealed, other.totalUnitsHealed)
&& Objects.equal(tripleKills, other.tripleKills)
&& Objects.equal(trueDamageDealt, other.trueDamageDealt)
&& Objects.equal(trueDamageDealtToChampions, other.trueDamageDealtToChampions)
&& Objects.equal(trueDamageTaken, other.trueDamageTaken)
&& Objects.equal(turretKills, other.turretKills)
&& Objects.equal(unrealKills, other.unrealKills)
&& Objects.equal(visionScore, other.visionScore)
&& Objects.equal(visionWardsBoughtInGame, other.visionWardsBoughtInGame)
&& Objects.equal(wardsKilled, other.wardsKilled)
&& Objects.equal(wardsPlaced, other.wardsPlaced)
&& Objects.equal(win, other.win);}
@Override
public int hashCode() {
return Objects.hashCode(0,
altarsCaptured,
altarsNeutralized,
assists,
champLevel,
combatPlayerScore,
damageDealtToObjectives,
damageDealtToTurrets,
damageSelfMitigated,
deaths,
doubleKills,
firstBloodAssist,
firstBloodKill,
firstInhibitorAssist,
firstInhibitorKill,
firstTowerAssist,
firstTowerKill,
goldEarned,
goldSpent,
inhibitorKills,
item0,
item1,
item2,
item3,
item4,
item5,
item6,
killingSprees,
kills,
largestCriticalStrike,
largestKillingSpree,
largestMultiKill,
longestTimeSpentLiving,
magicDamageDealt,
magicDamageDealtToChampions,
magicalDamageTaken,
neutralMinionsKilled,
neutralMinionsKilledEnemyJungle,
neutralMinionsKilledTeamJungle,
nodeCapture,
nodeCaptureAssist,
nodeNeutralize,
nodeNeutralizeAssist,
objectivePlayerScore,
participantId,
pentaKills,
perk0,
perk0Var1,
perk0Var2,
perk0Var3,
perk1,
perk1Var1,
perk1Var2,
perk1Var3,
perk2,
perk2Var1,
perk2Var2,
perk2Var3,
perk3,
perk3Var1,
perk3Var2,
perk3Var3,
perk4,
perk4Var1,
perk4Var2,
perk4Var3,
perk5,
perk5Var1,
perk5Var2,
perk5Var3,
perkPrimaryStyle,
perkSubStyle,
physicalDamageDealt,
physicalDamageDealtToChampions,
physicalDamageTaken,
playerScore0,
playerScore1,
playerScore2,
playerScore3,
playerScore4,
playerScore5,
playerScore6,
playerScore7,
playerScore8,
playerScore9,
quadraKills,
sightWardsBoughtInGame,
teamObjective,
timeCCingOthers,
totalDamageDealt,
totalDamageDealtToChampions,
totalDamageTaken,
totalHeal,
totalMinionsKilled,
totalPlayerScore,
totalScoreRank,
totalTimeCrowdControlDealt,
totalUnitsHealed,
tripleKills,
trueDamageDealt,
trueDamageDealtToChampions,
trueDamageTaken,
turretKills,
unrealKills,
visionScore,
visionWardsBoughtInGame,
wardsKilled,
wardsPlaced,
win);}
}
| MingweiSamuel/Zyra | src/main/gen/com/mingweisamuel/zyra/matchV4/ParticipantStats.java | Java | lgpl-3.0 | 22,002 |