repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
OnroerendErfgoed/atramhasis | atramhasis/static/admin/src/app/App.js | 2544 | /**
* Main application widget.
* @module App
* @see module:App
*/
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/promise/all',
'dijit/_WidgetBase',
'./ui/AppUi',
'./controllers/ConceptSchemeController',
'./controllers/ConceptController',
'./controllers/LanguageController',
'./controllers/ListController',
'dGrowl'
], function (
declare,
lang,
all,
WidgetBase,
AppUi,
ConceptSchemeController,
ConceptController,
LanguageController,
ListController,
dGrowl
) {
return declare([WidgetBase], {
appConfig: null,
_controllers: null,
languageManager: null,
/**
* Standard widget function.
* @public
*/
postCreate: function () {
this.inherited(arguments);
console.debug('App::postCreate');
this._controllers = {};
this._controllers.conceptSchemeController = new ConceptSchemeController({});
this._controllers.conceptController = new ConceptController({});
this._controllers.languageController = new LanguageController({});
this._controllers.listController = new ListController({});
//Start message handler
new dGrowl({
'channels':[
{'name':'info','pos':3},
{'name':'error', 'pos':1},
{'name':'warn', 'pos':2}
]
});
},
/**
* Standard widget function.
* @public
*/
startup: function () {
this.inherited(arguments);
console.debug('App::startup');
var conceptSchemePromise = this._controllers.conceptSchemeController.loadConceptSchemeStores();
all({
conceptScheme: conceptSchemePromise
}).then(
lang.hitch(this, function(results) {
new AppUi({
loadingContainer: this.appConfig.loadingContainer,
appContainer: this.appConfig.appContainer,
staticAppPath: this.appConfig.staticAppPath,
conceptSchemeController: this._controllers.conceptSchemeController,
conceptController: this._controllers.conceptController,
languageController: this._controllers.languageController,
listController: this._controllers.listController
}, this.appConfig.appContainer).startup();
}),
lang.hitch(this, function(error) {
console.error(error);
window.alert("Startup error: \n\n" +
"There was a problem connecting to the backend services, the application cannot be started.");
})
);
}
});
});
| gpl-3.0 |
RickMyers/Jarvis | lib/Rain3/example-simple.php | 812 | <?php
// namespace
use Rain\Tpl;
// include
include "library/Rain/Tpl.php";
// config
$config = array(
"tpl_dir" => "templates/simple/",
"cache_dir" => "cache/",
"debug" => true // set to false to improve the speed
);
Tpl::configure( $config );
// Add PathReplace plugin (necessary to load the CSS with path replace)
require_once('library/Rain/Tpl/Plugin/PathReplace.php');
Rain\Tpl::registerPlugin( new Rain\Tpl\Plugin\PathReplace() );
// create the Tpl object
$tpl = new Tpl;
// assign a variable
$tpl->assign( "name", "Obi Wan Kenoby" );
// assign an array
$tpl->assign( "week", array( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ) );
// draw the template
$tpl->draw( "simple_template" );
?> | gpl-3.0 |
hatstand/clementine-remote-android | src/de/qspool/clementineremote/backend/requests/RequestControl.java | 1138 | /* This file is part of the Android Clementine Remote.
* Copyright (C) 2013, Andreas Muttscheller <[email protected]>
*
* 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.qspool.clementineremote.backend.requests;
public class RequestControl extends RequestToThread {
public static enum Request {PLAY, PLAYPAUSE, PAUSE, STOP, NEXT, PREV, CHANGESONG, SHUFFLE};
private Request mRequest;
public RequestControl(Request request) {
super();
mRequest = request;
}
public Request getRequest() {
return mRequest;
}
}
| gpl-3.0 |
Stuart4/radio91x | app/src/main/java/org/stuartresearch/radio91x/AudioPlayerBroadcastReceiver.java | 2869 | package org.stuartresearch.radio91x;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
/**
* Created by jake on 5/15/15.
*/
public class AudioPlayerBroadcastReceiver extends BroadcastReceiver implements ServiceConnection{
private static MainActivity mainActivity;
private static RadioService radioService;
public static void setActivity (MainActivity act) {
mainActivity = act;
}
public static void setService (RadioService srv) {
radioService = srv;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (mainActivity != null) {
if (action.equals("org.stuartresearch.radio91x.LOADED")) {
mainActivity.streamLoaded();
} else if (action.equals("org.stuartresearch.radio91x.LOADING")) {
mainActivity.streamLoading();
} else if (action.equals("org.stuartresearch.radio91x.ERROR")) {
mainActivity.streamError();
} else if (action.equals("org.stuartresearch.radio91x.PLAYING")) {
mainActivity.streamPlaying();
} else if (action.equals("org.stuartresearch.radio91x.STOPPED")) {
mainActivity.streamStopped();
} else if (action.equals("org.stuartresearch.radio91x.PLAY")) {
mainActivity.streamPlaying();
} else if (action.equals("org.stuartresearch.radio91x.PAUSE")) {
mainActivity.streamStopped();
}
}
if (radioService != null) {
if (action.equals("org.stuartresearch.radio91x.PLAY")) {
radioService.play();
} else if (action.equals("org.stuartresearch.radio91x.PAUSE")) {
radioService.stop(true);
if (mainActivity != null) {
mainActivity.streamLoaded();
mainActivity.streamStopped();
}
} else if (action.equals("org.stuartresearch.radio91x.NOSOUND")) {
radioService.noSound();
} else if (action.equals("org.stuartresearch.radio91x.NOSOUND")) {
radioService.sound();
} else if (action.equals("android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY")) {
radioService.stop(true);
if (mainActivity != null) {
mainActivity.streamLoaded();
mainActivity.streamStopped();
}
}
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
| gpl-3.0 |
Donzii/phpMumbleAdmin-0.4.3 | program/widgets/main_languagesFlags.view.php | 1358 | <?php
/*
* phpMumbleAdmin (PMA), web php administration tool for murmur (mumble server daemon).
* Copyright (C) 2010 - 2015 Dadon David. [email protected]
*
* 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/>.
*/
if (! defined('PMA_STARTED')) { die('ILLEGAL: You cannot call this script directly !'); }
$widget = $PMA->widgets->getDatas('main_languagesFlags');
if (count($widget->langFlags) > 1): ?>
<ul id="PMA_langFlags">
<?php foreach ($widget->langFlags as $f): ?>
<li>
<a href="?cmd=config&setLang=<?php echo $f->dir; ?>">
<img src="<?php echo $f->src; ?>" title="<?php echo $f->title; ?>" alt="" /></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif;
| gpl-3.0 |
Raphcal/sigmah | src/main/java/org/sigmah/client/ui/presenter/admin/models/EditLayoutGroupAdminPresenter.java | 11632 | package org.sigmah.client.ui.presenter.admin.models;
/*
* #%L
* Sigmah
* %%
* Copyright (C) 2010 - 2016 URD
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import org.sigmah.client.dispatch.CommandResultHandler;
import org.sigmah.client.event.UpdateEvent;
import org.sigmah.client.i18n.I18N;
import org.sigmah.client.inject.Injector;
import org.sigmah.client.page.Page;
import org.sigmah.client.page.PageRequest;
import org.sigmah.client.page.RequestParameter;
import org.sigmah.client.ui.notif.N10N;
import org.sigmah.client.ui.presenter.base.AbstractPagePresenter;
import org.sigmah.client.ui.presenter.base.HasForm;
import org.sigmah.client.ui.view.admin.models.EditLayoutGroupAdminView;
import org.sigmah.client.ui.view.base.ViewPopupInterface;
import org.sigmah.client.ui.widget.button.Button;
import org.sigmah.client.ui.widget.form.FormPanel;
import org.sigmah.client.util.AdminUtil;
import org.sigmah.client.util.ClientUtils;
import org.sigmah.shared.command.CreateEntity;
import org.sigmah.shared.command.result.CreateResult;
import org.sigmah.shared.dto.ContactDetailsDTO;
import org.sigmah.shared.dto.ContactModelDTO;
import org.sigmah.shared.dto.IsModel;
import org.sigmah.shared.dto.OrgUnitDetailsDTO;
import org.sigmah.shared.dto.PhaseModelDTO;
import org.sigmah.shared.dto.ProjectDetailsDTO;
import org.sigmah.shared.dto.base.AbstractModelDataEntityDTO;
import org.sigmah.shared.dto.element.FlexibleElementDTO;
import org.sigmah.shared.dto.layout.LayoutConstraintDTO;
import org.sigmah.shared.dto.layout.LayoutDTO;
import org.sigmah.shared.dto.layout.LayoutGroupDTO;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.sigmah.shared.command.Delete;
import org.sigmah.shared.command.result.VoidResult;
import org.sigmah.shared.dto.referential.ElementTypeEnum;
/**
* Presenter in charge of creating/editing a layout group.
*
* @author Denis Colliot ([email protected]) (v2.0)
*/
@Singleton
public class EditLayoutGroupAdminPresenter extends AbstractPagePresenter<EditLayoutGroupAdminPresenter.View> implements HasForm {
/**
* Description of the view managed by this presenter.
*/
@ImplementedBy(EditLayoutGroupAdminView.class)
public static interface View extends ViewPopupInterface {
FormPanel getForm();
Field<String> getNameField();
ComboBox<BaseModelData> getContainerField();
SimpleComboBox<Integer> getRowField();
CheckBox getHasIterationsField();
Button getSaveButton();
Button getDeleteButton();
}
/**
* The edited {@link LayoutGroupDTO}, or {@code null} in case of creation.
*/
private LayoutGroupDTO layoutGroup;
/**
* Presenter's initialization.
*
* @param view
* The view managed by the presenter.
* @param injector
* The application injector.
*/
@Inject
protected EditLayoutGroupAdminPresenter(final View view, final Injector injector) {
super(view, injector);
}
/**
* {@inheritDoc}
*/
@Override
public Page getPage() {
return Page.ADMIN_EDIT_LAYOUT_GROUP_MODEL;
}
/**
* {@inheritDoc}
*/
@Override
public void onBind() {
// --
// Container field change events handler.
// --
view.getContainerField().addListener(Events.Change, new Listener<BaseEvent>() {
@Override
public void handleEvent(final BaseEvent event) {
final BaseModelData selectedContainer = view.getContainerField().getValue();
setRowFieldValues(selectedContainer, null);
}
});
// --
// Save button handler.
// --
view.getSaveButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(final ButtonEvent event) {
onSaveForm();
}
});
// --
// Delete button handler.
// --
view.getDeleteButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(final ButtonEvent event) {
onDelete();
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void onPageRequest(final PageRequest request) {
view.getForm().clearAll();
view.getRowField().disable();
setPageTitle(I18N.CONSTANTS.adminFlexibleGroup());
final FlexibleElementDTO flexibleElement = request.getData(RequestParameter.DTO);
final IsModel currentModel = request.getData(RequestParameter.MODEL);
if (currentModel == null) {
hideView();
throw new IllegalArgumentException("Missing required model.");
}
// --
// Loads containers.
// --
view.getContainerField().getStore().removeAll();
if (ClientUtils.isNotEmpty(currentModel.getHasLayoutElements())) {
for (final AbstractModelDataEntityDTO<?> hasLayout : currentModel.getHasLayoutElements()) {
if (hasLayout == null) {
continue;
}
view.getContainerField().getStore().add(hasLayout);
}
}
// --
// Loads the edited element.
// --
// view.getDeleteButton().setVisible(flexibleElement != null);
if (flexibleElement != null) {
layoutGroup = flexibleElement.getGroup();
view.getNameField().setValue(layoutGroup.getTitle());
view.getContainerField().setValue(flexibleElement.getContainerModel());
setRowFieldValues(flexibleElement.getContainerModel(), layoutGroup.getRow());
view.getHasIterationsField().setValue(layoutGroup.getHasIterations());
} else {
layoutGroup = null;
}
}
/**
* {@inheritDoc}
*/
@Override
public FormPanel[] getForms() {
return new FormPanel[] { view.getForm()
};
}
// ---------------------------------------------------------------------------------------------------------------
//
// UTILITY METHODS.
//
// ---------------------------------------------------------------------------------------------------------------
/**
* Populates the row field with the given {@code hasLayout} corresponding layout row counts.
*
* @param hasLayout
* The component with a layout.
* @param selectedValue
* The optional selected value.
*/
private void setRowFieldValues(final BaseModelData hasLayout, final Integer selectedValue) {
view.getRowField().removeAll();
view.getRowField().setEnabled(hasLayout != null);
if (hasLayout == null) {
return;
}
final LayoutDTO container = getLayout(hasLayout);
if (container != null) {
view.getRowField().removeAll();
for (int i = 0; i < container.getRowsCount(); i++) {
view.getRowField().add(i);
}
if (layoutGroup == null) {
view.getRowField().add(container.getRowsCount());
}
}
view.getRowField().setSimpleValue(selectedValue);
}
/**
* Retrieves the given {@code hasLayout} corresponding {@link LayoutDTO}.
*
* @param hasLayout
* The container, may be {@code null}.
* @return The given {@code hasLayout} corresponding {@link LayoutDTO}, or {@code null}.
*/
static LayoutDTO getLayout(final BaseModelData hasLayout) {
if (hasLayout instanceof ProjectDetailsDTO) {
return ((ProjectDetailsDTO) hasLayout).getLayout();
} else if (hasLayout instanceof PhaseModelDTO) {
return ((PhaseModelDTO) hasLayout).getLayout();
} else if (hasLayout instanceof OrgUnitDetailsDTO) {
return ((OrgUnitDetailsDTO) hasLayout).getLayout();
} else if (hasLayout instanceof ContactDetailsDTO) {
return ((ContactDetailsDTO) hasLayout).getLayout();
} else {
return null;
}
}
/**
* Callback executed on <em>save</em> button action.
*/
private void onSaveForm() {
if (!view.getForm().isValid()) {
return;
}
final String name = view.getNameField().getValue();
final Integer row = view.getRowField().getSimpleValue();
final Integer column = 0;
final Boolean hasIterations = view.getHasIterationsField().getValue();
final LayoutDTO container = getLayout(view.getContainerField().getValue());
// iterative groups cannot contain default fields nor core fields
if(hasIterations && layoutGroup != null) {
for(LayoutConstraintDTO constraint : layoutGroup.getConstraints()) {
if(constraint.getFlexibleElementDTO().getElementType() == ElementTypeEnum.DEFAULT
|| constraint.getFlexibleElementDTO().getElementType() == ElementTypeEnum.DEFAULT_CONTACT) {
N10N.error(I18N.CONSTANTS.adminFlexibleGroup(), I18N.CONSTANTS.adminErrorDefaultFieldIterable());
return;
}
if(constraint.getFlexibleElementDTO().getAmendable()) {
N10N.error(I18N.CONSTANTS.adminFlexibleGroup(), I18N.CONSTANTS.adminErrorCoreFieldIterable());
return;
}
}
}
final LayoutGroupDTO layoutGroupDTO = layoutGroup != null ? layoutGroup : new LayoutGroupDTO();
layoutGroupDTO.setTitle(name);
layoutGroupDTO.setRow(row);
layoutGroupDTO.setColumn(column);
layoutGroupDTO.setHasIterations(hasIterations);
layoutGroupDTO.setParentLayout(container);
final Map<String, Object> newGroupProperties = new HashMap<String, Object>();
newGroupProperties.put(AdminUtil.PROP_NEW_GROUP_LAYOUT, layoutGroupDTO);
dispatch.execute(new CreateEntity(LayoutGroupDTO.ENTITY_NAME, newGroupProperties), new CommandResultHandler<CreateResult>() {
@Override
public void onCommandFailure(final Throwable caught) {
N10N.error(I18N.CONSTANTS.adminFlexibleGroup(),
I18N.MESSAGES.adminStandardCreationFailure(I18N.MESSAGES.adminStandardLayoutGroup() + " '" + name + "'"));
}
@Override
public void onCommandSuccess(final CreateResult result) {
if (result == null) {
N10N.warn(I18N.CONSTANTS.adminFlexibleGroup(), I18N.MESSAGES.adminStandardCreationNull(I18N.MESSAGES.adminStandardLayoutGroup() + " '" + name + "'"));
return;
}
N10N.infoNotif(I18N.CONSTANTS.adminFlexibleGroup(),
I18N.MESSAGES.adminStandardUpdateSuccess(I18N.MESSAGES.adminStandardLayoutGroup() + " '" + name + "'"));
hideView();
// Send an update event to reload necessary data.
eventBus.fireEvent(new UpdateEvent(UpdateEvent.LAYOUT_GROUP_UPDATE, result.getEntity()));
}
}, view.getSaveButton(), view.getDeleteButton());
}
/**
* Callback executed on <em>delete</em> button action.
*/
private void onDelete() {
dispatch.execute(new Delete(layoutGroup), new CommandResultHandler<VoidResult>() {
@Override
protected void onCommandSuccess(VoidResult result) {
hideView();
// Send an update event to reload necessary data.
// eventBus.fireEvent(new UpdateEvent(UpdateEvent.LAYOUT_GROUP_UPDATE, result.getEntity()));
}
}, view.getSaveButton(), view.getDeleteButton());
}
}
| gpl-3.0 |
2CanGames/Perennial | Source/Perennial/Perennial.Build.cs | 720 | // Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
public class Perennial : ModuleRules
{
public Perennial(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
| gpl-3.0 |
j0r1/simpactcyan | src/lib/util/discretedistribution2d.cpp | 6216 | #include "discretedistribution2d.h"
#include "gridvalues.h"
#include "util.h"
#include <iostream>
#include <limits>
using namespace std;
DiscreteDistribution2D::DiscreteDistribution2D(double xOffset, double yOffset, double xSize, double ySize,
const GridValues &density, bool floor, GslRandomNumberGenerator *pRngGen,
const Polygon2D &filter) : ProbabilityDistribution2D(pRngGen, true)
{
m_pMarginalXDist = 0;
m_pMarginalYDist = 0;
m_xSize = xSize;
m_ySize = ySize;
m_xOffset = xOffset;
m_yOffset = yOffset;
m_width = density.getWidth();
m_height = density.getHeight();
generateConditionalsAndMarginal(xOffset, yOffset, xSize, ySize, density, pRngGen, filter, false, m_conditionalXDists, &m_pMarginalYDist);
generateConditionalsAndMarginal(xOffset, yOffset, xSize, ySize, density, pRngGen, filter, true, m_conditionalYDists, &m_pMarginalXDist);
m_flippedY = density.isYFlipped();
m_floor = floor;
}
DiscreteDistribution2D::~DiscreteDistribution2D()
{
delete m_pMarginalXDist;
delete m_pMarginalYDist;
for (size_t i = 0 ; i < m_conditionalXDists.size() ; i++)
delete m_conditionalXDists[i];
for (size_t i = 0 ; i < m_conditionalYDists.size() ; i++)
delete m_conditionalYDists[i];
}
Point2D DiscreteDistribution2D::pickPoint() const
{
double y = m_pMarginalYDist->pickNumber();
int yi = (int)y;
assert(yi >= 0 && yi < (int)m_conditionalXDists.size());
double x = m_conditionalXDists[yi]->pickNumber();
x = (x/(double)m_width)*m_xSize;
y = (y/(double)m_height)*m_ySize;
// If we want to floor it, we calculate that here
if (m_floor)
{
double xBinSize = m_xSize/(double)m_width;
double yBinSize = m_ySize/(double)m_height;
x = ((int)(x/xBinSize))*xBinSize;
y = ((int)(y/yBinSize))*yBinSize;
}
x += m_xOffset;
y += m_yOffset;
return Point2D(x, y);
}
double DiscreteDistribution2D::pickMarginalX() const
{
double x = m_pMarginalXDist->pickNumber();
x = (x/(double)m_width)*m_xSize;
// If we want to floor it, we calculate that here
if (m_floor)
{
double xBinSize = m_xSize/(double)m_width;
x = ((int)(x/xBinSize))*xBinSize;
}
x += m_xOffset;
return x;
}
double DiscreteDistribution2D::pickMarginalY() const
{
double y = m_pMarginalYDist->pickNumber();
y = (y/(double)m_height)*m_ySize;
// If we want to floor it, we calculate that here
if (m_floor)
{
double yBinSize = m_ySize/(double)m_height;
y = ((int)(y/yBinSize))*yBinSize;
}
y += m_yOffset;
return y;
}
double DiscreteDistribution2D::pickConditionalOnX(double x) const
{
x = (x - m_xOffset)/m_xSize * (double)m_width;
int xi = (int)x;
if (xi < 0 || xi >= (int)m_conditionalYDists.size())
return numeric_limits<double>::quiet_NaN();
double y = m_conditionalYDists[xi]->pickNumber();
y = (y/(double)m_height)*m_ySize;
// If we want to floor it, we calculate that here
if (m_floor)
{
double yBinSize = m_ySize/(double)m_height;
y = ((int)(y/yBinSize))*yBinSize;
}
y += m_yOffset;
return y;
}
double DiscreteDistribution2D::pickConditionalOnY(double y) const
{
y = (y - m_yOffset)/m_ySize * (double)m_height;
int yi = (int)y;
if (yi < 0 || yi >= (int)m_conditionalXDists.size())
return numeric_limits<double>::quiet_NaN();
double x = m_conditionalXDists[yi]->pickNumber();
x = (x/(double)m_width)*m_xSize;
// If we want to floor it, we calculate that here
if (m_floor)
{
double xBinSize = m_xSize/(double)m_width;
x = ((int)(x/xBinSize))*xBinSize;
}
x += m_xOffset;
return x;
}
void DiscreteDistribution2D::generateConditionalsAndMarginal(double xOffset, double yOffset, double xSize, double ySize,
const GridValues &density, GslRandomNumberGenerator *pRngGen,
const Polygon2D &filter, bool transpose,
#ifdef OLDTEST
vector<DiscreteDistribution *> &conditionals,
DiscreteDistribution **ppMarginal
#else
vector<DiscreteDistributionFast *> &conditionals,
DiscreteDistributionFast **ppMarginal
#endif
)
{
assert(conditionals.size() == 0);
assert(*ppMarginal == 0);
int dim1, dim2;
if (!transpose)
{
dim1 = density.getWidth();
dim2 = density.getHeight();
}
else
{
dim1 = density.getHeight();
dim2 = density.getWidth();
}
vector<double> margValues(dim2);
vector<double> condValues(dim1);
bool hasFilter = (filter.getNumberOfPoints() > 0);
double pixelWidth = xSize/(double)density.getWidth();
double pixelHeight = ySize/(double)density.getHeight();
bool hasValue = false;
for (int v = 0 ; v < dim2 ; v++)
{
double sum = 0;
for (int u = 0 ; u < dim1 ; u++)
{
double val = 0;
bool pass = true;
int x, y;
if (!transpose)
{
x = u;
y = v;
}
else
{
x = v;
y = u;
}
if (hasFilter)
{
double xCoord = xOffset + pixelWidth*(0.5+(double)x);
double yCoord = yOffset + pixelHeight*(0.5+(double)y);
if (!filter.isInside(xCoord, yCoord))
pass = false;
}
if (pass)
{
val = density.getValue(x, y);
if (val != 0)
hasValue = true;
}
assert(val >= 0);
condValues[u] = val;
sum += val;
}
#ifdef OLDTEST
std::vector<double> binStarts, histValues;
for (size_t i = 0 ; i < condValues.size() ; i++)
{
binStarts.push_back((double)i);
histValues.push_back(condValues[i]);
}
binStarts.push_back(dim1);
histValues.push_back(0);
conditionals.push_back(new DiscreteDistribution(binStarts, histValues, false, pRngGen));
#else
conditionals.push_back(new DiscreteDistributionFast(0, dim1, condValues, false, pRngGen));
#endif
margValues[v] = sum;
}
if (!hasValue)
abortWithMessage("No non-zero value found in DiscreteDistribution2D::generateConditionalsAndMarginal. Bad data file.");
#ifdef OLDTEST
std::vector<double> binStarts, histValues;
for (int i = 0 ; i < margValues.size() ; i++)
{
binStarts.push_back((double)i);
histValues.push_back(margValues[i]);
}
binStarts.push_back(dim2);
histValues.push_back(0);
*ppMarginal = new DiscreteDistribution(binStarts, histValues, false, pRngGen);
#else
*ppMarginal = new DiscreteDistributionFast(0, dim2, margValues, false, pRngGen);
#endif
}
| gpl-3.0 |
tfiedor/perun | perun/collect/trace/systemtap/script_compact.py | 17798 | """SystemTap script generator module. Assembles the SystemTap script according to the specified
rules such as function or USDT locations and sampling.
"""
from perun.collect.trace.watchdog import WATCH_DOG
from perun.collect.trace.values import RecordType
from perun.collect.trace.optimizations.structs import Optimizations, Parameters
# Names of the global arrays used throughout the script
ARRAY_PROBE_ID = 'probe_id'
ARRAY_SAMPLE_THRESHOLD = 'sampling_threshold'
ARRAY_SAMPLE_COUNTER = 'sampling_counter'
ARRAY_SAMPLE_FLAG = 'sampling_flag'
ARRAY_RECURSION_DEPTH = 'recursion_depth'
ARRAY_RECURSION_SAMPLE_HIT = 'recursion_sample_hit'
# Names of other used global variables
STOPWATCH_ON = 'stopwatch_on'
STOPWATCH_NAME = 'timestamp'
TIMED_SWITCH = 'timed_switch'
# Default MAP size
MAX_MAP_ENTRIES = 2048
# Template of the global arrays declaration
ARRAYS_TEMPLATE = """
{id_array}
{sampling_arrays}
{recursion_arrays}
"""
# Template of the sampling global arrays declaration
ARRAYS_SAMPLING_TEMPLATE = """
global {sampling_thr}[{{size}}]
global {sampling_cnt}[{{max_size}}]
global {sampling_flag}[{{max_size}}]
""".format(
sampling_thr=ARRAY_SAMPLE_THRESHOLD,
sampling_cnt=ARRAY_SAMPLE_COUNTER,
sampling_flag=ARRAY_SAMPLE_FLAG
)
# Template of the recursion sampling global arrays declaration
ARRAYS_RECURSION_TEMPLATE = """
global {recursion_depth}
global {recursion_hit}
""".format(
recursion_depth=ARRAY_RECURSION_DEPTH,
recursion_hit=ARRAY_RECURSION_SAMPLE_HIT,
)
# Template of a function event
FUNC_EVENT_TEMPLATE = 'process("{binary}").function("{name}"){{suffix}}{timed_switch}'
# Template of an USDT event
USDT_EVENT_TEMPLATE = 'process("{binary}").mark("{loc}")?'
# Template of a process begin / end handler
PROCESS_HANDLER_TEMPLATE = (
'printf("{type} %d %d %d %d;%s\\n", '
'tid(), pid(), ppid(), read_stopwatch_ns("{timestamp}"), execname())'
)
THREAD_HANDLER_TEMPLATE = \
'printf("{type} %d %d %d;%s\\n", tid(), pid(), read_stopwatch_ns("{timestamp}"), execname())'
# Template of a record creation within a probe handler
HANDLER_TEMPLATE = \
'printf("{type} %d %d;{id_type}\\n", tid, read_stopwatch_ns("{timestamp}"), {id_get})'
# Template of a probe event declaration and handler definition
PROBE_TEMPLATE = """
probe {probe_events}
{{
pname = ppfunc()
tid = tid()
{probe_handler}
}}
"""
# Template of a sampled entry probe handler that is imprecise for sampled recursive functions
ENTRY_APPROX_SAMPLE_TEMPLATE = """
counter = {sampling_cnt}[tid, pname]
if (counter == 0 || counter == {sampling_thr}[pname]) {{{{
counter = 0
{sampling_flag}[tid, pname] ++
{{probe_handler}}
}}}}
{sampling_cnt}[tid, pname] ++
""".format(
sampling_cnt=ARRAY_SAMPLE_COUNTER,
sampling_thr=ARRAY_SAMPLE_THRESHOLD,
sampling_flag=ARRAY_SAMPLE_FLAG
)
# Template of a sampled exit probe handler that is imprecise for sampled recursive functions
EXIT_APPROX_SAMPLE_TEMPLATE = """
if ({sampling_flag}[tid, pname] > 0) {{{{
{{probe_handler}}
{sampling_flag}[tid, pname] --
}}}}
""".format(
sampling_flag=ARRAY_SAMPLE_FLAG
)
# Template of a sampled entry probe handler that can precisely measure even sampled recursive
# functions - however, it is sensitive to call nesting errors (e.g., omitted retprobe calls etc.)
ENTRY_PRECISE_SAMPLE_TEMPLATE = """
{sampling_cnt}[tid, pname] ++
{recursion_depth}[tid, pname] ++
if ({sampling_cnt}[tid, pname] == {sampling_thr}[pname]) {{{{
{recursion_hit}[tid, pname, {recursion_depth}[tid, pname]] = 1
{sampling_cnt}[tid, pname] = 0
{{probe_handler}}
}}}}
""".format(
sampling_cnt=ARRAY_SAMPLE_COUNTER,
recursion_depth=ARRAY_RECURSION_DEPTH,
sampling_thr=ARRAY_SAMPLE_THRESHOLD,
recursion_hit=ARRAY_RECURSION_SAMPLE_HIT
)
# Template of a sampled exit probe handler that can precisely measure even sampled recursive
# functions - however, it is sensitive to call nesting errors (e.g., omitted retprobe calls etc.
EXIT_PRECISE_SAMPLE_TEMPLATE = """
if ([tid, pname, {recursion_depth}[tid, pname]] in {recursion_hit}) {{{{
{{probe_handler}}
delete {recursion_hit}[tid, pname, {recursion_depth}[tid, pname]]
}}}}
{recursion_depth}[tid, pname] --
""".format(
recursion_depth=ARRAY_RECURSION_DEPTH,
recursion_hit=ARRAY_RECURSION_SAMPLE_HIT
)
# TODO: solve func name / USDT name collision in the arrays
# TODO: solve precise / approx sampling switching
def assemble_system_tap_script(script_file, config, probes, **_):
"""Assembles SystemTap script according to the configuration and probes specification.
:param str script_file: path to the script file, that should be generated
:param Configuration config: the configuration parameters
:param Probes probes: the probes specification
"""
WATCH_DOG.info("Attempting to assembly the SystemTap script '{}'".format(script_file))
# Add unique probe and sampling ID to the probes
probes.add_probe_ids()
# Open the script file in write mode
with open(script_file, 'w') as script_handle:
# Obtain configuration for the timed sampling optimization
timed_sampling = Optimizations.TIMED_SAMPLING.value in config.run_optimizations
# Declare and init arrays, create the begin / end probes
_add_script_init(script_handle, config, probes, timed_sampling)
# Add the thread begin / end probes
_add_thread_probes(script_handle, config.binary, bool(probes.sampled_probes_len()))
# Add the timed sampling timer probe if needed
if timed_sampling:
sampling_freq = config.run_optimization_parameters[Parameters.TIMEDSAMPLE_FREQ.value]
_add_timer_probe(script_handle, sampling_freq)
# Create the timing probes for functions and USDT probes
_add_program_probes(script_handle, probes, config.verbose_trace, timed_sampling)
# Success
WATCH_DOG.info("SystemTap script successfully assembled")
WATCH_DOG.log_probes(len(probes.func), len(probes.usdt), script_file)
def _add_script_init(handle, config, probes, timed_sampling):
"""Declare and initialize ID, sampling and recursion arrays (certain arrays may be omitted
when e.g., sampling is turned off), necessary global variables, as well as add the process
begin and end probe.
:param TextIO handle: the script file handle
:param Configuration config: the configuration parameters
:param Probes probes: the probes specification
:param bool timed_sampling: specifies whether Timed Sampling is on or off
"""
script_init = """
{array_declaration}
{timed_sampling}
global {stopwatch} = 0
probe process("{binary}").begin {{
{id_init}
{sampling_init}
if (!{stopwatch}) {{
{stopwatch} = 1
start_stopwatch("{timestamp}")
}}
{begin_handler}
}}
probe process("{binary}").end
{{
{end_handler}
}}
""".format(
array_declaration=_build_array_declaration(
probes, config.verbose_trace, config.maximum_threads
),
stopwatch=STOPWATCH_ON,
id_init=_build_id_init(probes, config.verbose_trace),
sampling_init=_build_sampling_init(probes),
binary=config.binary,
timestamp=STOPWATCH_NAME,
begin_handler=PROCESS_HANDLER_TEMPLATE.format(
type=int(RecordType.PROCESS_BEGIN), timestamp=STOPWATCH_NAME
),
end_handler=PROCESS_HANDLER_TEMPLATE.format(
type=int(RecordType.PROCESS_END), timestamp=STOPWATCH_NAME
),
timed_sampling=(
"global {} = 1".format(TIMED_SWITCH) if timed_sampling else "# Timed Sampling omitted"
)
)
handle.write(script_init)
def _add_thread_probes(handle, binary, sampling_on):
""" Add thread begin and end probes.
:param TextIO handle: the script file handle
:param str binary: the name of the binary file
:param bool sampling_on: specifies whether per-function sampling is on
"""
end_probe = """
probe process("{binary}").thread.begin {{
{begin_handler}
}}
probe process("{binary}").thread.end {{
{end_handler}
{sampling_cleanup}
}}
""".format(
binary=binary,
begin_handler=THREAD_HANDLER_TEMPLATE.format(
type=int(RecordType.THREAD_BEGIN), timestamp=STOPWATCH_NAME
),
end_handler=THREAD_HANDLER_TEMPLATE.format(
type=int(RecordType.THREAD_END), timestamp=STOPWATCH_NAME
),
sampling_cleanup=(
('delete {sampling_cnt}[tid(), *]\n delete {sampling_flag}[tid(), *]'
.format(sampling_cnt=ARRAY_SAMPLE_COUNTER, sampling_flag=ARRAY_SAMPLE_FLAG))
if sampling_on else '# Sampling cleanup omitted'
)
)
handle.write(end_probe)
# TODO: frequency to ns timer
def _add_timer_probe(handle, sampling_frequency):
""" Add a probe for timed event that enables / disables function probes.
:param TextIO handle: the script file handle
:param int sampling_frequency: timer (ns) value of the timer probe firing
"""
# Create the sampling timer
timer_probe = """
probe timer.ns({freq}) if ({stopwatch}) {{
{switch} = !{switch}
}}
""".format(
freq=sampling_frequency,
stopwatch=STOPWATCH_ON,
switch=TIMED_SWITCH
)
handle.write(timer_probe)
def _add_program_probes(handle, probes, verbose_trace, timed_sampling):
""" Add function and USDT probe definitions to the script.
:param TextIO handle: the script file handle
:param Probes probes: the Probes configuration
:param bool verbose_trace: the verbosity level of the data output
:param bool timed_sampling: specifies whether timed sampling is on or off
"""
# Obtain the distinct set of function and usdt probes
sampled_func, nonsampled_func = probes.get_partitioned_func_probes()
sampled_usdt, nonsampled_usdt, single_usdt = probes.get_partitioned_usdt_probes()
# Pre-build events and handlers based on the probe sets
prebuilt = {
'e': {
'sampled_func': _build_func_events(sampled_func, timed_sampling),
'sampled_usdt': _build_usdt_events(sampled_usdt),
'sampled_usdt_exit': _build_usdt_events(sampled_usdt, 'pair'),
'nonsampled_func': _build_func_events(nonsampled_func, timed_sampling),
'nonsampled_usdt': _build_usdt_events(nonsampled_usdt),
'nonsampled_usdt_exit': _build_usdt_events(nonsampled_usdt, 'pair'),
'single_usdt': _build_usdt_events(single_usdt)
},
'h': {
'func_begin': _build_probe_body(RecordType.FUNC_BEGIN, verbose_trace),
'func_exit': _build_probe_body(RecordType.FUNC_END, verbose_trace),
'usdt_begin': _build_probe_body(RecordType.USDT_BEGIN, verbose_trace),
'usdt_exit': _build_probe_body(RecordType.USDT_END, verbose_trace),
'usdt_single': _build_probe_body(RecordType.USDT_SINGLE, verbose_trace)
}
}
# Create pairs of events-handlers to add to the script
# Nonsampled: function entry, function exit, USDT entry, USDT exit
# Sampled: function entry, function exit, USDT entry, USDT exit
# Single: USDT single
specification = [
(prebuilt['e']['nonsampled_func'].format(suffix='.call?'),
prebuilt['h']['func_begin']),
(prebuilt['e']['nonsampled_func'].format(suffix='.return?'),
prebuilt['h']['func_exit']),
(prebuilt['e']['nonsampled_usdt'],
prebuilt['h']['usdt_begin']),
(prebuilt['e']['nonsampled_usdt_exit'],
prebuilt['h']['usdt_exit']),
(prebuilt['e']['single_usdt'],
prebuilt['h']['usdt_single']),
(prebuilt['e']['sampled_func'].format(suffix='.call?'),
ENTRY_APPROX_SAMPLE_TEMPLATE.format(probe_handler=prebuilt['h']['func_begin'])),
(prebuilt['e']['sampled_func'].format(suffix='.return?'),
EXIT_APPROX_SAMPLE_TEMPLATE.format(probe_handler=prebuilt['h']['func_exit'])),
(prebuilt['e']['sampled_usdt'],
ENTRY_APPROX_SAMPLE_TEMPLATE.format(probe_handler=prebuilt['h']['usdt_begin'])),
(prebuilt['e']['sampled_usdt_exit'],
EXIT_APPROX_SAMPLE_TEMPLATE.format(probe_handler=prebuilt['h']['usdt_exit'])),
]
for spec_event, spec_handler in specification:
# Add the new events + handler only if there are some associated events
if spec_event:
probe = PROBE_TEMPLATE.format(probe_events=spec_event, probe_handler=spec_handler)
handle.write(probe)
def _build_array_declaration(probes, verbose_trace, max_threads):
""" Build only the array declarations necessary for the given script, i.e.,
create / omit probe ID mapping array based on the verbosity
create / omit sampling arrays based on the presence / absence of sampled probes, etc.
:param Probes probes: the Probes object
:param bool verbose_trace: the verbosity level of the output
:param int max_threads: maximum number of expected simultaneous threads
:return str: the built array declaration string
"""
# Currently three types of arrays
id_array = '# ID array omitted'
sampling_arrays = '# Sampling arrays omitted'
recursion_arrays = '# Recursion arrays omitted'
# Verbose mode controls the ID array
if not verbose_trace:
id_array = 'global {}[{}]'.format(ARRAY_PROBE_ID, probes.total_probes_len())
# Sampled probes control the presence of sampling arrays
if probes.sampled_probes_len() > 0:
array_size = probes.sampled_probes_len()
max_array_size = array_size * max_threads
max_array_size = max_array_size if max_array_size > MAX_MAP_ENTRIES else MAX_MAP_ENTRIES
sampling_arrays = ARRAYS_SAMPLING_TEMPLATE.format(size=array_size, max_size=max_array_size)
# TODO: Recursion sampling switch on / off
return ARRAYS_TEMPLATE.format(
id_array=id_array,
sampling_arrays=sampling_arrays,
recursion_arrays=recursion_arrays
)
def _array_assign(arr_id, arr_idx, arr_value):
return f' {arr_id}["{arr_idx}"] = {arr_value}\n'
def _build_id_init(probes, verbose_trace):
""" Build the probe name -> ID mapping initialization code
:param Probes probes: the Probes object
:param bool verbose_trace: the verbosity level of the output
:return str: the built ID array initialization code
"""
# The name -> ID mapping is not used in verbose mode
if verbose_trace:
return ' # Probe name -> Probe ID is not used in verbose mode\n'
# For each probe, map the name to the probe ID for compact output
init_string = ' # Probe name -> Probe ID\n'
for probe in probes.get_probes():
init_string += _array_assign(ARRAY_PROBE_ID, probe['name'], probe['id'])
return init_string
def _build_sampling_init(probes):
""" Build the sampling arrays initialization code
:param Probes probes: the Probes object
:return str: the built sampling array initialization code
"""
# The threshold array contains the sampling values for each function
# When the threshold is reached, the probe generates a data record
threshold_string = ' # Probe name -> Probe sampling threshold\n'
# Generate the initialization code for both the function and USDT sampled probes
for probe in probes.get_sampled_probes():
threshold_string += _array_assign(ARRAY_SAMPLE_THRESHOLD, probe['name'], probe['sample'])
return threshold_string
def _build_probe_body(probe_type, verbose_trace):
""" Build the probe innermost body.
:param RecordType probe_type: the probe type
:param bool verbose_trace: the verbosity level of the data output
:return str: the probe handler code
"""
# Set how the probe will be identified in the output and how we obtain the identification
# based on the trace verbosity
id_t, id_get = ('%s', 'pname') if verbose_trace else ('%d', '{}[pname]'.format(ARRAY_PROBE_ID))
# Format the template for the required probe type
return HANDLER_TEMPLATE.format(
type=int(probe_type), id_type=id_t, id_get=id_get, timestamp=STOPWATCH_NAME
)
def _build_func_events(probe_iter, timed_sampling):
""" Build function probe events code, which is basically a list of events that share some
common handler.
:param iter probe_iter: iterator of probe configurations
:param bool timed_sampling: specifies whether Timed Sampling is on or off
:return str: the built probe events code
"""
def timed_switch(func_name):
return ' if ({})'.format(TIMED_SWITCH) if timed_sampling and func_name != 'main' else ''
return ',\n '.join(
FUNC_EVENT_TEMPLATE.format(binary=prb['lib'], name=prb['name'],
timed_switch=timed_switch(prb['name']))
for prb in probe_iter
)
def _build_usdt_events(probe_iter, probe_id='name'):
""" Build USDT probe events code, which is basically a list of events that share some
common handler.
:param iter probe_iter: iterator of probe configurations
:return str: the built probe events code
"""
return ',\n '.join(
USDT_EVENT_TEMPLATE.format(binary=prb['lib'], loc=prb[probe_id]) for prb in probe_iter
)
def _id_type_value(value_set, verbose_trace):
""" Select the type and value of printed data based on the verbosity level of the output.
:param tuple value_set: a set of nonverbose / verbose data output
:param bool verbose_trace: the verbosity level of the output
:return tuple (str, str): the 'type' and 'value' objects for the print statement
"""
if verbose_trace:
return '%s', value_set[1]
return '%d', value_set[0]
| gpl-3.0 |
Philomelos/xml2ly | music_data/key_signature.py | 1583 | def KeySignatureTonicPitch(mode):
from music_data.pitch import LilyPitch
modes = {
'major' : (0, 0), # (step, alteration)
'minor' : (5, 0),
'ionian' : (0, 0),
'dorian' : (1, 0),
'phrygian' : (2, 0),
'lydian' : (3, 0),
'mixolydian': (4, 0),
'aeolian' : (5, 0),
'locrian' : (6, 0),
}
result = modes.get(mode, None)
if result:
step = result[0]
pitch = LilyPitch(step=step, alteration=0, octave=0)
return pitch
class KeySignatureMixin(object):
@property
def has_non_standard_key(self):
# TODO: non-standard keys
return self.non_standard_key is not None
@property
def tonic(self):
from music_data.pitch import LilyPitch
if self.mode and self.fifths:
fifths = self.fifths # copy to avoid overwriting when reading
# value multiple times.
tonic = KeySignatureTonicPitch(self.mode)
transposer = LilyPitch(step=4)
if fifths < 0:
fifths *= -1
transposer.step *= -1
transposer.normalize()
for x in range(fifths):
tonic = tonic.transposed(transposer)
tonic.normalize()
return tonic
@property
def lilypond_format(self):
from music_data.pitch import LilyPitch
a = self.tonic
if a:
return '\\key %s \\%s' % (a.ly_step_expression(), self.mode)
else:
return ''
| gpl-3.0 |
andrewtikhonov/RCloud | rcloud-bench/src/main/java/workbench/views/benchlogviewer/LogViewerMouseAdapter.java | 2681 | /*
* R Cloud - R-based Cloud Platform for Computational Research
* at EMBL-EBI (European Bioinformatics Institute)
*
* Copyright (C) 2007-2015 European Bioinformatics Institute
* Copyright (C) 2009-2015 Andrew Tikhonov - [email protected]
* Copyright (C) 2007-2009 Karim Chine - [email protected]
*
* 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 workbench.views.benchlogviewer;
import uk.ac.ebi.rcloud.common.util.ImageLoader;
import workbench.RGui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by IntelliJ IDEA.
* User: andrew
* Date: Feb 5, 2010
* Time: 3:51:55 PM
* To change this template use File | Settings | File Templates.
*/
public class LogViewerMouseAdapter extends MouseAdapter {
private JTextPane logarea;
private RGui rgui;
public LogViewerMouseAdapter(RGui rgui, JTextPane logarea){
this.logarea = logarea;
this.rgui = rgui;
}
public void mousePressed(MouseEvent event) {
checkPopup(event);
}
public void mouseClicked(MouseEvent event) {
checkPopup(event);
}
public void mouseReleased(MouseEvent event) {
checkPopup(event);
}
private void checkPopup(MouseEvent event) {
if (event.isPopupTrigger()) {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem cleanItem = new JMenuItem();
cleanItem.setAction(new AbstractAction("Clear") {
public void actionPerformed(ActionEvent e) {
rgui.getLogContainer().clearLog();
logarea.setText("");
}
public boolean isEnabled() {
return !logarea.getText().equals("");
}
});
cleanItem.setIcon(new ImageIcon(
ImageLoader.load("/views/images/logviewer/edit-clear.png")));
popupMenu.add(cleanItem);
popupMenu.show(logarea, event.getX(), event.getY());
}
}
}
| gpl-3.0 |
atheerabed/gnash-fork | libcore/asobj/flash/display/JointStyle_as.cpp | 1645 | // JointStyle_as.cpp: ActionScript "JointStyle" class, for Gnash.
//
// Copyright (C) 2009, 2010 Free Software Foundation, Inc.
//
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "display/JointStyle_as.h"
#include "log.h"
#include "fn_call.h"
#include "Global_as.h"
#include "smart_ptr.h" // for boost intrusive_ptr
#include "builtin_function.h"
/// The flash.display.JointStyle class is AS3 only. It enumerates
/// constants for use in other classes.
namespace gnash {
// Forward declarations
namespace {
void attachJointStyleStaticInterface(as_object& o);
}
// extern (used by Global.cpp)
void
jointstyle_class_init(as_object& where, const ObjectURI& uri)
{
registerBuiltinObject(where, attachJointStyleStaticInterface, uri);
}
namespace {
void
attachJointStyleStaticInterface(as_object& /*o*/)
{
// TODO: add constants here.
}
} // anonymous namespace
} // gnash namespace
// local Variables:
// mode: C++
// indent-tabs-mode: t
// End:
| gpl-3.0 |
kevoree-modeling/framework | microframework/src/test/java/org/kevoree/modeling/memory/space/impl/OffHeapChunkSpaceCleanerTest.java | 578 | package org.kevoree.modeling.memory.space.impl;
import org.kevoree.modeling.memory.manager.DataManagerBuilder;
import org.kevoree.modeling.memory.manager.KDataManager;
import org.kevoree.modeling.memory.space.BaseKChunkSpaceCleanerTest;
import org.kevoree.modeling.memory.space.impl.press.PressOffHeapChunkSpace;
/**
* @ignore ts
*/
public class OffHeapChunkSpaceCleanerTest extends BaseKChunkSpaceCleanerTest {
@Override
public KDataManager createDataManager() {
return new DataManagerBuilder().withSpace(new PressOffHeapChunkSpace(1000)).build();
}
}
| gpl-3.0 |
msdevstep/subroute.io | Subroute.Api/Models/RoutePackages/RoutePackageResponse.cs | 951 | using System;
using System.Linq.Expressions;
using Subroute.Api.Models.Routes;
using Subroute.Core.Data;
namespace Subroute.Api.Models.RoutePackages
{
public class RoutePackageResponse
{
public string Id { get; set; }
public string Version { get; set; }
public DateTimeOffset UpdatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTimeOffset CreatedOn { get; set; }
public string CreatedBy { get; set; }
public static Expression<Func<RoutePackage, RoutePackageResponse>> Projection = r => r == null ? null : new RoutePackageResponse
{
Id = r.Id,
Version = r.Version,
CreatedBy = r.CreatedBy,
CreatedOn = r.CreatedOn,
UpdatedBy = r.UpdatedBy,
UpdatedOn = r.UpdatedOn
};
public static Func<RoutePackage, RoutePackageResponse> Map = Projection.Compile();
}
} | gpl-3.0 |
GetSimpleCMS/GetSimpleCMS | admin/inc/security_functions.php | 11497 | <?php if(!defined('IN_GS')){ die('you cannot load this page directly.'); }
/**
* Security
*
* @package GetSimple
* @subpackage Security-Functions
*/
/*
* File and File MIME-TYPE Blacklist arrays
*/
$mime_type_blacklist = array(
# HTML may contain cookie-stealing JavaScript and web bugs
'text/html', 'text/javascript', 'text/x-javascript', 'application/x-shellscript',
# PHP scripts may execute arbitrary code on the server
'application/x-php', 'text/x-php', 'application/php', 'application/x-httpd-php', 'application/x-httpd-php-source',
# Other types that may be interpreted by some servers
'text/x-python', 'text/x-perl', 'text/x-bash', 'text/x-sh', 'text/x-csh',
# Client-side hazards on Internet Explorer
'text/scriptlet', 'application/x-msdownload',
# Windows metafile, client-side vulnerability on some systems
'application/x-msmetafile',
# MS Office OpenXML and other Open Package Conventions files are zip files
# and thus blacklisted just as other zip files
'application/x-opc+zip'
);
$file_ext_blacklist = array(
# HTML may contain cookie-stealing JavaScript and web bugs
'html', 'htm', 'js', 'jsb', 'mhtml', 'mht',
# PHP scripts may execute arbitrary code on the server
'php', 'pht', 'phtm', 'phtml', 'php3', 'php4', 'php5', 'ph3', 'ph4', 'ph5', 'phps', 'phar', 'php7', 'php8',
# Other types that may be interpreted by some servers
'shtml', 'jhtml', 'pl', 'py', 'cgi', 'sh', 'ksh', 'bsh', 'c', 'htaccess', 'htpasswd',
# May contain harmful executables for Windows victims
'exe', 'scr', 'dll', 'msi', 'vbs', 'bat', 'com', 'pif', 'cmd', 'vxd', 'cpl'
);
/**
* Anti-XSS
*
* Attempts to clean variables from XSS attacks
* @since 2.03
*
* @author Martijn van der Ven
*
* @param string $str The string to be stripped of XSS attempts
* @return string
*/
function antixss($str){
$strdirty = $str;
// attributes blacklist:
$attr = array('style','on[a-z]+');
// elements blacklist:
$elem = array('script','iframe','embed','object');
// extermination:
$str = preg_replace('#<!--.*?-->?#', '', $str);
$str = preg_replace('#<!--#', '', $str);
$str = preg_replace('#(<[a-z]+(\s+[a-z][a-z\-]+\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*))*)\s+href\s*=\s*(\'javascript:[^\']*\'|"javascript:[^"]*"|javascript:[^\s>]*)((\s+[a-z][a-z\-]*\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*))*\s*>)#is', '$1$5', $str);
foreach($attr as $a) {
$regex = '(<[a-z]+(\s+[a-z][a-z\-]+\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*))*)\s+'.$a.'\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*)((\s+[a-z][a-z\-]*\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*))*\s*>)';
$str = preg_replace('#'.$regex.'#is', '$1$5', $str);
}
foreach($elem as $e) {
$regex = '<'.$e.'(\s+[a-z][a-z\-]*\s*=\s*(\'[^\']*\'|"[^"]*"|[^\'">][^\s>]*))*\s*>.*?<\/'.$e.'\s*>';
$str = preg_replace('#'.$regex.'#is', '', $str);
}
// if($strdirty !== $str) debugLog("string cleaned: removed ". (strlen($strdirty) - strlen($str)) .' chars');
return $str;
}
function xss_clean($data){
$datadirty = $data;
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'/])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
do
{
// Remove really unwanted tags
$old_data = $data;
$data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);
// we are done...
// if($datadirty !== $data) debugLog("string cleaned: removed ". (strlen($datadirty) - strlen($data)) .' chars');
return $data;
}
/**
* check for csrfs
* @param string $action action to pass to check_nonce
* @param string $file file to pass to check_nonce
* @param bool $die if false return instead of die
* @return bool returns true if csrf check fails
*/
function check_for_csrf($action, $file="", $die = true){
// check for csrf
if (!getDef('GSNOCSRF',true)) {
$nonce = $_REQUEST['nonce'];
if(!check_nonce($nonce, $action, $file)) {
exec_action('csrf'); // @hook csrf a csrf was detected
if(requestIsAjax()){
$error = i18n_r("CSRF","CRSF Detected!");
echo "<div>"; // jquery bug will not parse 1 html element so we wrap it
include('template/error_checking.php');
echo "</div>";
die();
}
if($die) die(i18n_r("CSRF","CRSF Detected!"));
return true;
}
}
}
/**
* Get Nonce
*
* @since 2.03
* @author tankmiche
* @uses $USR
* @uses $SALT
*
* @param string $action Id of current page
* @param string $file Optional, default is empty string
* @param bool $last
* @return string
*/
function get_nonce($action, $file = "", $last = false) {
global $USR;
global $SALT;
// set nonce_timeout default and clamps
include_once(GSADMININCPATH.'configuration.php');
clamp($nonce_timeout, 60, 86400, 3600);// min, max, default in seconds
// $nonce_timeout = 10;
if($file == "")
$file = getScriptFile();
// using user agent since ip can change on proxys
$uid = $_SERVER['HTTP_USER_AGENT'];
// set nonce time domain to $nonce_timeout or $nonce_timeout x 2 when last is $true
$time = $last ? time() - $nonce_timeout: time();
$time = floor($time/$nonce_timeout);
// Mix with a little salt
$hash=sha1($action.$file.$uid.$USR.$SALT.$time);
return $hash;
}
/**
* Check Nonce
*
* @since 2.03
* @author tankmiche
* @uses get_nonce
*
* @param string $nonce
* @param string $action
* @param string $file Optional, default is empty string
* @return bool
*/
function check_nonce($nonce, $action, $file = ""){
return ( $nonce === get_nonce($action, $file) || $nonce === get_nonce($action, $file, true) );
}
/**
* Validate Safe File
* NEVER USE MIME CHECKING FROM BROWSERS, eg. $_FILES['userfile']['type'] cannot be trusted
* @since 3.1
* @uses file_mime_type
* @uses $mime_type_blacklist
* @uses $file_ext_blacklist
*
* @param string $file, absolute path
* @param string $name, filename
* @param string $mime, optional
* @return bool
*/
function validate_safe_file($file, $name, $mime = null){
global $mime_type_blacklist, $file_ext_blacklist, $mime_type_whitelist, $file_ext_whitelist;
include(GSADMININCPATH.'configuration.php');
$file_extension = lowercase(pathinfo($name,PATHINFO_EXTENSION));
if ($mime && $mime_type_whitelist && in_arrayi($mime, $mime_type_whitelist)) {
return true;
}
if ($file_ext_whitelist && in_arrayi($file_extension, $file_ext_whitelist)) {
return true;
}
// skip blackist checks if whitelists exist
if($mime_type_whitelist || $file_ext_whitelist) return false;
if ($mime && in_arrayi($mime, $mime_type_blacklist)) {
return false;
} elseif (in_arrayi($file_extension, $file_ext_blacklist)) {
return false;
} else {
return true;
}
}
/**
* Checks that an existing filepath is safe to use by checking canonicalized absolute pathname.
* If file does not exist and realpath fails, we realpath dirname() instead
*
* @since 3.1.3
*
* @param string $filepath Unknown Path to file to check for safety
* @param string $pathmatch Known Path to parent folder to check against
* @param bool $subdir allow path to be a deeper subfolder
* @param bool $newfile if true fallback and realpath basename, caution, use with other filename sanitizers
* @return bool Returns true if files path resolves to your known path
*/
function filepath_is_safe($filepath, $pathmatch, $subdir = true, $newfile = false){
$realpath = realpath($filepath);
if(!$realpath && $newfile) return path_is_safe(dirname($filepath),$pathmatch,$subdir);
$realpathmatch = realpath($pathmatch);
if($subdir) return strpos(dirname($realpath),$realpathmatch) === 0;
return dirname($realpath) == $realpathmatch;
}
/**
* Checks that an existing path is safe to use by checking canonicalized absolute path
*
* @since 3.1.3
*
* @param string $path Unknown Path to check for safety
* @param string $pathmatch Known Path to check against
* @param bool $subdir allow path to be a deeper subfolder
* @return bool Returns true if $path is direct subfolder of $pathmatch
*
*/
function path_is_safe($path,$pathmatch,$subdir = true){
$realpath = realpath($path);
$realpathmatch = realpath($pathmatch);
if($subdir) return strpos($realpath,$realpathmatch) === 0;
return $realpath == $realpathmatch;
}
// alias to check a subdir easily
function subpath_is_safe($path,$dir){
return path_is_safe($path.$dir,$path);
}
/**
* Check if server is Apache
*
* @returns bool
*/
function server_is_apache() {
return( strpos(strtolower(get_Server_Software()),'apache') !== false );
}
/**
* Try to get server_software
*
* @returns string
*/
function get_Server_Software() {
return $_SERVER['SERVER_SOFTWARE'];
}
/**
* Performs filtering on variable, falls back to htmlentities
*
* @since 3.3.0
* @param string $var var to filter
* @param string $filter filter type
* @return string return filtered string
*/
function var_out($var,$filter = "special"){
// php 5.2 shim
if(!defined('FILTER_SANITIZE_FULL_SPECIAL_CHARS')){
define('FILTER_SANITIZE_FULL_SPECIAL_CHARS',522);
if($filter == "full") return htmlspecialchars($var, ENT_QUOTES);
}
if(function_exists( "filter_var") ){
$aryFilter = array(
"string" => FILTER_SANITIZE_STRING,
"int" => FILTER_SANITIZE_NUMBER_INT,
"float" => FILTER_SANITIZE_NUMBER_FLOAT,
"url" => FILTER_SANITIZE_URL,
"email" => FILTER_SANITIZE_EMAIL,
"special" => FILTER_SANITIZE_SPECIAL_CHARS,
);
if(isset($aryFilter[$filter])) return filter_var( $var, $aryFilter[$filter]);
return filter_var( $var, FILTER_SANITIZE_SPECIAL_CHARS);
}
else {
return htmlentities($var);
}
}
//alias var_out for inputs in case we ned to diverge in future
function var_in($var,$filter = 'special'){
return var_out($var,$filter);
}
function validImageFilename($file){
$image_exts = array('jpg','jpeg','gif','png');
return in_array(getFileExtension($file),$image_exts);
}
/* ?> */
| gpl-3.0 |
tracktopell/jpa-builder | src/main/java/com/tracktopell/dao/builder/ejb3/VPModel2JPA.java | 2644 | package com.tracktopell.dao.builder.ejb3;
import com.tracktopell.dao.builder.metadata.DBTableSet;
import com.tracktopell.dao.builder.parser.VP6Parser;
import com.tracktopell.dao.builder.parser.VPModel;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Hashtable;
/**
* com.tracktopell.dao.builder.ejb3.VPModel2JPA
*/
public class VPModel2JPA {
public static void main(String[] args) {
String pathToVPProject = null;
String schemmaName = null;
String packageBeanMember= null;
String basePath = null;
String[]tableNames2Gen = null;
String fetchType = null;
try {
if( args.length < 5 || args.length > 6) {
System.err.println("bad args:"+Arrays.asList(args));
System.err.println("use: <java ...> com.tracktopell.dao.builder.ejb3.VPModel2JPA pathToVPProject schemmaName packageBeanMember basePath tableNames2GenList,Separated,By,Comma [FETCHTYPE_LAZY|FETCHTYPE_EAGER]" );
System.exit(1);
}
pathToVPProject = args[0];
schemmaName = args[1];
packageBeanMember= args[2];
basePath = args[3];
tableNames2Gen = args[4].split(",");
if(args.length == 6){
fetchType = args[5];
if(fetchType.equals(EJB3Builder.FETCHTYPE_LAZY)){
EJB3Builder.setDefaultValueFetchType_LAZY();
System.out.println("==>>NOW FETCHTYPE_LAZY !");
} else if(fetchType.equals(EJB3Builder.FETCHTYPE_EAGER)){
EJB3Builder.setDefaultValueFetchType_EAGER();
System.out.println("==>>NOW FETCHTYPE_EAGER !");
}
}
Hashtable<String, VPModel> vpModels;
vpModels = VP6Parser.loadVPModels(new FileInputStream(pathToVPProject));
//System.err.println("DBBuilderFactory ->vpModels=" + vpModels);
DBTableSet dbSet;
dbSet = VP6Parser.loadFromXMLWithVPModels(new FileInputStream(pathToVPProject), vpModels);
if(!tableNames2Gen[0].equals("{all}")){
dbSet = dbSet.copyJustSelectedNames(tableNames2Gen);
}
//System.err.println("====================== END PARSE XML ========================");
//System.err.println("->" + dbSet);
EJB3Builder.buildMappingBeans(dbSet, schemmaName, packageBeanMember, basePath);
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(2);
}
}
}
| gpl-3.0 |
cabrera-dcc/agnes_bts | index.php | 10925 | <?php
require_once("tickets/start.php");
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="application-name" content="Agnes"/>
<meta name="description" content="Sistema de Seguimiento de Errores"/>
<meta name="author" content="Daniel Cabrera Cebrero (http://cabrera-dcc.github.io)"/>
<meta name="version" content="Beta-1 (rev. 20150407)"/>
<meta name="keywords" content="bts, bug, incident, traking, ticket"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Agnes | BTS</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"/>
<link rel="stylesheet" type="text/css" href="css/agnes-default.css"/>
</head>
<body>
<nav class="navbar navbar-inverse navbar-static-top small text-uppercase">
<div class="container-fluid">
<a class="navbar-brand" target="_blank" rel="alternate" hreflang="en" type="text/html" href="https://github.com/cabrera-dcc/agnes_bts"><strong>Agnes</strong></a>
<p id="nav-description" class="navbar-text navbar-right"><small>Un sencillo</small> Sistema de Seguimiento de Incidencias</p>
</div>
</nav>
<main class="container-fluid">
<section id="form-section" class="col-md-4 col-lg-3">
<form class="small" action="<?php echo $action ?>" method="post">
<div class="form-group col-sm-12">
<label for="inputTitle" class="control-label text-uppercase">Título</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pushpin"></span></span>
<input name="nombre" type="text" class="form-control input-sm" id="inputTitle" maxlength="100" disabled="disabled" placeholder="Nombre del ticket (4-100 caracteres)" value="<?php if($load==true){load_data("name");}?>" required/>
</div>
</div>
<div class="form-group col-sm-6">
<label for="inputPriority" class="control-label text-uppercase">Prioridad</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-exclamation-sign"></span></span>
<select class="form-control input-sm" name="prioridad" id="inputPriority" disabled="disabled" value="<?php if($load==true){load_data("priority");}?>">
<option value="Normal">Normal</option>
<option value="Baja">Baja</option>
<option value="Alta">Alta</option>
</select>
</div>
</div>
<div class="form-group col-sm-6">
<label for="inputRef" class="control-label text-uppercase">Referencia</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-certificate"></span></span>
<input name="reference" type="text" class="form-control input-sm" id="inputRef" placeholder="#" disabled="disabled" value="<?php if($load==true){load_data("ref");}?>" required/>
</div>
</div>
<div class="form-group col-sm-6 col-md-12">
<label for="inputTarget" class="control-label text-uppercase">Asignatario</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input name="asignatario" type="text" class="form-control input-sm" id="inputDesignate" maxlength="100" disabled="disabled" placeholder="Asignado a... (4-100 caracteres)" value="<?php if($load==true){load_data("designate");}?>" required/>
</div>
</div>
<div class="form-group col-sm-6 col-md-12">
<label for="inputBoss" class="control-label text-uppercase">Responsable</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input name="responsable" type="text" class="form-control input-sm" id="inputSupervisor" maxlength="100" disabled="disabled" placeholder="Asignado por... (4-100 caracteres)" value="<?php if($load==true){load_data("supervisor");}?>" required/>
</div>
</div>
<div class="form-group col-sm-6 col-md-12">
<label for="areaDescription" class="control-label text-uppercase">Descripción</label>
<textarea name="descripcion" class="form-control input-sm" rows="3" id="areaDescription" maxlength="255" disabled="disabled" placeholder="Descripción del ticket (4-255 caracteres)" required><?php if($load==true){load_data("description");}?></textarea>
</div>
<div class="form-group col-sm-6 col-md-12">
<label for="areaObservations" class="control-label text-uppercase">Observaciones</label>
<textarea name="observaciones" class="form-control input-sm" rows="3" id="areaObservations" maxlength="255" disabled="disabled" placeholder="Observaciones (hasta 255 caracteres)"><?php if($load==true){load_data("observations");}?></textarea>
</div>
<div class="form-group container-fluid">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group btn-group-xs" role="group">
<button id="new" type="button" class="btn btn-default"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> <small>Nuevo</small></button>
</div>
<div class="btn-group btn-group-xs" role="group">
<button name="btn-create" id="create" type="submit" class="btn btn-default" disabled="disabled"><span class="glyphicon glyphicon-save" aria-hidden="true"></span> <small>Crear</small></button>
</div>
<div class="btn-group btn-group-xs" role="group">
<button id="cancel" type="button" class="btn btn-default" disabled="disabled"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> <small>Cancelar</small></button>
</div>
<div class="btn-group btn-group-xs" role="group">
<button name="btn-save" id="save" type="submit" class="btn btn-default" disabled="disabled"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <small>Guardar</small></button>
</div>
</div>
</div>
</form>
</section>
<section class="col-md-8 col-lg-9">
<div id="filters" class="btn-group btn-group-xs" role="group">
<a role="button" class="btn btn-default" href="index.php?filter=all"><span class="glyphicon glyphicon-list-alt"></span> <small>Ver todo</small></a>
<div class="btn-group btn-group-xs" role="group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="glyphicon glyphicon-filter"></span> <small>Por estado</small>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li class="small"><a href="index.php?filter=pending"><span class="glyphicon glyphicon-inbox"></span> Pendiente</a></li>
<li class="small"><a href="index.php?filter=progress"><span class="glyphicon glyphicon-play-circle"></span> Progreso</a></li>
<li class="small"><a href="index.php?filter=completed"><span class="glyphicon glyphicon-ok"></span> Completado</a></li>
</ul>
</div>
<div class="btn-group btn-group-xs" role="group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="glyphicon glyphicon-filter"></span> <small>Por prioridad</small>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li class="small"><a href="index.php?filter=low"><span class="glyphicon glyphicon-star"></span><span class="glyphicon glyphicon-star-empty"></span><span class="glyphicon glyphicon-star-empty"></span> Baja </a></li>
<li class="small"><a href="index.php?filter=normal"><span class="glyphicon glyphicon-star"></span><span class="glyphicon glyphicon-star"></span><span class="glyphicon glyphicon-star-empty"></span> Normal</a></li>
<li class="small"><a href="index.php?filter=high"><span class="glyphicon glyphicon-star"></span><span class="glyphicon glyphicon-star"></span><span class="glyphicon glyphicon-star"></span> Alta</a></li>
</ul>
</div>
<div class="btn-group btn-group-xs" role="group">
<a role="button" class="btn btn-default" href="index.php"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> <small>Reiniciar filtros</small></a>
</div>
</div>
<div class="panel panel-default small">
<div class="panel-heading"><span class="glyphicon glyphicon-tasks" aria-hidden="true"></span> <strong>Tickets</strong></div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<tr>
<th><span class="glyphicon glyphicon-certificate" aria-hidden="true"></span></th>
<th>Título <span class="glyphicon glyphicon-pushpin" aria-hidden="true"></span></th>
<th>Estado <span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></th>
<th>Prioridad <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span></th>
<th>Asignado <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></th>
<th>Finalizado <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></th>
<th>Asignatario <span class="glyphicon glyphicon-user" aria-hidden="true"></span></th>
<th>Opciones <span class="glyphicon glyphicon-wrench" aria-hidden="true"></span></th>
</tr>
<?php check_filter(); ?>
</table>
</div>
</div>
</div>
</section>
</main>
<footer class="navbar navbar-default navbar-static-bottom small">
<div class="container-fluid">
<div class="row">
<p class="navbar-text"><abbr title="Sistema de Seguimiento de Errores AGNES" class="initialism"><strong>Agnes</abbr> © 2015 - <i>Bug Tracking System</i></strong></p>
<i><p class="navbar-text small">Software licensed by <a target="_blank" rel="author" hreflang="es" type="text/html" href="http://cabrera-dcc.github.io">Daniel Cabrera Cebrero</a> under a GNU General Public License (<a rel="license" target="blank" hreflang="en" type="text/html" href="https://github.com/cabrera-dcc/agnes_bts/blob/master/LICENSE">GPLv3</a>)</p>
<p class="navbar-text small">Design and theme under <a rel="license" target="_blank" hreflang="en" type="text/html" href="http://opensource.org/licenses/MIT">MIT License</a></p></i>
</div>
</div>
</footer>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.get-url-params.js"></script>
<script type="text/javascript" src="js/listener.js"></script>
</body>
</html> | gpl-3.0 |
itucsdb1601/itucsdb1601 | comments.py | 2950 | import json
import os
import psycopg2 as dbapi2
import re
from flask import Flask, request, render_template, redirect
from flask.helpers import url_for
app = Flask(__name__)
class comments:
def savecomment(config):
tweet_input = None
user_logname = None
comment = None
if request.method == 'POST':
tweet_input = request.form['tweetinput_text']
print(tweet_input)
user_logname = request.form['userlogname_text']
print(user_logname)
comment = request.form['comment_text']
print(comment)
with dbapi2.connect(config) as connection:
cursor = connection.cursor()
try:
query = """INSERT INTO comments (tweet_input, comment, user_logname) VALUES (%s, %s, %s)"""
cursor.execute(query, (tweet_input, comment , user_logname))
connection.commit();
return 'Your comment has been successfully posted <a href="http://localhost:5000">Home</a>'
except:
return 'Your comment cannot be added due to foreign key constraints! <a href="http://localhost:5000">Home</a>'
def comments_db(config):
with dbapi2.connect(config) as connection:
if request.method == 'GET':
cursor = connection.cursor()
query = "SELECT DISTINCT user_logname, tweet_input, comment from COMMENTS"
cursor.execute(query)
connection.commit();
return render_template('comments.html', comments_list=cursor)
def comments_db_delete(config, deletecomment):
with dbapi2.connect(config) as connection:
cursor = connection.cursor()
query = "DELETE FROM COMMENTS where user_logname = %s"
cursor.execute(query, (deletecomment,))
connection.commit();
return redirect(url_for('comments'))
def comments_db_update(config, updatecomment):
with dbapi2.connect(config) as connection:
cursor = connection.cursor()
query = """SELECT comment from comments where user_logname = '%s'""" % (updatecomment)
cursor.execute(query)
connection.commit();
return render_template('comments_update.html', comment_updates=cursor)
def comments_db_update_apply(config, updatecomment):
with dbapi2.connect(config) as connection:
cursor = connection.cursor()
try:
comment = request.form['comment_txt']
query = """UPDATE comments set comment ='%s' where user_logname = '%s'""" % (comment, updatecomment)
cursor.execute(query)
connection.commit();
return redirect(url_for('comments'))
except:
return 'Value cannot be NULL! <a href="http://localhost:5000">Home</a>'
| gpl-3.0 |
wolfidan/pycosmo | pycosmo/derived_vars.py | 8847 | #!/usr/bin/env python2
import numpy as np
# COSMO CONSTANTS
COSMO_R_D = 287.05
COSMO_R_V = 451.51
COSMO_RDV = COSMO_R_D / COSMO_R_V
COSMO_O_M_RDV = 1.0 - COSMO_RDV
COSMO_RVD_M_O = COSMO_R_V / COSMO_R_D - 1.0
DERIVED_VARS=['PREC_RATE','QV_v','QR_v','QS_v','QG_v','QC_v','QI_v','QH_v',
'QNR_v','QNS_v','QNG_v','QNC_v','QNI_v','QNH_v',
'LWC','TWC','IWC','RHO','N','Pw','RELHUM']
def get_derived_var(file_instance, varname, options):
derived_var=None
try:
if varname == 'PREC_RATE': # PRECIPITATION RATE
vars_to_get = ['PRR_GSP_GDS10_SFC','PRR_CON_GDS10_SFC','PRS_CON_GDS10_SFC','PRS_GSP_GDS10_SFC']
d = file_instance.get_variable(vars_to_get,**options)
derived_var=d['PRR_GSP_GDS10_SFC']+d['PRR_CON_GDS10_SFC']+\
d['PRS_CON_GDS10_SFC']+d['PRS_GSP_GDS10_SFC']
if 'PRG_GSP_GDS10_SFC' in file_instance.variables.keys(): # Check if graupel is present
derived_var += file_instance.get_variable('PRG_GSP_GDS10_SFC',**options)
if 'PRH_GSP_GDS10_SFC' in file_instance.variables.keys(): # Check if hail is present
derived_var += file_instance.get_variable('PRH_GSP_GDS10_SFC',**options)
derived_var.name='PREC_RATE'
derived_var.attributes['long_name']='precipitation intensity'
derived_var.attributes['units'] = 'mm/s'
elif varname == 'QV_v': # Water vapour mass density
d = file_instance.get_variable(['QV','RHO'],**options)
derived_var = d['QV']*d['RHO']
derived_var.name = 'QV_v'
derived_var.attributes['units'] = 'kg/m3'
derived_var.attributes['long_name'] = 'Water vapor mass density'
elif varname == 'QR_v': # Rain water mass density
d = file_instance.get_variable(['QR','RHO'],**options)
derived_var = d['QR']*d['RHO']
derived_var.name='QR_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Rain mass density'
elif varname == 'QS_v': # Snow water mass density
d = file_instance.get_variable(['QS','RHO'],**options)
derived_var=d['QS']*d['RHO']
derived_var.name='QS_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Snow mass density'
elif varname == 'QG_v': # Graupel water mass density
d = file_instance.get_variable(['QG','RHO'],**options)
derived_var=d['QG']*d['RHO']
derived_var.name='QG_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Graupel mass density'
elif varname == 'QC_v': # Cloud water mass density
d = file_instance.get_variable(['QC','RHO'],**options)
derived_var=d['QC']*d['RHO']
derived_var.name='QC_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Cloud mass density'
elif varname == 'QI_v': # Ice cloud water mass density
d = file_instance.get_variable(['QI','RHO'],**options)
derived_var=d['QI']*d['RHO']
derived_var.name='QI_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Ice crystals mass density'
elif varname == 'QH_v': # Hail water mass density
d = file_instance.get_variable(['QH','RHO'],**options)
derived_var=d['QH']*d['RHO']
derived_var.name='QH_v'
derived_var.attributes['units']='kg/m3'
derived_var.attributes['long_name']='Hail mass density'
elif varname == 'QNR_v': # Rain number density
d = file_instance.get_variable(['QNR','RHO'],**options)
derived_var=d['QNR']*d['RHO']
derived_var.name='QNR_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Rain number density'
elif varname == 'QNS_v': # Snow number density
d = file_instance.get_variable(['QNS','RHO'],**options)
derived_var=d['QNS']*d['RHO']
derived_var.name='QNS_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Snow number density'
elif varname == 'QNG_v': # Graupel number density
d = file_instance.get_variable(['QNG','RHO'],**options)
derived_var=d['QNG']*d['RHO']
derived_var.name='QNG_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Graupel number density'
elif varname == 'QNC_v': # Cloud number density
d = file_instance.get_variable(['QNC','RHO'],**options)
derived_var=d['QNC']*d['RHO']
derived_var.name='QNC_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Rain number density'
elif varname == 'QNI_v': # Ice cloud particles number density
d = file_instance.get_variable(['QNI','RHO'],**options)
derived_var=d['QNI']*d['RHO']
derived_var.name='QNI_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Ice crystals number density'
elif varname == 'QNH_v': # Hail number density
d = file_instance.get_variable(['QNH','RHO'],**options)
derived_var=d['QNH']*d['RHO']
derived_var.name='QNH_v'
derived_var.attributes['units']='m^-3'
derived_var.attributes['long_name']='Rain number density'
elif varname == 'LWC': # LIQUID WATER CONTENT
d = file_instance.get_variable(['QC','QR'],**options)
derived_var=d['QC']+d['QR']
derived_var=derived_var*100000
derived_var.name='LWC'
derived_var.attributes['units']='mg/kg'
derived_var.attributes['long_name']='Liquid water content'
elif varname == 'IWC': # ICE WATER CONTENT
d = file_instance.get_variable(['QG','QS','QI'],**options)
derived_var=d['QG']+d['QS']+d['QI']
derived_var=derived_var*100000
derived_var.name='IWC'
derived_var.attributes['units']='mg/kg'
derived_var.attributes['long_name']='Ice water content'
elif varname == 'TWC': # TOTAL WATER CONTENT
d = file_instance.get_variable(['QG','QS','QI','QC','QV','QR'],**options)
derived_var=d['QG']+d['QS']+d['QI']+d['QC']+d['QV']+d['QR']
derived_var=derived_var*100000
derived_var.name='TWC'
derived_var.attributes['long_name']='Total water content'
derived_var.attributes['units']='mg/kg'
elif varname == 'RHO': # AIR DENSITY
d = file_instance.get_variable(['P','T','QV','QR','QC','QI','QS','QG'],**options)
derived_var=d['P']/(d['T']*COSMO_R_D*((d['QV']*COSMO_RVD_M_O\
-d['QR']-d['QC']-d['QI']-d['QS']-d['QG'])+1.0))
derived_var.name='RHO'
derived_var.attributes['long_name']='Air density'
derived_var.attributes['units']='kg/m3'
elif varname == 'Pw': # Vapor pressure
d = file_instance.get_variable(['P','QV'],**options)
derived_var=(d['P']*d['QV'])/(d['QV']*(1-0.6357)+0.6357)
derived_var.attributes['long_name']='Vapor pressure'
derived_var.attributes['units']='Pa'
elif varname == 'RELHUM': # Vapor pressure
d = file_instance.get_variable(['Pw','T'],**options)
esat = 610.78*np.exp(17.2693882*(d['T'].data-273.16)/(d['T'].data-35.86)) # TODO
derived_var=d['Pw']/esat*100
derived_var.attributes['long_name']='Relative humidity'
derived_var.attributes['units']='%'
elif varname == 'N': # Refractivity
d = file_instance.get_variable(['T','Pw','P'],**options)
derived_var=(77.6/d['T'])*(0.01*d['P']+4810*(0.01*d['Pw'])/d['T'])
derived_var.attributes['long_name']='Refractivity'
derived_var.attributes['units']='-'
else:
raise ValueError('Could not compute derived variable, please specify a valid variable name')
except:
raise ValueError('Could not compute specified derived variable, check if all the necessary variables are in the input file_instance.')
return derived_var | gpl-3.0 |
bsidio/fuelapp | vendor/bundle/ruby/2.3.0/gems/redis-activesupport-5.0.1/lib/active_support/cache/redis_store.rb | 9495 | # encoding: UTF-8
require 'redis-store'
module ActiveSupport
module Cache
class RedisStore < Store
attr_reader :data
# Instantiate the store.
#
# Example:
# RedisStore.new
# # => host: localhost, port: 6379, db: 0
#
# RedisStore.new "example.com"
# # => host: example.com, port: 6379, db: 0
#
# RedisStore.new "example.com:23682"
# # => host: example.com, port: 23682, db: 0
#
# RedisStore.new "example.com:23682/1"
# # => host: example.com, port: 23682, db: 1
#
# RedisStore.new "example.com:23682/1/theplaylist"
# # => host: example.com, port: 23682, db: 1, namespace: theplaylist
#
# RedisStore.new "localhost:6379/0", "localhost:6380/0"
# # => instantiate a cluster
#
# RedisStore.new "localhost:6379/0", "localhost:6380/0", pool_size: 5, pool_timeout: 10
# # => use a ConnectionPool
#
# RedisStore.new "localhost:6379/0", "localhost:6380/0",
# pool: ::ConnectionPool.new(size: 1, timeout: 1) { ::Redis::Store::Factory.create("localhost:6379/0") })
# # => supply an existing connection pool (e.g. for use with redis-sentinel or redis-failover)
def initialize(*addresses)
@options = addresses.dup.extract_options!
@data = if @options[:pool]
raise "pool must be an instance of ConnectionPool" unless @options[:pool].is_a?(ConnectionPool)
@pooled = true
@options[:pool]
elsif [:pool_size, :pool_timeout].any? { |key| @options.has_key?(key) }
pool_options = {}
pool_options[:size] = options[:pool_size] if options[:pool_size]
pool_options[:timeout] = options[:pool_timeout] if options[:pool_timeout]
@pooled = true
::ConnectionPool.new(pool_options) { ::Redis::Store::Factory.create(*addresses) }
else
::Redis::Store::Factory.create(*addresses)
end
super(@options)
end
def write(name, value, options = nil)
options = merged_options(options)
instrument(:write, name, options) do |payload|
entry = options[:raw].present? ? value : Entry.new(value, options)
write_entry(normalize_key(name, options), entry, options)
end
end
# Delete objects for matched keys.
#
# Performance note: this operation can be dangerous for large production
# databases, as it uses the Redis "KEYS" command, which is O(N) over the
# total number of keys in the database. Users of large Redis caches should
# avoid this method.
#
# Example:
# cache.delete_matched "rab*"
def delete_matched(matcher, options = nil)
options = merged_options(options)
instrument(:delete_matched, matcher.inspect) do
matcher = key_matcher(matcher, options)
begin
with do |store|
!(keys = store.keys(matcher)).empty? && store.del(*keys)
end
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Redis::CannotConnectError
raise if raise_errors?
false
end
end
end
# Reads multiple keys from the cache using a single call to the
# servers for all keys. Options can be passed in the last argument.
#
# Example:
# cache.read_multi "rabbit", "white-rabbit"
# cache.read_multi "rabbit", "white-rabbit", :raw => true
def read_multi(*names)
return {} if names == []
options = names.extract_options!
keys = names.map{|name| normalize_key(name, options)}
values = with { |c| c.mget(*keys) }
values.map! { |v| v.is_a?(ActiveSupport::Cache::Entry) ? v.value : v }
# Remove the options hash before mapping keys to values
names.extract_options!
result = Hash[names.zip(values)]
result.reject!{ |k,v| v.nil? }
result
end
def fetch_multi(*names)
return {} if names == []
results = read_multi(*names)
options = names.extract_options!
fetched = {}
need_writes = {}
fetched = names.inject({}) do |memo, (name, _)|
memo[name] = results.fetch(name) do
value = yield name
need_writes[name] = value
value
end
memo
end
with do |c|
c.multi do
need_writes.each do |name, value|
write(name, value, options)
end
end
end
fetched
end
# Increment a key in the store.
#
# If the key doesn't exist it will be initialized on 0.
# If the key exist but it isn't a Fixnum it will be initialized on 0.
#
# Example:
# We have two objects in cache:
# counter # => 23
# rabbit # => #<Rabbit:0x5eee6c>
#
# cache.increment "counter"
# cache.read "counter", :raw => true # => "24"
#
# cache.increment "counter", 6
# cache.read "counter", :raw => true # => "30"
#
# cache.increment "a counter"
# cache.read "a counter", :raw => true # => "1"
#
# cache.increment "rabbit"
# cache.read "rabbit", :raw => true # => "1"
def increment(key, amount = 1, options = {})
options = merged_options(options)
instrument(:increment, key, :amount => amount) do
with{|c| c.incrby namespaced_key(key, options), amount}
end
end
# Decrement a key in the store
#
# If the key doesn't exist it will be initialized on 0.
# If the key exist but it isn't a Fixnum it will be initialized on 0.
#
# Example:
# We have two objects in cache:
# counter # => 23
# rabbit # => #<Rabbit:0x5eee6c>
#
# cache.decrement "counter"
# cache.read "counter", :raw => true # => "22"
#
# cache.decrement "counter", 2
# cache.read "counter", :raw => true # => "20"
#
# cache.decrement "a counter"
# cache.read "a counter", :raw => true # => "-1"
#
# cache.decrement "rabbit"
# cache.read "rabbit", :raw => true # => "-1"
def decrement(key, amount = 1, options = {})
options = merged_options(options)
instrument(:decrement, key, :amount => amount) do
with{|c| c.decrby namespaced_key(key, options), amount}
end
end
def expire(key, ttl)
options = merged_options(nil)
with { |c| c.expire namespaced_key(key, options), ttl }
end
# Clear all the data from the store.
def clear
instrument(:clear, nil, nil) do
with(&:flushdb)
end
end
# fixed problem with invalid exists? method
# https://github.com/rails/rails/commit/cad2c8f5791d5bd4af0f240d96e00bae76eabd2f
def exist?(name, options = nil)
res = super(name, options)
res || false
end
def stats
with(&:info)
end
def with(&block)
if defined?(@pooled) && @pooled
@data.with(&block)
else
block.call(@data)
end
end
def reconnect
@data.reconnect if @data.respond_to?(:reconnect)
end
protected
def write_entry(key, entry, options)
method = options && options[:unless_exist] ? :setnx : :set
with { |client| client.send method, key, entry, options }
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Redis::CannotConnectError
raise if raise_errors?
false
end
def read_entry(key, options)
entry = with { |c| c.get key, options }
if entry
entry.is_a?(ActiveSupport::Cache::Entry) ? entry : ActiveSupport::Cache::Entry.new(entry)
end
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Redis::CannotConnectError
raise if raise_errors?
nil
end
##
# Implement the ActiveSupport::Cache#delete_entry
#
# It's really needed and use
#
def delete_entry(key, options)
with { |c| c.del key }
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Redis::CannotConnectError
raise if raise_errors?
false
end
def raise_errors?
!!@options[:raise_errors]
end
# Add the namespace defined in the options to a pattern designed to match keys.
#
# This implementation is __different__ than ActiveSupport:
# __it doesn't accept Regular expressions__, because the Redis matcher is designed
# only for strings with wildcards.
def key_matcher(pattern, options)
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
if prefix
raise "Regexps aren't supported, please use string with wildcards." if pattern.is_a?(Regexp)
"#{prefix}:#{pattern}"
else
pattern
end
end
private
if ActiveSupport::VERSION::MAJOR < 5
def normalize_key(*args)
namespaced_key(*args)
end
end
end
end
end
| gpl-3.0 |
KoderKat/keyblade | src/ficwad-spider/ficwad1/ficwad1/pipelines.py | 3079 | # -*- coding: utf-8 -*-
#
# This code is based on the pipeline code written by Alex Black for the IMDB-spider project available at: https://github.com/alexwhb/IMDB-spider
# IMDB-spider is copyrighted by Alex Black: The MIT License (MIT) Copyright (c) 2014 Alex Black
from scrapy import log
import sqlite3 as sqlite
#BASE_DIR is the path to the data directory for storing all output files.
# recommendation: use the data directory in ficwad-spider-v1/data/
BASE_DIR = "/Users/KsComp/projects/keyblade/src/ficwad-spider-v1/data/"
class Ficwad1Pipeline(object):
def __init__(self):
# Possible we should be doing this in spider_open instead, but okay
self.connection = sqlite.connect(BASE_DIR + 'ficwad.db')
self.cursor = self.connection.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS ficwad (id INTEGER PRIMARY KEY, fandom VARCHAR(100), ' \
'url_fandom VARCHAR(200), ' \
'title VARCHAR(100), ' \
'url_title VARCHAR(200), ' \
'author VARCHAR(80), ' \
'url_author VARCHAR(200), ' \
'genre VARCHAR(100), ' \
'author_rating VARCHAR(80), ' \
'auto_rating VARCHAR(80), ' \
'wordcount VARCHAR(80), ' \
'numchapters VARCHAR(80))'
)
# Take the item and put it in database - do not allow duplicates
def process_item(self, item, spider):
self.cursor.execute("SELECT * FROM ficwad WHERE url_title=? AND url_author=?", (item['url_title'], item['url_author']))
result = self.cursor.fetchone()
if result:
#log.msg("Item already in database: %s" % item, level=log.DEBUG)
print ("MESSAGE: Item already in database: %s" % item)
else:
self.cursor.execute("""INSERT INTO ficwad (fandom, url_fandom, title, url_title, author, url_author, genre, author_rating, wordcount, numchapters) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
item['fandom'],
item['url_fandom'],
item['title'],
item['url_title'],
item['author'],
item['url_author'],
item['genre'],
item['author_rating'],
item['wc'],
item['numchs']
))
self.connection.commit()
#log.msg("Item stored : " % item, level=log.DEBUG)
print ("Item stored : " % item)
return item
def handle_error(self, e):
log.err(e)
| gpl-3.0 |
mariomka/ImpressPages-CMS | ip_cms/backend/cms.php | 13637 | <?php
/**
* @package ImpressPages
* @copyright Copyright (C) 2011 ImpressPages LTD.
* @license see ip_license.html
*/
namespace Backend;
if(!defined('BACKEND')) exit;
require (__DIR__.'/html_output.php');
require (__DIR__.'/session.php');
if (file_exists(BASE_DIR.CONFIG_DIR.'admin/template.php')) {
require_once(BASE_DIR.CONFIG_DIR.'admin/template.php');
} else {
require_once (__DIR__.'/template.php');
}
/**
* ImpressPages main administration area class
*
* Manages session, logins, rights, loads managemenet tools
*
* @package ImpressPages
*/
class Cms {
var $module; //current module object
var $session;
var $html; //html output object
var $tinyMce; //true if tinyMce engine is loaded
var $curModId;
var $loginError;
function __construct() {
$this->session = new Session();
$this->html = new HtmlOutput();
$this->module = null;
$this->tinyMce = false;
$this->curModId = null;
$this->loginError = null;
}
/**
* Output management tools
*
* @access public
* @return string Option
*/
function manage() {
global $parametersMod;
//log off
if(isset($_REQUEST['action']) && $_REQUEST['action'] == "logout" && !isset($_REQUEST['module_id']) && !(isset($_REQUEST['admin_module_group']) && isset($_REQUEST['admin_module_group']))) {
$this->session->logout();
$this->html->headerModules();
$this->html->html('<script type="text/javascript">window.top.location=\'admin.php\';</script>');
$this->deleteTmpFiles();
$this->html->footer();
$this->html->send();
\db::disconnect();
exit;
}
//eof log off
//log in
if(isset($_REQUEST['action']) && isset($_POST['f_name']) && isset($_POST['f_pass']) && $_REQUEST['action'] == "login" && !isset($_REQUEST['module_id'])) {
if(\Backend\Db::incorrectLoginCount($_POST['f_name'].'('.$_SERVER['REMOTE_ADDR'].')') > 2) {
$this->loginError = $parametersMod->getValue('standard', 'configuration', 'system_translations', 'login_suspended');
\Backend\Db::log('system', 'backend login suspended', $_POST['f_name'].'('.$_SERVER['REMOTE_ADDR'].')', 2);
}else {
$id = \Backend\Db::userId($_POST['f_name'], $_POST['f_pass']);
if($id !== false) {
$this->session->login($id);
\Backend\Db::log('system', 'backend login', $_POST['f_name'].' ('.$_SERVER['REMOTE_ADDR'].')', 0);
header("location:ip_backend_frames.php");
} else {
$this->loginError = $parametersMod->getValue('standard', 'configuration', 'system_translations', 'login_incorrect');
\Backend\Db::log('system', 'backend login incorrect', $_POST['f_name'].'('.$_SERVER['REMOTE_ADDR'].')', 1);
}
}
}
//eof log in
if($this->session->loggedIn()) { //login check
if (isset($_REQUEST['admin_module_group']) && $_REQUEST['admin_module_name']) {
$module = \Db::getModule(null, $_REQUEST['admin_module_group'], $_REQUEST['admin_module_name']);
if ($module) {
$_GET['module_id'] = $module['id'];
$_REQUEST['module_id'] = $module['id'];
}
}
//create module
if(isset($_GET['module_id']) && $_GET['module_id'] != '' && \Backend\Db::allowedModule($_GET['module_id'], $this->session->userId())) {
/*new module*/
$newModule = \Db::getModule($_GET['module_id']);
if ($newModule['core']) {
require(MODULE_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/manager.php');
} else {
require(PLUGIN_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/manager.php');
}
$this->curModId = $newModule['id'];
eval('$this->module = new \\Modules\\'.$newModule['g_name'].'\\'.$newModule['m_name'].'\\Manager();');
}else {
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'first_module') {
/*first module*/
$newModule = \Backend\Db::firstAllowedModule($this->session->userId());
if($newModule != false) {
$this->curModId = $newModule['id'];
if ($newModule['core']) {
require(MODULE_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/manager.php');
} else {
require(PLUGIN_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/manager.php');
}
eval('$this->module = new \\Modules\\'.$newModule['g_name'].'\\'.$newModule['m_name'].'\\Manager();');
}
}elseif(isset($_REQUEST['action']) && $_REQUEST['action'] == 'ping') {
$this->html->html('');
}elseif(!isset($_REQUEST['action'])) {
$this->html->html('<html><body><script type="text/javascript">parent.window.top.location=\'ip_backend_frames.php\';</script></body></html>');
}
}
//eof create module
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'tep_modules') {
$this->html->headerModules();
$this->html->modules(\Backend\Db::modules(true, $this->session->userId()));
$this->html->footer();
}else {
if($this->module) {
$this->html->html($this->module->manage());
}
}
}else {
if(strpos(BASE_URL, $_SERVER['HTTP_HOST']) != 7 && strpos(BASE_URL, $_SERVER['HTTP_HOST']) != 8 ) {
/*check if we are in correct subdomain. www.yoursite.com not allways equal to yoursite.com from session perspective)*/
header("location: ".BASE_URL."admin.php");
\db::disconnect();
exit;
}
$this->html->html(Template::headerLogin());
$this->html->html('<script type="text/javascript">if(parent.header && parent.content)parent.window.top.location=\'admin.php\';</script>');
$this->html->html(Template::loginForm($this->loginError)); //login window
$this->html->footer();
}
$this->html->send();
}
function worker() { //make worker actions.
global $cms;
global $log;
global $globalWorker;
if($this->session->loggedIn()) { //login check
//deprecated way
if (isset($_REQUEST['admin_module_group']) && $_REQUEST['admin_module_name']) {
$module = \Db::getModule(null, $_GET['admin_module_group'], $_REQUEST['admin_module_name']);
if ($module) {
$_GET['module_id'] = $module['id'];
$_REQUEST['module_id'] = $module['id'];
}
}
if(isset($_GET['module_id']) && $_GET['module_id'] != '' && \Backend\Db::allowedModule($_GET['module_id'], $cms->session->userId())) {
$this->curModId = $_GET['module_id'];
$newModule = \Db::getModule($_GET['module_id']);
if(Db::allowedModule($_GET['module_id'], $this->session->userId())){
if(file_exists(MODULE_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/backend_worker.php')) {
require_once(MODULE_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/backend_worker.php');
} else {
require_once(PLUGIN_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/backend_worker.php');
}
eval('$globalWorker = new \\Modules\\'.$newModule['g_name'].'\\'.$newModule['m_name'].'\\BackendWorker();');
$globalWorker->work();
}
}
//eof deprecated way
}
}
function getCurrentUrl() {
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= '://';
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
function generateUrl($moduleId = null, $getVars = null) { //url to cms module
if($moduleId == null)
$moduleId = $this->curModId;
if($getVars != '')
return BASE_URL.BACKEND_MAIN_FILE.'?module_id='.$moduleId.'&'.$getVars.'&security_token='.$this->session->securityToken();
else
return BASE_URL.BACKEND_MAIN_FILE.'?module_id='.$moduleId.'&security_token='.$this->session->securityToken();
}
function generateWorkerUrl($modId = null, $getVars = null) { //url to module worker file
if($modId == null)
$modId = $this->curModId;
if($getVars == '')
return BASE_URL.BACKEND_WORKER_FILE."?module_id=".$modId.'&security_token='.$this->session->securityToken();
else
return BASE_URL.BACKEND_WORKER_FILE."?module_id=".$modId.'&security_token='.$this->session->securityToken().'&'.$getVars;
}
function generateActionUrl($action, $getVars = null) { //url to global backend action
if($getVars != '')
return BASE_URL.BACKEND_MAIN_FILE.'?action='.$action.'&'.$getVars.'&security_token='.$this->session->securityToken();
else
return BASE_URL.BACKEND_MAIN_FILE.'?action='.$action.'&security_token='.$this->session->securityToken();
}
function deleteTmpFiles() {
$dirs = array();
$dirs[] = BASE_DIR.TMP_IMAGE_DIR;
$dirs[] = BASE_DIR.TMP_VIDEO_DIR;
$dirs[] = BASE_DIR.TMP_FILE_DIR;
$dirs[] = BASE_DIR.TMP_AUDIO_DIR;
foreach($dirs as $key => $dir) {
if ($handle = opendir($dir)) {
$now = time();
// List all the files
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.$file) && $file != ".." && $file != ".") {
if (filectime($dir.$file) + 3600*24*7*2 < $now) //delete if a file is created more than two weeks ago
unlink($dir.$file);
}
}
closedir($handle);
}
}
}
public static function usedUrl($url) {
$systemDirs = array();
$systemDirs[BACKEND_DIR] = 1;
$systemDirs[FILE_DIR] = 1;
$systemDirs[FRONTEND_DIR] = 1;
$systemDirs[IMAGE_DIR] = 1;
$systemDirs[INCLUDE_DIR] = 1;
$systemDirs[LIBRARY_DIR] = 1;
$systemDirs[MODULE_DIR] = 1;
$systemDirs[THEME_DIR] = 1;
$systemDirs[VIDEO_DIR] = 1;
$systemDirs['.htaccess'] = 1;
$systemDirs['admin.php'] = 1;
$systemDirs['ip_backend_frames.php'] = 1;
$systemDirs['ip_cron.php'] = 1;
$systemDirs['index.php'] = 1;
$systemDirs['ip_license.html'] = 1;
$systemDirs['robots.txt'] = 1;
$systemDirs['sitemap.php'] = 1;
if(isset($systemDirs[$url]))
return true;
else
return false;
}
/**
* Some modules need to make some actions before any output.
* This function detects such requirements and executes specified module.
* If you need to use this feature, simply POST (or GET) two variables:
* @private
* $_REQUEST['module_group']
* $_REQUEST['module_name']
* This function will include file actions.php on specified module directory and axecute method "make_actions()" on class actions_REQUEST['module_gorup']_REQUEST['module_name']
*/
public function makeActions() {
if(sizeof($_REQUEST) > 0) {
if(isset($_REQUEST['module_group']) && isset($_REQUEST['module_name'])) { //old deprecated way
//actions may be set by post or get. The prime way is trouht post. But in some cases it is not possible
$newModule = \Db::getModule(null, $_REQUEST['module_group'], $_REQUEST['module_name']);
if($newModule) {
if($newModule['core']) {
require_once(BASE_DIR.MODULE_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/actions.php');
} else {
require_once(BASE_DIR.PLUGIN_DIR.$newModule['g_name'].'/'.$newModule['m_name'].'/actions.php');
}
eval('$tmpModule = new \\Modules\\'.$newModule['g_name'].'\\'.$newModule['m_name'].'\\Actions();');
$tmpModule->makeActions();
}else {
$backtrace = debug_backtrace();
if(isset($backtrace[0]['file']) && isset($backtrace[0]['line']))
trigger_error("Requested module (".$_REQUEST['module_group'].">".$_REQUEST['module_name'].") does not exitst. (Error source: '.$backtrace[0]['file'].' line: '.$backtrace[0]['line'].' ) ");
else
trigger_error("Requested module (".$_REQUEST['module_group'].">".$_REQUEST['module_name'].") does not exitst.");
}
}
}
}
}
| gpl-3.0 |
pixartist/KSPComputer | DefaultNodes/NodeAnomaly.cs | 326 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSPComputer;
using KSPComputer.Nodes;
namespace DefaultNodes
{
[Serializable]
public class NodeAnomaly : DefaultRootNode
{
public override void OnAnomaly()
{
Execute(null);
}
}
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/temp/src/minecraft_server/net/minecraft/src/EntityAIPlay.java | 3296 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.util.*;
// Referenced classes of package net.minecraft.src:
// EntityAIBase, EntityVillager, AxisAlignedBB, World,
// Entity, RandomPositionGenerator, PathNavigate, Vec3D,
// EntityLiving
public class EntityAIPlay extends EntityAIBase
{
private EntityVillager field_48167_a;
private EntityLiving field_48165_b;
private float field_48166_c;
private int field_48164_d;
public EntityAIPlay(EntityVillager p_i1018_1_, float p_i1018_2_)
{
field_48167_a = p_i1018_1_;
field_48166_c = p_i1018_2_;
func_46087_a(1);
}
public boolean func_46090_a()
{
if(field_48167_a.func_48351_J() >= 0)
{
return false;
}
if(field_48167_a.func_46019_ai().nextInt(400) != 0)
{
return false;
}
List list = field_48167_a.field_9093_l.func_457_a(net.minecraft.src.EntityVillager.class, field_48167_a.field_312_v.func_708_b(6D, 3D, 6D));
double d = 1.7976931348623157E+308D;
Iterator iterator = list.iterator();
do
{
if(!iterator.hasNext())
{
break;
}
Entity entity = (Entity)iterator.next();
if(entity != field_48167_a)
{
EntityVillager entityvillager = (EntityVillager)entity;
if(!entityvillager.func_48353_E_() && entityvillager.func_48351_J() < 0)
{
double d1 = entityvillager.func_102_b(field_48167_a);
if(d1 <= d)
{
d = d1;
field_48165_b = entityvillager;
}
}
}
} while(true);
if(field_48165_b == null)
{
Vec3D vec3d = RandomPositionGenerator.func_48396_a(field_48167_a, 16, 3);
if(vec3d == null)
{
return false;
}
}
return true;
}
public boolean func_46092_g()
{
return field_48164_d > 0;
}
public void func_46088_e()
{
if(field_48165_b != null)
{
field_48167_a.func_48354_b(true);
}
field_48164_d = 1000;
}
public void func_46085_d()
{
field_48167_a.func_48354_b(false);
field_48165_b = null;
}
public void func_46089_b()
{
field_48164_d--;
if(field_48165_b != null)
{
if(field_48167_a.func_102_b(field_48165_b) > 4D)
{
field_48167_a.func_48333_ak().func_48652_a(field_48165_b, field_48166_c);
}
} else
if(field_48167_a.func_48333_ak().func_46034_b())
{
Vec3D vec3d = RandomPositionGenerator.func_48396_a(field_48167_a, 16, 3);
if(vec3d == null)
{
return;
}
field_48167_a.func_48333_ak().func_48658_a(vec3d.field_1055_a, vec3d.field_1054_b, vec3d.field_1058_c, field_48166_c);
}
}
}
| gpl-3.0 |
spanezz/staticsite | staticsite/page.py | 14269 | from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Any, Optional, Union, List
import os
import logging
from urllib.parse import urlparse, urlunparse
from .utils import lazy
from .utils.typing import Meta
from .render import RenderedString
import jinja2
if TYPE_CHECKING:
from .site import Site
from .file import File
from .contents import Dir
log = logging.getLogger("page")
class PageNotFoundError(Exception):
pass
class PageValidationError(Exception):
def __init__(self, page: "Page", msg: str):
self.page = page
self.msg = msg
class PageMissesFieldError(PageValidationError):
def __init__(self, page: "Page", field: str):
super().__init__(page, f"missing required field meta.{field}")
class Page:
"""
A source page in the site.
This can be a static asset, a file to be rendered, a taxonomy, a
directory listing, or anything else.
"""
# Page type
TYPE: str
def __init__(
self,
site: Site,
src: Optional[File],
meta: Meta,
dir: Optional[Dir],
created_from: Optional["Page"] = None):
# Site for this page
self.site = site
# contents.Dir which loaded this page, set at load time for non-autogenerated pages
self.dir: Optional[Dir] = dir
# If this page is autogenerated from another one, parent is the generating page
self.created_from: Optional["Page"] = created_from
# File object for this page on disk, or None if this is an autogenerated page
self.src = src
# A dictionary with the page metadata. See the README for documentation
# about its contents.
self.meta: Meta = meta
# True if this page can render a short version of itself
self.content_has_split = False
@classmethod
def create_from(cls, page: "Page", meta: Meta, **kw):
"""
Generate this page derived from an existing one
"""
# If page is the root dir, it has dir set to None, and we can use it as dir
return cls(page.site, page.src, meta, dir=page.dir or page, created_from=page, **kw)
def add_related(self, name: str, page: "Page"):
"""
Set the page as meta.related.name
"""
related = self.meta.get("related")
if related is None:
self.meta["related"] = related = {}
old = related.get(name)
if old is not None:
log.warn("%s: attempt to set related.%s to %r but it was already %r",
self, name, page, old)
return
related[name] = page
def validate(self):
"""
Enforce common meta invariants.
Performs validation and completion of metadata.
Raises PageValidationError or one of its subclasses of the page should
not be added to the site.
"""
# Run metadata on load functions
self.site.metadata.on_load(self)
# TODO: move more of this to on_load functions?
# title must exist
if "title" not in self.meta:
self.meta["title"] = self.meta["site_name"]
# Check the existence of other mandatory fields
if "site_url" not in self.meta:
raise PageMissesFieldError(self, "site_url")
# Make sure site_path exists and is relative
site_path = self.meta.get("site_path")
if site_path is None:
raise PageMissesFieldError(self, "site_path")
# Make sure build_path exists and is relative
build_path = self.meta.get("build_path")
if build_path is None:
raise PageMissesFieldError(self, "build_path")
if build_path.startswith("/"):
self.meta["build_path"] = build_path.lstrip("/")
@lazy
def page_template(self):
template = self.meta["template"]
if isinstance(template, jinja2.Template):
return template
return self.site.theme.jinja2.get_template(template)
@lazy
def redirect_template(self):
return self.site.theme.jinja2.get_template("redirect.html")
@property
def date_as_iso8601(self):
from dateutil.tz import tzlocal
ts = self.meta.get("date", None)
if ts is None:
return None
# TODO: Take timezone from config instead of tzlocal()
tz = tzlocal()
ts = ts.astimezone(tz)
offset = tz.utcoffset(ts)
offset_sec = (offset.days * 24 * 3600 + offset.seconds)
offset_hrs = offset_sec // 3600
offset_min = offset_sec % 3600
if offset:
tz_str = '{0:+03d}:{1:02d}'.format(offset_hrs, offset_min // 60)
else:
tz_str = 'Z'
return ts.strftime("%Y-%m-%d %H:%M:%S") + tz_str
def find_pages(
self,
path: Optional[str] = None,
limit: Optional[int] = None,
sort: Optional[str] = None,
root: Optional[str] = None,
**kw) -> List["Page"]:
"""
If not set, default root to the path of the containing directory for
this page
"""
if root is None and self.dir is not None and self.dir.src.relpath:
root = self.dir.src.relpath
from .page_filter import PageFilter
f = PageFilter(self.site, path, limit, sort, root=root, **kw)
return f.filter(self.site.pages.values())
def resolve_path(self, target: Union[str, "Page"]) -> "Page":
"""
Return a Page from the site, given a source or site path relative to
this page.
The path is resolved relative to this page, and if not found, relative
to the parent page, and so on until the top.
"""
if isinstance(target, Page):
return target
# Absolute URLs are resolved as is
if target.startswith("/"):
target_relpath = os.path.normpath(target)
# Try by source path
# src.relpath is indexed without leading / in site
res = self.site.pages_by_src_relpath.get(target_relpath.lstrip("/"))
if res is not None:
return res
# Try by site path
res = self.site.pages.get(target_relpath)
if res is not None:
return res
# Try adding STATIC_PATH as a compatibility with old links
target_relpath = os.path.join(self.site.settings.STATIC_PATH, target_relpath.lstrip("/"))
# Try by source path
res = self.site.pages_by_src_relpath.get(target_relpath)
if res is not None:
log.warn("%s: please use %s instead of %s", self, target_relpath, target)
return res
log.warn("%s: cannot resolve path %s", self, target)
raise PageNotFoundError(f"cannot resolve absolute path {target}")
# Relative urls are tried based on all path components of this page,
# from the bottom up
# First using the source paths
if self.src is not None:
if self.dir is None:
root = "/"
else:
root = os.path.join("/", self.dir.src.relpath)
target_relpath = os.path.normpath(os.path.join(root, target))
res = self.site.pages_by_src_relpath.get(target_relpath.lstrip("/"))
if res is not None:
return res
# Finally, using the site paths
if self.dir is None:
root = self.meta["site_path"]
else:
root = self.dir.meta["site_path"]
target_relpath = os.path.normpath(os.path.join(root, target))
res = self.site.pages.get(target_relpath)
if res is not None:
return res
raise PageNotFoundError(f"cannot resolve `{target!r}` relative to `{self!r}`")
def resolve_url(self, url: str) -> str:
"""
Resolve internal URLs.
Returns the argument itself if the URL does not need changing, else
returns the new URL.
To check for a noop, check like ``if page.resolve_url(url) is url``
This is used by url resolver postprocessors, like in markdown or
restructured text pages.
For resolving urls in templates, see Theme.jinja2_url_for().
"""
parsed = urlparse(url)
if parsed.scheme or parsed.netloc:
return url
if not parsed.path:
return url
try:
dest = self.url_for(parsed.path)
except PageNotFoundError as e:
log.warn("%s: %s", self, e)
return url
dest = urlparse(dest)
return urlunparse(
(dest.scheme, dest.netloc, dest.path,
parsed.params, parsed.query, parsed.fragment)
)
def url_for(self, target: Union[str, "Page"], absolute=False) -> str:
"""
Generate a URL for a page, specified by path or with the page itself
"""
page: "Page"
if isinstance(target, str):
page = self.resolve_path(target)
else:
page = target
# If the destination has a different site_url, generate an absolute url
if self.meta["site_url"] != page.meta["site_url"]:
absolute = True
if absolute:
site_url = page.meta["site_url"].rstrip("/")
return f"{site_url}{page.meta['site_path']}"
else:
return page.meta["site_path"]
def get_img_attributes(
self, image: Union[str, "Page"], type: Optional[str] = None, absolute=False) -> Dict[str, str]:
"""
Get <img> attributes into the given dict
"""
img = self.resolve_path(image)
res = {
"alt": img.meta["title"],
}
if type is not None:
# If a specific version is required, do not use srcset
rel = img.meta["related"].get(type, img)
res["width"] = str(rel.meta["width"])
res["height"] = str(rel.meta["height"])
res["src"] = self.url_for(rel, absolute=absolute)
else:
# https://developers.google.com/web/ilt/pwa/lab-responsive-images
# https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
srcsets = []
for rel in img.meta["related"].values():
if rel.TYPE != "image":
continue
width = rel.meta.get("width")
if width is None:
continue
url = self.url_for(rel, absolute=absolute)
srcsets.append(f"{jinja2.escape(url)} {width}w")
if srcsets:
width = img.meta["width"]
srcsets.append(f"{jinja2.escape(self.url_for(img))} {width}w")
res["srcset"] = ", ".join(srcsets)
res["src"] = self.url_for(img, absolute=absolute)
else:
res["width"] = str(img.meta["width"])
res["height"] = str(img.meta["height"])
res["src"] = self.url_for(img, absolute=absolute)
return res
def check(self, checker):
pass
def target_relpaths(self):
res = [self.meta["build_path"]]
for relpath in self.meta.get("aliases", ()):
res.append(os.path.join(relpath, "index.html"))
return res
def __str__(self):
return self.meta["site_path"]
def __repr__(self):
if self.src:
return f"{self.TYPE}:{self.src.relpath}"
else:
return f"{self.TYPE}:auto:{self.meta['site_path']}"
@jinja2.contextfunction
def html_full(self, context, **kw) -> str:
"""
Render the full page, from the <html> tag downwards.
"""
context = dict(context)
context["render_style"] = "full"
context.update(kw)
return self.render_template(self.page_template, template_args=context)
@jinja2.contextfunction
def html_body(self, context, **kw) -> str:
"""
Render the full body of the page, with UI elements excluding
navigation, headers, footers
"""
return ""
@jinja2.contextfunction
def html_inline(self, context, **kw) -> str:
"""
Render the content of the page to be shown inline, like in a blog page.
Above-the-fold content only, small images, no UI elements
"""
return ""
@jinja2.contextfunction
def html_feed(self, context, **kw) -> str:
"""
Render the content of the page to be shown in a RSS/Atom feed.
It shows the whole contents, without any UI elements, and with absolute
URLs
"""
return ""
def to_dict(self):
from .utils import dump_meta
res = {
"meta": dump_meta(self.meta),
"type": self.TYPE,
}
if self.src:
res["src"] = {
"relpath": str(self.src.relpath),
"abspath": str(self.src.abspath),
}
return res
def render(self, **kw):
res = {
self.meta["build_path"]: RenderedString(self.html_full(kw)),
}
aliases = self.meta.get("aliases", ())
if aliases:
for relpath in aliases:
html = self.render_template(self.redirect_template, template_args=kw)
res[os.path.join(relpath, "index.html")] = RenderedString(html)
return res
def render_template(self, template: jinja2.Template, template_args: Dict[Any, Any] = None) -> str:
"""
Render a jinja2 template, logging things if something goes wrong
"""
if template_args is None:
template_args = {}
template_args["page"] = self
try:
return template.render(**template_args)
except jinja2.TemplateError as e:
log.error("%s: failed to render %s: %s", template.filename, self.src.relpath, e)
log.debug("%s: failed to render %s: %s", template.filename, self.src.relpath, e, exc_info=True)
# TODO: return a "render error" page? But that risks silent errors
return None
| gpl-3.0 |
kailIII/SiGA | application/models/funcionarios_model.php | 987 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Funcionarios_model extends CI_Model {
public function busca($atributo, $setor) {
$res = $this->db->get_where("funcionarios", array($atributo => $setor[$atributo]))->row_array();
$res = checkArray($res);
return $res;
}
public function buscaTodos() {
$allFuncionaries = $this->db->get("funcionarios")->result_array();
$allFuncionaries = checkArray($allFuncionaries);
return $allFuncionaries;
}
public function salva($setor) {
$this->db->insert("funcionarios", $setor);
}
public function altera($id, $nome) {
$this->db->where('id', $id);
$res = $this->db->update("funcionarios", array('nome' => $nome));
return $res;
}
public function remove($id) {
$res = $this->db->delete("funcionarios", array('id' => $id));
var_dump($this->db->last_query());
return $res;
}
}
/* End of file funcionarios_model.php */
/* Location: ./application/models/funcionarios_model.php */ ?> | gpl-3.0 |
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/finiteVolume/finiteVolume/fvc/fvcReconstruct.C | 4130 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "fvcReconstruct.H"
#include "fvMesh.H"
#include "zeroGradientFvPatchFields.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace fvc
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
template<class Type>
tmp
<
GeometricField
<
typename outerProduct<vector,Type>::type, fvPatchField, volMesh
>
>
reconstruct
(
const GeometricField<Type, fvsPatchField, surfaceMesh>& ssf
)
{
typedef typename outerProduct<vector, Type>::type GradType;
const fvMesh& mesh = ssf.mesh();
tmp<GeometricField<GradType, fvPatchField, volMesh> > treconField
(
new GeometricField<GradType, fvPatchField, volMesh>
(
IOobject
(
"volIntegrate(" + ssf.name() + ')',
ssf.instance(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE
),
mesh,
ssf.dimensions()/dimArea,
zeroGradientFvPatchField<GradType>::typeName
)
);
GeometricField<GradType, fvPatchField, volMesh>& reconField =
treconField();
// Note:
// 1) Reconstruction is only available in cell centres: there is no need
// to invert the tensor on the boundary
// 2) For boundaries, the only reconstructed data is the flux times
// normal. Based on this guess, boundary conditions can adjust
// patch values
// HJ, 12/Aug/2011
GeometricField<GradType, fvPatchField, volMesh> fluxTimesNormal =
surfaceSum((mesh.Sf()/mesh.magSf())*ssf);
// Note: hinv inverse must be used to stabilise the inverse on bad meshes
// but it gives strange failures
// HJ, 19/Aug/2015
reconField.internalField() =
(
inv
(
surfaceSum(sqr(mesh.Sf())/mesh.magSf())().internalField()
)
& fluxTimesNormal.internalField()
);
reconField.boundaryField() = fluxTimesNormal.boundaryField();
treconField().correctBoundaryConditions();
return treconField;
}
template<class Type>
tmp
<
GeometricField
<
typename outerProduct<vector, Type>::type, fvPatchField, volMesh
>
>
reconstruct
(
const tmp<GeometricField<Type, fvsPatchField, surfaceMesh> >& tssf
)
{
typedef typename outerProduct<vector, Type>::type GradType;
tmp<GeometricField<GradType, fvPatchField, volMesh> > tvf
(
fvc::reconstruct(tssf())
);
tssf.clear();
return tvf;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace fvc
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
sgvandijk/libbats | DistributionTracker/distributiontracker.hh | 4657 | /*
* Little Green BATS (2008-2013), AI department, University of Groningen
*
* Authors: Sander van Dijk ([email protected])
* Drew Noakes ([email protected])
* Martin Klomp ([email protected])
* Mart van de Sanden ([email protected])
* A. Bram Neijt ([email protected])
* Matthijs Platje ([email protected])
* Jeroen Kuijpers ([email protected])
*
* Date: August 17, 20013
*
* Website: https://github.com/sgvandijk/libbats
*
* Comment: Please feel free to contact us if you have any
* problems or questions about the code.
*
*
* License: 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, write
* to the Free Software Foundation, Inc., 59 Temple Place -
* Suite 330, Boston, MA 02111-1307, USA.
*
*/
#ifndef BATS_DISTRIBUTIONTRACKER_HH
#define BATS_DISTRIBUTIONTRACKER_HH
#include <Eigen/Core>
namespace bats
{
/** Track the statistics of a time series
*
* This class allows you to gather statistics of samples, by adding
* them iteratively. The average and standard deviation are updated
* accordingly.
*/
class DistributionTracker
{
public:
/** Reset statistics
*
* Sets mean and variation to 0
*/
void reset();
/**
* @returns number of values added
*/
unsigned count() const;
/** Add new sample
*/
void add(double d);
/**
* @returns the current average of all added samples
*/
double average() const;
/**
* @returns the current variance of all added samples
*/
double variance() const;
private:
double d_total;
double d_totalSquared;
unsigned d_count;
};
/** Track the statistics of a 3-dimensional time series
*
* This class allows you to gather statistics of vector samples, by adding
* them iteratively. The average and standard deviation are updated
* accordingly.
*/
class Vector3dDistributionTracker
{
public:
/** Reset statistics
*
* Sets mean and variation to (0,0,0)
*/
void reset();
/**
* @returns number of samples added so far
*/
unsigned count() const;
/** Add a new sample
*/
void add(Eigen::Vector3d vector);
/**
* @returns the current average of all added samples
*/
Eigen::Vector3d average() const;
/**
* @returns the current element-wise variance of all added samples
*/
Eigen::Vector3d variance() const;
private:
DistributionTracker d_x;
DistributionTracker d_y;
DistributionTracker d_z;
};
// Inline member implementations
// DistributionTracker
inline void DistributionTracker::reset()
{
d_total = d_totalSquared = d_count = 0;
}
inline unsigned DistributionTracker::count() const
{
return d_count;
}
inline void DistributionTracker::add(double d)
{
if (std::isnan(d))
throw std::runtime_error("Cannot add nan to a DistributionTracker");
d_total += d;
d_totalSquared += d*d;
d_count++;
}
inline double DistributionTracker::average() const
{
return d_count == 0 ? NAN : d_total/d_count;
}
inline double DistributionTracker::variance() const
{
double avg = average();
return d_count == 0 ? NAN : d_totalSquared/d_count - avg*avg;
}
// Vector3dDistributionTracker
inline void Vector3dDistributionTracker::reset()
{
d_x.reset();
d_y.reset();
d_z.reset();
}
inline unsigned Vector3dDistributionTracker::count() const
{
return d_x.count();
}
inline void Vector3dDistributionTracker::add(Eigen::Vector3d vector)
{
d_x.add(vector.x());
d_y.add(vector.y());
d_z.add(vector.z());
}
inline Eigen::Vector3d Vector3dDistributionTracker::average() const
{
return Eigen::Vector3d(d_x.average(), d_y.average(), d_z.average());
}
inline Eigen::Vector3d Vector3dDistributionTracker::variance() const
{
return Eigen::Vector3d(d_x.variance(), d_y.variance(), d_z.variance());
}
}
#endif /* BATS_DISTRIBUTIONTRACKER_HH */
| gpl-3.0 |
applifireAlgo/HR | hrproject/src/main/webapp/app/view/fw/mainViewPanel/MainPanelController.js | 1238 | Ext.define('Hrproject.view.fw.mainViewPanel.MainPanelController', {
extend : 'Ext.app.ViewController',
requires : ['Ext.util.Cookies',
'Hrproject.view.login.ChangePasswordScreen'],
alias : 'controller.mainViewPanelController',
afterRender:function()
{
debugger;
var cookieChangePwd = Ext.util.Cookies.get('changePwd');
/*var pathName= location.pathname;
var initialPath=pathName.slice(0,pathName.lastIndexOf("/"));
Ext.util.Cookies.clear('changePwd',initialPath);*/
if(cookieChangePwd=="true"){
var component = Ext.create("Hrproject.view.login.ChangePasswordScreen",
{
modal:true,
});
component.show();
}
},
aftrAppMainTabPanelRender:function(tabpanel)
{
debugger;
contextMenu = new Ext.menu.Menu({
items: [{
text: 'Close All',
icon: 'images/closable.png',
listeners:{
click:'onCloseAllClick',
scope:this
}
}]
});
tabpanel.tabBar.getEl().on('contextmenu', function(e) {
e.stopEvent();
contextMenu.showAt(e.getXY());
});
},
onCloseAllClick:function()
{
var tabpanel=this.getView().down('#appMainTabPanel');
while(tabpanel.items.items.length>0){
tabpanel.items.items[0].close();
}
}
}); | gpl-3.0 |
Drxmo/imaginarium | vendor/laravel/framework/src/Illuminate/Queue/Console/ListenCommand.php | 3602 | <?php
namespace Illuminate\Queue\Console;
use Illuminate\Queue\Listener;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ListenCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:listen';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Listen to a given queue';
/**
* The queue listener instance.
*
* @var \Illuminate\Queue\Listener
*/
protected $listener;
/**
* Create a new queue listen command.
*
* @param \Illuminate\Queue\Listener $listener
* @return void
*/
public function __construct(Listener $listener) {
parent::__construct();
$this->listener = $listener;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire() {
$this->setListenerOptions();
$delay = $this->input->getOption('delay');
// The memory limit is the amount of memory we will allow the script to occupy
// before killing it and letting a process manager restart it for us, which
// is to protect us against any memory leaks that will be in the scripts.
$memory = $this->input->getOption('memory');
$connection = $this->input->getArgument('connection');
$timeout = $this->input->getOption('timeout');
// We need to get the right queue for the connection which is set in the queue
// configuration file for the application. We will pull it based on the set
// connection being run for the queue operation currently being executed.
$queue = $this->getQueue($connection);
$this->listener->listen(
$connection, $queue, $delay, $memory, $timeout
);
}
/**
* Get the name of the queue connection to listen on.
*
* @param string $connection
* @return string
*/
protected function getQueue($connection) {
if (is_null($connection)) {
$connection = $this->laravel['config']['queue.default'];
}
$queue = $this->laravel['config']->get("queue.connections.{$connection}.queue", 'default');
return $this->input->getOption('queue') ? : $queue;
}
/**
* Set the options on the queue listener.
*
* @return void
*/
protected function setListenerOptions() {
$this->listener->setEnvironment($this->laravel->environment());
$this->listener->setSleep($this->option('sleep'));
$this->listener->setMaxTries($this->option('tries'));
$this->listener->setOutputHandler(function ($type, $line) {
$this->output->write($line);
});
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments() {
return [
['connection', InputArgument::OPTIONAL, 'The name of connection'],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions() {
return [
['queue', null, InputOption::VALUE_OPTIONAL, 'The queue to listen on', null],
['delay', null, InputOption::VALUE_OPTIONAL, 'Amount of time to delay failed jobs', 0],
['memory', null, InputOption::VALUE_OPTIONAL, 'The memory limit in megabytes', 128],
['timeout', null, InputOption::VALUE_OPTIONAL, 'Seconds a job may run before timing out', 60],
['sleep', null, InputOption::VALUE_OPTIONAL, 'Seconds to wait before checking queue for jobs', 3],
['tries', null, InputOption::VALUE_OPTIONAL, 'Number of times to attempt a job before logging it failed', 0],
];
}
}
| gpl-3.0 |
MailCleaner/MailCleaner | www/framework/Zend/Mail/Part/File.php | 6148 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: File.php,v 1.1.2.4 2011-05-30 08:31:04 root Exp $
*/
/**
* @see Zend_Mime_Decode
*/
require_once 'Zend/Mime/Decode.php';
/**
* @see Zend_Mail_Part
*/
require_once 'Zend/Mail/Part.php';
/**
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Mail_Part_File extends Zend_Mail_Part
{
protected $_contentPos = array();
protected $_partPos = array();
protected $_fh;
/**
* Public constructor
*
* This handler supports the following params:
* - file filename or open file handler with message content (required)
* - startPos start position of message or part in file (default: current position)
* - endPos end position of message or part in file (default: end of file)
*
* @param array $params full message with or without headers
* @throws Zend_Mail_Exception
*/
public function __construct(array $params)
{
if (empty($params['file'])) {
/**
* @see Zend_Mail_Exception
*/
require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('no file given in params');
}
if (!is_resource($params['file'])) {
$this->_fh = fopen($params['file'], 'r');
} else {
$this->_fh = $params['file'];
}
if (!$this->_fh) {
/**
* @see Zend_Mail_Exception
*/
require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('could not open file');
}
if (isset($params['startPos'])) {
fseek($this->_fh, $params['startPos']);
}
$header = '';
$endPos = isset($params['endPos']) ? $params['endPos'] : null;
while (($endPos === null || ftell($this->_fh) < $endPos) && trim($line = fgets($this->_fh))) {
$header .= $line;
}
Zend_Mime_Decode::splitMessage($header, $this->_headers, $null);
$this->_contentPos[0] = ftell($this->_fh);
if ($endPos !== null) {
$this->_contentPos[1] = $endPos;
} else {
fseek($this->_fh, 0, SEEK_END);
$this->_contentPos[1] = ftell($this->_fh);
}
if (!$this->isMultipart()) {
return;
}
$boundary = $this->getHeaderField('content-type', 'boundary');
if (!$boundary) {
/**
* @see Zend_Mail_Exception
*/
require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('no boundary found in content type to split message');
}
$part = array();
$pos = $this->_contentPos[0];
fseek($this->_fh, $pos);
while (!feof($this->_fh) && ($endPos === null || $pos < $endPos)) {
$line = fgets($this->_fh);
if ($line === false) {
if (feof($this->_fh)) {
break;
}
/**
* @see Zend_Mail_Exception
*/
require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('error reading file');
}
$lastPos = $pos;
$pos = ftell($this->_fh);
$line = trim($line);
if ($line == '--' . $boundary) {
if ($part) {
// not first part
$part[1] = $lastPos;
$this->_partPos[] = $part;
}
$part = array($pos);
} else if ($line == '--' . $boundary . '--') {
$part[1] = $lastPos;
$this->_partPos[] = $part;
break;
}
}
$this->_countParts = count($this->_partPos);
}
/**
* Body of part
*
* If part is multipart the raw content of this part with all sub parts is returned
*
* @return string body
* @throws Zend_Mail_Exception
*/
public function getContent($stream = null)
{
fseek($this->_fh, $this->_contentPos[0]);
if ($stream !== null) {
return stream_copy_to_stream($this->_fh, $stream, $this->_contentPos[1] - $this->_contentPos[0]);
}
$length = $this->_contentPos[1] - $this->_contentPos[0];
return $length < 1 ? '' : fread($this->_fh, $length);
}
/**
* Return size of part
*
* Quite simple implemented currently (not decoding). Handle with care.
*
* @return int size
*/
public function getSize() {
return $this->_contentPos[1] - $this->_contentPos[0];
}
/**
* Get part of multipart message
*
* @param int $num number of part starting with 1 for first part
* @return Zend_Mail_Part wanted part
* @throws Zend_Mail_Exception
*/
public function getPart($num)
{
--$num;
if (!isset($this->_partPos[$num])) {
/**
* @see Zend_Mail_Exception
*/
require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('part not found');
}
return new self(array('file' => $this->_fh, 'startPos' => $this->_partPos[$num][0],
'endPos' => $this->_partPos[$num][1]));
}
}
| gpl-3.0 |
lrq3000/author-detector | authordetector/preprocessor/indev/stopwordsfilter.py | 1011 | #!/usr/bin/env python
# encoding: utf-8
## @package basepatternsextractor
#
# This contains the base patterns extractor class that you can use as a template for other classes
from authordetector.base import BaseClass
## BasePatternsExtractor
#
# Base features patterns class that you can use as a template for other classes
# Simply return the same as the input
class BasePatternsExtractor(BaseClass):
## @var config
# A reference to a ConfigParser object, already loaded
## @var parent
# A reference to the parent object (Runner)
## Constructor
# @param config An instance of the ConfigParser class
def __init__(self, config=None, parent=None, *args, **kwargs):
return BaseClass.__init__(self, config, parent, *args, **kwargs)
## Extract patterns from a text
# Here it simply returns the input
# @param X The extracted features
# @return dict A dict containing X2, the patterns
def extract(self, X=None, *args, **kwargs):
return {'X2': X}
| gpl-3.0 |
colinodell/mcforge | Commands/CmdPermissionVisit.cs | 3358 | /*
Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge)
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.osedu.org/licenses/ECL-2.0
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
namespace MCForge
{
public class CmdPermissionVisit : Command
{
public override string name { get { return "pervisit"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return "mod"; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Operator; } }
public CmdPermissionVisit() { }
public override void Use(Player p, string message)
{
if (message == "") { Help(p); return; }
int number = message.Split(' ').Length;
if (number > 2 || number < 1) { Help(p); return; }
if (number == 1)
{
LevelPermission Perm = Level.PermissionFromName(message);
if (Perm == LevelPermission.Null) { Player.SendMessage(p, "Not a valid rank"); return; }
if (p.level.permissionvisit > p.group.Permission) {
Player.SendMessage(p, "You cannot change the pervisit of a level with a pervisit higher than your rank.");
return;
}
p.level.permissionvisit = Perm;
Server.s.Log(p.level.name + " visit permission changed to " + message + ".");
Player.GlobalMessageLevel(p.level, "visit permission changed to " + message + ".");
}
else
{
int pos = message.IndexOf(' ');
string t = message.Substring(0, pos).ToLower();
string s = message.Substring(pos + 1).ToLower();
LevelPermission Perm = Level.PermissionFromName(s);
if (Perm == LevelPermission.Null) { Player.SendMessage(p, "Not a valid rank"); return; }
Level level = Level.Find(t);
if (level != null)
{
level.permissionvisit = Perm;
Server.s.Log(level.name + " visit permission changed to " + s + ".");
Player.GlobalMessageLevel(level, "visit permission changed to " + s + ".");
if (p != null)
if (p.level != level) { Player.SendMessage(p, "visit permission changed to " + s + " on " + level.name + "."); }
return;
}
else
Player.SendMessage(p, "There is no level \"" + s + "\" loaded.");
}
}
public override void Help(Player p)
{
Player.SendMessage(p, "/PerVisit <map> <rank> - Sets visiting permission for a map.");
}
}
} | gpl-3.0 |
albeva/fbide | src/Config/StyleEntry.hpp | 1172 | /*
* This file is part of fbide project, an open source IDE
* for FreeBASIC.
* https://github.com/albeva/fbide
* http://fbide.freebasic.net
* Copyright (C) 2020 Albert Varaksin
*
* fbide 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.
*
* fbide is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "pch.h"
#include "FB/Defaults.hpp"
namespace fbide {
class Config;
struct StyleEntry {
wxFont font;
#define STYLE_ENTRY(name, value) decltype(value) name;
DEFAULT_EDITOR_STYLE(STYLE_ENTRY)
#undef STYLE_ENTRY
explicit StyleEntry(const Config& style, const StyleEntry* parent = nullptr);
};
} // namespace fbide
| gpl-3.0 |
frcgang/Filesystem-over-Unreliable-Network-Storages | fuse/src/distribute.cpp | 3474 | //#include <stdio.h>
//#include <stdlib.h>
#include <string.h>
//#include <strings.h>
//#include <sys/time.h>
#include "distribute.h"
//#define DEBUG_TIME
#ifdef DEBUG_TIME
#include <time.h>
extern clock_t total_time;
#endif
void Distribute::init()//int n_servers, int k_servers, int alphabet_size)
{
//this->n_servers = n_servers;
//this->alphabet_size = alphabet_size;
//this->k_servers = k_servers;
rs = new ReedSolomon((n_servers - k_servers) * alphabet_size);
}
Distribute::~Distribute()
{
delete rs;
}
void Distribute::reset(int n_servers, int k_servers, int alphabet_size)
{
this->n_servers = n_servers;
this->k_servers = k_servers;
this->alphabet_size = alphabet_size;
rs->reset_npar((n_servers - k_servers) * alphabet_size);
}
// 'encoded_length' returns the byte length of each array
unsigned char **Distribute::encode_split(unsigned char *msg, int message_length_in_bytes, int &encoded_length)
{
//initialize_rs((n_servers - k_servers) * alphabet_size);
int msg_unit = k_servers * alphabet_size;
int unit_count = (message_length_in_bytes - 1) / msg_unit + 1;
unsigned char codeword[256];
int i,j;
unsigned char **encoded = new unsigned char *[n_servers];
for(i = 0; i < n_servers; i++)
{
encoded[i] = new unsigned char[unit_count * alphabet_size];
}
for(i = 0; i < unit_count; i++)
{
if((i < (unit_count - 1)) || ( message_length_in_bytes % msg_unit == 0))
{
rs->encode_data( msg + i * msg_unit, k_servers * alphabet_size, codeword);
}
else // padding
{
unsigned char padded_msg[msg_unit];
bzero(padded_msg, msg_unit *(sizeof(unsigned char)));
memcpy(padded_msg, msg + i * msg_unit, message_length_in_bytes - i * msg_unit);
rs->encode_data( padded_msg, k_servers * alphabet_size, codeword);
}
for(j = 0; j < n_servers; j++)
{
memcpy(encoded[j] + i * alphabet_size, codeword + j * alphabet_size,
alphabet_size * sizeof(unsigned char));
}
}
encoded_length = unit_count * alphabet_size;
return encoded;
}
// returns message length
unsigned char *Distribute::decode_merge(unsigned char **encoded, int encoded_length, int &message_length)
{
message_length = encoded_length * k_servers;
unsigned char codeword[256];
int i,j,k;
//initialize_rs((n_servers - k_servers) * alphabet_size);
unsigned char *decoded = new unsigned char[message_length];
for(i = 0; i < encoded_length / alphabet_size; i++)
{
int er[128];
int num_er = 0;
bzero(er, sizeof(er));
for(j=0; j < n_servers; j++)
{
if(encoded[j] == NULL)
{
// erased
//memset(codeword + j * alphabet_size, 0xFF, alphabet_size); // TEMP for DEBUG
for(k =0; k<alphabet_size; k++)
er[num_er++] = (n_servers * alphabet_size) - (j * alphabet_size + k) - 1;
}
else
{
memcpy(codeword + j * alphabet_size, encoded[j] + i * alphabet_size, alphabet_size);
}
}
//print_hex("EN", codeword, n_servers * alphabet_size);
rs->decode_data(codeword, n_servers * alphabet_size);
#ifdef DEBUG_TIME
clock_t start=clock();
#endif
rs->get_berlekamp()->correct_errors_erasures (codeword, n_servers * alphabet_size, num_er, er);
#ifdef DEBUG_TIME
total_time += clock() - start;
#endif
//print_hex("DE", codeword, n_servers * alphabet_size);
memcpy(decoded + k_servers * alphabet_size * i, codeword, k_servers * alphabet_size);
}
return decoded;
}
| gpl-3.0 |
CMPUT-301F14T10/project | QueueUnderflow/src/ca/ualberta/cs/queueunderflow/views/SetUsernameFragment.java | 2211 | package ca.ualberta.cs.queueunderflow.views;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import ca.ualberta.cs.queueunderflow.R;
import ca.ualberta.cs.queueunderflow.singletons.ListHandler;
import ca.ualberta.cs.queueunderflow.singletons.User;
/**
* The Class SetUsernameFragment.
* Allows user to change their username.
* @author group 10
* @version 1.0
*/
public class SetUsernameFragment extends Fragment {
/* (non-Javadoc)
* @see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().getActionBar().setTitle("Home");
return inflater.inflate(R.layout.fragment_set_username, container, false);
}
/* (non-Javadoc)
* @see android.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final TextView currentUsername = (TextView) view.findViewById(R.id.currentUsername);
final EditText newUsername = (EditText) view.findViewById(R.id.newUsername);
Button submitBtn = (Button) view.findViewById(R.id.submitBtn);
currentUsername.setText(User.getUserName());
submitBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String username = newUsername.getText().toString();
User user= ListHandler.getUser();
int flag = 0;
try {
user.setUserName(username);
} catch (IllegalArgumentException e){
currentUsername.setText(User.getUserName());
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
flag = 1;
}
if (flag == 0){
currentUsername.setText(User.getUserName());
Toast.makeText(getActivity(), "Username successfully set to " + user.getUserName(), Toast.LENGTH_SHORT).show();
}
}
});
//
}
} | gpl-3.0 |
rastating/wordpress-exploit-framework | lib/wpxf/modules/exploit/xss/reflected/all_in_one_wp_security_reflected_xss_shell_upload.rb | 994 | # frozen_string_literal: true
class Wpxf::Exploit::AllInOneWpSecurityReflectedXssShellUpload < Wpxf::Module
include Wpxf::WordPress::StagedReflectedXss
def initialize
super
update_info(
name: 'All In One WP Security 4.1.4 to 4.1.9 Reflected XSS Shell Upload',
author: [
'Yorick Koster', # Disclosure
'rastating' # WPXF module
],
references: [
['WPVDB', '8665'],
['URL', 'https://sumofpwn.nl/advisory/2016/cross_site_scripting_in_all_in_one_wp_security___firewall_wordpress_plugin.html']
],
date: 'Nov 16 2016'
)
end
def check
check_plugin_version_from_readme('all-in-one-wp-security-and-firewall', '4.1.10', '4.1.4')
end
def vulnerable_url
normalize_uri(wordpress_url_admin, 'admin.php?page=aiowpsec&tab=tab3')
end
def initial_script
create_basic_post_script(
vulnerable_url,
'tab' => "\\\"><script>#{xss_ascii_encoded_include_script}<\\/script>"
)
end
end
| gpl-3.0 |
hosseinnarimanirad/IRI.Japey | IRI.Tag/IRI.Article.Sfc/View/Components/SFCControl.xaml.cs | 5059 | using IRI.Msh.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace IRI.Article.Sfc.View.Components
{
/// <summary>
/// Interaction logic for SFCControl.xaml
/// </summary>
public partial class SFCControl : UserControl
{
public SFCControl()
{
InitializeComponent();
}
List<Point> points = new List<Point>();
List<Line> lines = new List<Line>();
public void Reset()
{
for (int i = this.layoutCanvas.Children.Count - 1; i >= 0; i--)
{
if (this.layoutCanvas.Children[i].GetType() == typeof(Line))
{
this.layoutCanvas.Children.RemoveAt(i);
}
}
this.ellipse00.MouseDown -= Ellipse_MouseDown;
this.ellipse01.MouseDown -= Ellipse_MouseDown;
this.ellipse10.MouseDown -= Ellipse_MouseDown;
this.ellipse11.MouseDown -= Ellipse_MouseDown;
this.points.Clear();
this.lines.Clear();
}
public void Define()
{
this.points = new List<Point>();
for (int i = this.layoutCanvas.Children.Count - 1; i >= 0; i--)
{
if (this.layoutCanvas.Children[i].GetType() == typeof(Line))
{
this.layoutCanvas.Children.RemoveAt(i);
}
}
this.ellipse00.MouseDown -= Ellipse_MouseDown;
this.ellipse01.MouseDown -= Ellipse_MouseDown;
this.ellipse10.MouseDown -= Ellipse_MouseDown;
this.ellipse11.MouseDown -= Ellipse_MouseDown;
this.ellipse00.MouseDown += Ellipse_MouseDown;
this.ellipse01.MouseDown += Ellipse_MouseDown;
this.ellipse10.MouseDown += Ellipse_MouseDown;
this.ellipse11.MouseDown += Ellipse_MouseDown;
}
private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
{
((Ellipse)sender).MouseDown -= Ellipse_MouseDown;
string[] temp = (((Ellipse)sender).Tag).ToString().Split(',');
this.points.Add(new Point(int.Parse(temp[0]), int.Parse(temp[1])));
int i = this.points.Count;
if (i > 1)
{
Line line = new Line()
{
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 10,
X1 = this.points[i - 2].X * 45 + 15,
X2 = this.points[i - 1].X * 45 + 15,
Y1 = this.points[i - 2].Y * 45 + 15,
Y2 = this.points[i - 1].Y * 45 + 15,
StrokeEndLineCap = PenLineCap.Triangle,
StrokeStartLineCap = PenLineCap.Round,
Opacity = .7,
Tag = "line"
};
this.layoutCanvas.Children.Add(line);
Canvas.SetZIndex(line, 0);
this.lines.Add(line);
}
if (i == 4)
{
DoTheJob();
}
}
public delegate void DoTheJobEventHandler();
public event DoTheJobEventHandler DoTheJob;
//private Line GetLine(int index)
//{
// Line line = new Line()
// {
// Stroke = this.lines[index].Stroke,
// StrokeThickness = this.lines[index].StrokeThickness,
// X1 = this.lines[index].X1,
// X2 = this.lines[index].X2,
// Y1 = this.lines[index].Y1,
// Y2 = this.lines[index].Y2,
// StrokeStartLineCap = this.lines[index].StrokeStartLineCap,
// StrokeEndLineCap = this.lines[index].StrokeEndLineCap,
// //Opacity = this.lines[index].Opacity,
// Tag = "line"
// };
// return line;
//}
public Line[] GetLines()
{
return this.lines.ToArray();
}
public List<IRI.Ket.Spatial.Primitives.Move> GetMoves()
{
List<IRI.Ket.Spatial.Primitives.Move> result = new List<IRI.Ket.Spatial.Primitives.Move>();
for (int i = 1; i < points.Count; i++)
{
double dx = points[i].X - points[i - 1].X;
double dy = points[i].Y - points[i - 1].Y;
result.Add((p, step) => new Point(p.X + step * dx,
p.Y + step * dy));
}
return result;
}
public Point[] GetPoints()
{
return this.points.ToArray();
}
}
}
| gpl-3.0 |
akaunting/akaunting | app/Jobs/Setting/UpdateCategory.php | 1406 | <?php
namespace App\Jobs\Setting;
use App\Abstracts\Job;
use App\Interfaces\Job\ShouldUpdate;
use App\Models\Setting\Category;
class UpdateCategory extends Job implements ShouldUpdate
{
public function handle(): Category
{
$this->authorize();
\DB::transaction(function () {
$this->model->update($this->request->all());
});
return $this->model;
}
/**
* Determine if this action is applicable.
*/
public function authorize(): void
{
if (! $relationships = $this->getRelationships()) {
return;
}
if ($this->request->has('type') && ($this->request->get('type') != $this->model->type)) {
$message = trans('messages.error.change_type', ['text' => implode(', ', $relationships)]);
throw new \Exception($message);
}
if (! $this->request->get('enabled')) {
$message = trans('messages.warning.disabled', ['name' => $this->model->name, 'text' => implode(', ', $relationships)]);
throw new \Exception($message);
}
}
public function getRelationships(): array
{
$rels = [
'items' => 'items',
'invoices' => 'invoices',
'bills' => 'bills',
'transactions' => 'transactions',
];
return $this->countRelationships($this->model, $rels);
}
}
| gpl-3.0 |
open-classifieds/noahsclassifieds | livesearch.php | 1583 | <?php //defined('_NOAH') or die('Restricted access'); ?>
<?php
include("app/config.php");
//include("app/controller.php");
mysql_connect($hostName, $dbUser, $dbUserPw);
mysql_selectdb($dbName);
//$obj = new Controller();
//get the q parameter from URL
$q = addslashes($_GET["q"]);
?>
<ul>
<?php
$query = "SELECT * FROM " . $dbPrefix . "category";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$query1 = 'SELECT * FROM ' . $dbPrefix . 'customfield where cid=' . $row['id'] . ' and seo=1';
$result1 = mysql_query($query1) or die(mysql_error());
while ($row1 = mysql_fetch_array($result1)) {
$columnIndex = $row1['columnIndex'];
$query2 = 'SELECT creationtime,id,clicked,' . $columnIndex . ' FROM ' . $dbPrefix . 'item where cid=' . $row['id'] . " and " . $columnIndex . " LIKE '%$q%'";
$result2 = mysql_query($query2) or die(mysql_error());
while ($row2 = mysql_fetch_array($result2)) {
$item_url = str_replace(' ', '_', $row2[$columnIndex]);
$item_url = str_replace('/', '_', $item_url);
$item_url = str_replace('&', '', $item_url);
$item_url = str_replace('^', '', $item_url);
$item_url = str_replace('%', '', $item_url);
echo "<li><a href='" . $row['permaLink'] . '/' . $row2['id'] . '_' . $item_url . "'>" . $row2[$columnIndex] . "</a></li>";
}
}
}
?>
</ul>
<?php
mysql_close(); | gpl-3.0 |
toconn/QuickQuiz-Text | Source/flashcards/convertors/conv_text_smb.py | 1820 | from ua.core.utils import strutils
from flashcards.card import Card
'''
Converts text files with format
Title // Single line title
Text... // Multiline content
[blank...] // Blank Line Break
'''
STATE_BREAK = 'break'
STATE_TITLE = 'title'
STATE_CONTENT = 'content'
class CardConvertorTextSmb:
def read (self, file_path):
lines = self._read_file (file_path)
flashcards = self._from_lines(lines)
return flashcards
def _from_lines (self, lines):
flashcards = []
flashcard = None
state = STATE_BREAK
for line in lines:
if (strutils.is_blank(line)):
if state != STATE_BREAK:
state = STATE_BREAK
flashcards.append(flashcard)
flashcard = None
# Else:
# Ignore - just another break line.
else:
if state == STATE_BREAK:
state = STATE_TITLE
flashcard = Card(title = line)
elif state == STATE_TITLE:
state = STATE_CONTENT
flashcard.content = line
else: # Must be a multiline description:
flashcard.content += '\n' + line
if flashcard:
flashcards.append (flashcard)
return flashcards
def _read_file (self, file_path):
with open(file_path) as file_handle: # 'r' is optional
lines = [line.rstrip('\n') for line in file_handle.readlines()]
return lines
| gpl-3.0 |
DomainDrivenConsulting/dogen | projects/masd.dogen.utility/include/masd.dogen.utility/types/test_data/test_data_exception.hpp | 1659 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2012-2015 Marco Craveiro <[email protected]>
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#ifndef MASD_DOGEN_UTILITY_TYPES_TEST_DATA_TEST_DATA_EXCEPTION_HPP
#define MASD_DOGEN_UTILITY_TYPES_TEST_DATA_TEST_DATA_EXCEPTION_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif
#include <string>
#include <boost/exception/info.hpp>
namespace masd::dogen::utility::test_data {
/**
* @brief An error occurred whilst obtaining the test data.
*/
class test_data_exception : public virtual std::exception, public virtual boost::exception {
public:
test_data_exception() = default;
~test_data_exception() noexcept = default;
public:
explicit test_data_exception(const std::string& message) : message_(message) { }
public:
const char* what() const noexcept { return(message_.c_str()); }
private:
const std::string message_;
};
}
#endif
| gpl-3.0 |
iamkakadong/SparseRL | result_run.py | 2606 | import MDP.chain_walk as chain_walk
import MDP.chain_walk_policy as chain_walk_policy
import numpy as np
import td.fast_elastic_td as elastic_td
import pickle
if __name__ == '__main__':
gamma = 0.9
length = 20
n_samples = 1000
# Define environment and policy
env = chain_walk.chain_walk(gamma, length)
policy = chain_walk_policy.chain_walk_policy(length)
# Set policy to optimal policy, i.e. move left if state < 10, move right if state >= 10 (state index start with 0)
p_mat = np.zeros([20, 2])
p_mat[0:10, 0] = 1
p_mat[10::, 1] = 1
policy.set_policy(p_mat)
# load samples
with open('samples.pickle') as fin:
data = pickle.load(fin)
results = dict()
NOISE = [20, 50, 100, 200, 500, 800]
for n_noisy in NOISE:
for i in range(10):
print n_noisy, i
state_seq = data[(n_noisy, i)][0]
next_state_seq = data[(n_noisy, i)][1]
reward_seq = data[(n_noisy, i)][2]
# running lstd
agent = lstd.lstd(0.0, 3 + n_noisy, gamma)
state_seq.append(next_state_seq[-1])
agent.set_start(state_seq[0])
prev_state = state_seq[0]
for i in range(len(reward_seq)):
if i == 500:
agent.set_start(state_seq[i])
prev_state = state_seq[i]
else:
agent.update_V(prev_state, state_seq[i + 1], reward_seq[i])
prev_state = state_seq[i + 1]
state_seq.pop()
theta = agent.get_theta()
print theta
# parameters for Elastic_TD
# mu: parameter for augmented Lagrangian
# epsilon: parameter for equility constraint
# delta: paramter for l1-norm and l2-norm
# stop_ep: parameter for stopping criteria (ADMM)
mu = 10
epsilon = 0.01
stop_ep = 0.01
eta = 0.5
# running elastic
delta = 0.5
alg = elastic_td.Elastic_TD(n_samples, n_noisy + 3, gamma)
beta = alg.run(mu, epsilon, delta, stop_ep, eta, np.array(state_seq), np.array(next_state_seq), np.array(reward_seq))
print(beta)
# mse, truth, pred = env.compute_mse(policy, theta, n_noisy, mc_iter=1000, restart=200)
mse, truth, pred = env.compute_mse(policy, beta, n_noisy, mc_iter=1000, restart=200)
print mse
results[(n_noisy, i)] = [mse, beta]
with open('results.pickle', 'wb') as fout:
pickle.dump(results, fout)
| gpl-3.0 |
nmdp-bioinformatics/service-epitope | resource-impl/src/test/java/org/nmdp/service/epitope/resource/impl/AlleleResourceTest.java | 5863 | /*
epitope-service T-cell epitope group matching service for HLA-DPB1 locus.
Copyright (c) 2014-2015 National Marrow Donor Program (NMDP)
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.gnu.org/licenses/lgpl.html
*/
package org.nmdp.service.epitope.resource.impl;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.nmdp.service.epitope.EpitopeServiceTestData.anAllele;
import static org.nmdp.service.epitope.EpitopeServiceTestData.anAlleleList;
import static org.nmdp.service.epitope.EpitopeServiceTestData.getTestEpitopeService;
import static org.nmdp.service.epitope.EpitopeServiceTestData.getTestGlClient;
import static org.nmdp.service.epitope.EpitopeServiceTestData.getTestGlStringFilter;
import static org.nmdp.service.epitope.EpitopeServiceTestData.group1Alleles;
import static org.nmdp.service.epitope.EpitopeServiceTestData.group2Alleles;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.nmdp.gl.Allele;
import org.nmdp.gl.client.GlClient;
import org.nmdp.service.epitope.resource.AlleleListRequest;
import org.nmdp.service.epitope.resource.AlleleView;
import org.nmdp.service.epitope.service.EpitopeService;
import org.nmdp.service.epitope.service.FrequencyService;
import com.google.common.base.Joiner;
import com.google.common.collect.FluentIterable;
@RunWith(MockitoJUnitRunner.class)
public class AlleleResourceTest {
EpitopeService epitopeService = getTestEpitopeService();
GlClient glClient = getTestGlClient();
Function<String, String> glStringFilter = getTestGlStringFilter();
@Mock
FrequencyService freqService;
private AlleleResource resource;
@Before
public void setUp() throws Exception {
resource = new AlleleResource(epitopeService, glClient, glStringFilter, freqService);
}
public List<String> allelesToStrings(List<Allele> alleleList) {
return alleleList.stream().map(a -> a.getGlstring()).collect(toList());
}
public List<String> alleleViewsToStrings(List<AlleleView> alleleViewList) {
return alleleViewList.stream().map(av -> av.getAllele()).collect(toList());
}
@Test
public void testGetAlleles_NoInputs() throws Exception {
List<String> test = alleleViewsToStrings(resource.getAlleles(null, null, null));
List<String> expect = allelesToStrings(epitopeService.getAllAlleles());
assertThat(test, containsInAnyOrder(expect.toArray()));
}
@Test
public void testGetAlleles_Alleles() throws Exception {
List<Allele> al = anAlleleList().getAlleles();
String gls = Joiner.on(",").join(al);
List<String> test = alleleViewsToStrings(resource.getAlleles(gls, null, null));
List<String> expect = allelesToStrings(al);
assertThat(test, contains(expect.toArray()));
}
@Test
public void testGetAlleles_UnknownGroup() throws Exception {
List<Allele> al = anAlleleList().getAlleles();
String gls = Joiner.on(",").join(al);
List<String> test = alleleViewsToStrings(resource.getAlleles(gls, null, null));
List<String> expect = allelesToStrings(al);
assertThat(test, contains(expect.toArray()));
}
@Test
public void testGetAlleles_Groups() throws Exception {
List<String> test = alleleViewsToStrings(resource.getAlleles(null, "1,2", null));
List<String> expect = allelesToStrings(
FluentIterable.from(group1Alleles()).append(group2Alleles()).toList());
assertThat(test, contains(expect.toArray()));
}
@Test
public void testGetAlleles_AlleleListRequest_NoInputs() throws Exception {
AlleleListRequest r = new AlleleListRequest(null, null, null);
List<String> test = alleleViewsToStrings(resource.getAlleles(r));
assertThat(test, emptyIterable());
}
@Test
public void testGetAlleles_AlleleListRequest_Alleles() throws Exception {
List<String> al = anAlleleList().getAlleles().stream().map(a -> a.getGlstring()).collect(Collectors.toList());
String gls = Joiner.on(",").join(al);
AlleleListRequest r = new AlleleListRequest(al, null, null);
List<String> test = alleleViewsToStrings(resource.getAlleles(gls, null, null));
assertThat(test, contains(al.toArray()));
}
@Test
public void testGetAlleles_AlleleListRequest_Groups() throws Exception {
AlleleListRequest r = new AlleleListRequest(null, Arrays.asList(1, 2), null);
List<String> test = alleleViewsToStrings(resource.getAlleles(r));
List<String> expect = allelesToStrings(
FluentIterable.from(group1Alleles()).append(group2Alleles()).toList());
assertThat(test, contains(expect.toArray()));
}
@Test
public void testGetAllele() throws Exception {
Allele a = anAllele();
AlleleView test = resource.getAllele(a.getGlstring(), null);
assertThat(test.getGroup(), equalTo(epitopeService.getImmuneGroupForAllele(a)));
}
}
| gpl-3.0 |
eliteironlix/portaio2 | Core/Champion Ports/Riven/NechritoRiven/Event/Misc/PermaActive.cs | 2096 | using EloBuddy;
using LeagueSharp.Common;
namespace NechritoRiven.Event.Misc
{
#region
using System;
using LeagueSharp;
using LeagueSharp.Common;
using NechritoRiven.Core;
using NechritoRiven.Event.OrbwalkingModes;
using Orbwalking = Orbwalking;
#endregion
internal class PermaActive : Core
{
#region Public Methods and Operators
private static void QMove()
{
if (!MenuConfig.QMove || !Spells.Q.IsReady())
{
return;
}
LeagueSharp.Common.Utility.DelayAction.Add(Game.Ping + 2, () => Spells.Q.Cast(Player.Position - 15));
}
public static void Update(EventArgs args)
{
if (Player.IsDead)
{
return;
}
if (Utils.GameTimeTickCount - LastQ >= 3650 - Game.Ping
&& MenuConfig.KeepQ
&& !Player.InFountain()
&& !Player.HasBuff("Recall")
&& Player.HasBuff("RivenTriCleave"))
{
Spells.Q.Cast(Game.CursorPos);
}
QMove();
BackgroundData.ForceSkill();
switch (Orbwalker.ActiveMode)
{
case Orbwalking.OrbwalkingMode.Combo:
ComboMode.Combo();
break;
case Orbwalking.OrbwalkingMode.Burst:
BurstMode.Burst();
break;
case Orbwalking.OrbwalkingMode.Flee:
FleeMode.Flee();
break;
case Orbwalking.OrbwalkingMode.QuickHarass:
FastHarassMode.FastHarass();
break;
case Orbwalking.OrbwalkingMode.Mixed:
Mixed.Harass();
break;
case Orbwalking.OrbwalkingMode.LaneClear:
JungleClearMode.Jungleclear();
LaneclearMode.Laneclear();
break;
}
}
#endregion
}
} | gpl-3.0 |
digitarald/redracer | vendor/agavi/vendor/PHPUnit/Tests/Extensions/AllTests.php | 3601 | <?php
/**
* PHPUnit
*
* Copyright (c) 2002-2008, Sebastian Bergmann <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* 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.
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2008 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id: AllTests.php 3670 2008-08-31 06:52:15Z sb $
* @link http://www.phpunit.de/
* @since File available since Release 2.0.0
*/
require_once 'PHPUnit/Util/Filter.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__);
require_once 'PHPUnit/Framework/TestSuite.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'OutputTestCaseTest.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PerformanceTestCaseTest.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'RepeatedTestTest.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'SeleniumTestCaseTest.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Database' . DIRECTORY_SEPARATOR . 'AllTests.php';
PHPUnit_Util_Filter::$filterPHPUnit = FALSE;
/**
*
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2008 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://www.phpunit.de/
* @since Class available since Release 2.0.0
*/
class Extensions_AllTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions');
$suite->addTestSuite('Extensions_OutputTestCaseTest');
$suite->addTestSuite('Extensions_PerformanceTestCaseTest');
$suite->addTestSuite('Extensions_RepeatedTestTest');
$suite->addTestSuite('Extensions_SeleniumTestCaseTest');
$suite->addTest(Extensions_Database_AllTests::suite());
return $suite;
}
}
?>
| gpl-3.0 |
natapol/dactyls | lib/dactyls/datamodel/embedded.rb | 338 | #
# Systems biology library for Ruby (Sylfy)
# Copyright (C) 2012-2013
#
# author: Natapol Pornputtapong <[email protected]>
#
# Documentation: Natapol Pornputtapong (RDoc'd and embellished by William Webber)
#
module Dactyls
class EmbeddedDocument < MongoModel::EmbeddedDocument
def initialize()
super()
end
end
end | gpl-3.0 |
neo4j-contrib/geoff-plugin | src/main/java/org/neo4j/server/plugin/geoff/GeoffPlugin.java | 2498 | /**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 org.neo4j.server.plugin.geoff;
import java.util.Map;
import org.neo4j.cypher.SyntaxException;
import org.neo4j.geoff.GEOFF;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.server.plugins.Description;
import org.neo4j.server.plugins.Name;
import org.neo4j.server.plugins.Parameter;
import org.neo4j.server.plugins.PluginTarget;
import org.neo4j.server.plugins.ServerPlugin;
import org.neo4j.server.plugins.Source;
import org.neo4j.server.rest.repr.Representation;
import org.neo4j.server.rest.repr.ValueRepresentation;
/* This is a class that will represent a server side
* Gremlin plugin and will return JSON
* for the following use cases:
* Add/delete vertices and edges from the graph.
* Manipulate the graph indices.
* Search for elements of a graph.
* Load graph data from a file or URL.
* Make use of JUNG algorithms.
* Make use of SPARQL queries over OpenRDF-based graphs.
* and much, much more.
*/
@Description( "Plugin to handle GEOFF data insertion and emits" )
public class GeoffPlugin extends ServerPlugin
{
@Name( "insert" )
@Description( "receive and add a graph encoded in GEOFF" )
@PluginTarget( GraphDatabaseService.class )
public Representation executeScript(
@Source final GraphDatabaseService neo4j,
@Description( "The geoff" ) @Parameter( name = "geoff", optional = false ) Map geoff)
throws SyntaxException
{
try
{
GEOFF.loadIntoNeo4j(geoff, neo4j, null);
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return ValueRepresentation.string( "OK." );
}
}
| gpl-3.0 |
tadatitam/info-flow-experiments | AdFisher/core/web/browser_unit.py | 7354 | import time, re # time.sleep, re.split
import sys # some prints
import os, platform # for running os, platform specific function calls
from selenium import webdriver # for running the driver on websites
from datetime import datetime # for tagging log with datetime
# from xvfbwrapper import Xvfb # for creating artificial display to run experiments
from selenium.webdriver.common.proxy import * # for proxy settings
class BrowserUnit:
def __init__(self, browser, log_file, unit_id, treatment_id, headless=False, proxy=None):
self.headless = headless
if(headless):
from xvfbwrapper import Xvfb
self.vdisplay = Xvfb(width=1280, height=720)
self.vdisplay.start()
# if(not self.vdisplay.start()):
# fo = open(log_file, "a")
# fo.write(str(datetime.now())+"||"+'error'+"||"+'Xvfb failure'+"||"+'failed to start'+"||"+str(unit_id)+"||"+str(treatment_id) + '\n')
# fo.close()
# sys.exit(0)
if(proxy != None):
sproxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': proxy,
'ftpProxy': proxy,
'sslProxy': proxy,
'noProxy': '' # set this value as desired
})
else:
sproxy = Proxy({
'proxyType': ProxyType.MANUAL
})
if(browser=='firefox'):
if (platform.system()=='Darwin'):
self.driver = webdriver.Firefox(proxy=sproxy)
elif (platform.system()=='Linux'):
self.driver = webdriver.Firefox(proxy=sproxy)
else:
print("Unidentified Platform")
sys.exit(0)
elif(browser=='chrome'):
print("Expecting chromedriver at path specified in core/web/browser_unit")
if (platform.system()=='Darwin'):
chromedriver = "../core/web/chromedriver/chromedriver_mac"
elif (platform.system() == 'Linux'):
chromedriver = "../core/web/chromedriver/chromedriver_linux"
else:
print("Unidentified Platform")
sys.exit(0)
os.environ["webdriver.chrome.driver"] = chromedriver
chrome_option = webdriver.ChromeOptions()
if(proxy != None):
chrome_option.add_argument("--proxy-server="+proxy)
self.driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_option)
else:
print("Unsupported Browser")
sys.exit(0)
self.base_url = "https://www.google.com/"
self.verificationErrors = []
self.driver.set_page_load_timeout(40)
self.accept_next_alert = True
self.log_file = log_file
self.unit_id = unit_id
self.treatment_id = treatment_id
def quit(self):
if(self.headless):
self.vdisplay.stop()
self.driver.quit()
def wait(self, seconds):
time.sleep(seconds)
def log(self, linetype, linename, msg): # linetype = ['treatment', 'measurement', 'event', 'error', 'meta']
"""Maintains a log of visitations"""
fo = open(self.log_file, "a")
fo.write(str(datetime.now())+"||"+linetype+"||"+linename+"||"+str(msg)+"||"+str(self.unit_id)+"||"+str(self.treatment_id) + '\n')
fo.close()
def interpret_log_line(self, line):
"""Interprets a line of the log, and returns six components
For lines containing meta-data, the unit_id and treatment_id is -1
"""
chunks = re.split("\|\|", line)
tim = chunks[0]
linetype = chunks[1]
linename = chunks[2]
value = chunks[3].strip()
if(len(chunks)>5):
unit_id = chunks[4]
treatment_id = chunks[5].strip()
else:
unit_id = -1
treatment_id = -1
return tim, linetype, linename, value, unit_id, treatment_id
def wait_for_others(self):
"""Makes instance with SELF.UNIT_ID wait while others train"""
fo = open(self.log_file, "r")
line = fo.readline()
tim, linetype, linename, value, unit_id, treatment_id = self.interpret_log_line(line)
instances = int(value)
fo.close()
fo = open(self.log_file, "r")
for line in fo:
tim, linetype, linename, value, unit_id, treatment_id = self.interpret_log_line(line)
if(linename == 'block_id start'):
round = int(value)
# print "round, instances: ", round, instances
fo.close()
clear = False
count = 0
while(not clear):
time.sleep(5)
count += 1
if(count > 500):
self.log('event', 'wait_for_others timeout', 'breaking out')
break
c = [0]*instances
curr_round = 0
fo = open(self.log_file, "r")
for line in fo:
tim, linetype, linename, value, unit_id, treatment_id = self.interpret_log_line(line)
if(linename == 'block_id start'):
curr_round = int(value)
if(round == curr_round):
if(value=='training-start'):
c[int(unit_id)-1] += 1
if(value=='training-end'):
c[int(unit_id)-1] -= 1
fo.close()
clear = True
# print c
for i in range(0, instances):
if(c[i] == 0):
clear = clear and True
else:
clear = False
def visit_sites(self, site_file, delay=5):
"""Visits all pages in site_file"""
fo = open(site_file, "r")
for line in fo:
chunks = re.split("\|\|", line)
site = "http://"+chunks[0].strip()
try:
self.driver.set_page_load_timeout(40)
self.driver.get(site)
time.sleep(delay)
self.log('treatment', 'visit website', site)
# pref = get_ad_pref(self.driver)
# self.log("pref"+"||"+str(treatment_id)+"||"+"@".join(pref), self.unit_id)
except:
self.log('error', 'website timeout', site)
def collect_sites_from_alexa(self, alexa_link, output_file="sites.txt", num_sites=5):
"""Collects sites from Alexa and stores them in file_name"""
fo = open(output_file, "w")
fo.close()
self.driver.get(alexa_link)
count = 0
while(count < num_sites):
els = self.driver.find_elements_by_css_selector("li.site-listing div.desc-container p.desc-paragraph a")
for el in els:
if(count < num_sites):
t = el.get_attribute('innerHTML').lower()
fo = open(output_file, "a")
fo.write(t + '\n')
fo.close()
count += 1
self.driver.find_element_by_css_selector("a.next").click()
| gpl-3.0 |
fragglet/autodoom | source/c_net.cpp | 7221 | // Emacs style mode select -*- C++ -*-
//----------------------------------------------------------------------------
//
// Copyright (C) 2013 James Haley et al.
//
// 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/
//
//--------------------------------------------------------------------------
//
// Console Network support
//
// Network commands can be sent across netgames using 'C_SendCmd'. The
// command is transferred byte by byte, 1 per tic cmd, using the
// chatchar variable (previously used for chat messages)
//
// By Simon Howard
//
// NETCODE_FIXME RED LEVEL ALERT!!! -- CONSOLE_FIXME
// The biggest problems are in here by far. While all the netcode needs
// an overhaul, the incredibly terrible way netcmds/net vars are sent
// and the fact that they cannot be recorded in demos is the most
// pressing problem and requires a complete rewrite of more or less
// everything in here. zdoom has an elegant solution to this problem,
// but it requires much more complicated network packet parsing.
//
//----------------------------------------------------------------------------
#include "z_zone.h"
#include "c_io.h"
#include "c_runcmd.h"
#include "c_net.h"
#include "d_main.h"
#include "doomdef.h"
#include "doomstat.h"
#include "dstrings.h"
#include "g_game.h"
#include "m_qstr.h"
#include "v_misc.h"
int incomingdest[MAXPLAYERS];
qstring incomingmsg[MAXPLAYERS];
command_t *c_netcmds[NUMNETCMDS];
/*
haleyjd: fixed a bug here
default_name was being set equal to a string on the C heap,
and then free()'d in the player name console command handler --
but of course free() is redefined to Z_Free(), and you can't do
that -- similar to the bug that was crashing the savegame menu,
but this one caused a segfault, and only occasionally, because
of Z_Free's faulty assumption that a pointer will be in valid
address space to test the zone id, even if its not a ptr to a
zone block.
*/
char *default_name; // = "player";
int default_colour;
// basic chat char stuff: taken from hu_stuff.c and renamed
#define QUEUESIZE 1024
static char chatchars[QUEUESIZE];
static int head = 0;
static int tail = 0;
// haleyjd: this must be called from start-up -- see above.
void C_InitPlayerName(void)
{
default_name = estrdup("player");
}
//
// C_queueChatChar() (used to be HU_*)
//
// Add an incoming character to the circular chat queue
//
// Passed the character to queue, returns nothing
//
void C_queueChatChar(unsigned char c)
{
if (((head + 1) & (QUEUESIZE-1)) == tail)
C_Printf("command unsent\n");
else
{
chatchars[head++] = c;
head &= QUEUESIZE-1;
}
}
//
// C_dequeueChatChar() (used to be HU_*)
//
// Remove the earliest added character from the circular chat queue
//
// Passed nothing, returns the character dequeued
//
unsigned char C_dequeueChatChar(void)
{
char c;
if (head != tail)
{
c = chatchars[tail++];
tail &= QUEUESIZE-1;
}
else
c = 0;
return c;
}
void C_SendCmd(int dest, int cmdnum, const char *s,...)
{
va_list args;
char tempstr[500];
va_start(args, s);
pvsnprintf(tempstr, sizeof(tempstr), s, args);
va_end(args);
s = tempstr;
if(!netgame || demoplayback)
{
Console.cmdsrc = consoleplayer;
Console.cmdtype = c_netcmd;
C_RunCommand(c_netcmds[cmdnum], s);
return;
}
C_queueChatChar(0); // flush out previous commands
C_queueChatChar((unsigned char)(dest+1)); // the chat message destination
C_queueChatChar((unsigned char)cmdnum); // command num
while(*s)
{
C_queueChatChar(*s);
s++;
}
C_queueChatChar(0);
}
void C_NetInit(void)
{
int i;
for(i = 0; i < MAXPLAYERS; ++i)
{
incomingdest[i] = -1;
incomingmsg[i].initCreate();
}
}
void C_DealWithChar(unsigned char c, int source);
void C_NetTicker(void)
{
int i;
if(netgame && !demoplayback) // only deal with chat chars in netgames
{
// check for incoming chat chars
for(i=0; i<MAXPLAYERS; i++)
{
if(!playeringame[i])
continue;
C_DealWithChar(players[i].cmd.chatchar,i);
}
}
// run buffered commands essential for netgame sync
C_RunBuffer(c_netcmd);
}
void C_DealWithChar(unsigned char c, int source)
{
int netcmdnum;
if(c)
{
if(incomingdest[source] == -1) // first char: the destination
incomingdest[source] = c-1;
else
incomingmsg[source] += c; // append to string
}
else
{
if(incomingdest[source] != -1) // end of message
{
if((incomingdest[source] == consoleplayer)
|| incomingdest[source] == CN_BROADCAST)
{
Console.cmdsrc = source;
Console.cmdtype = c_netcmd;
// the first byte is the command num
netcmdnum = *(incomingmsg[source].constPtr());
if(netcmdnum >= NUMNETCMDS || netcmdnum <= 0)
C_Printf(FC_ERROR "unknown netcmd: %i\n", netcmdnum);
else
{
// C_Printf("%s, %s", c_netcmds[netcmdnum].name,
// incomingmsg[source]+1);
C_RunCommand(c_netcmds[netcmdnum],
incomingmsg[source].constPtr() + 1);
}
}
incomingmsg[source].clear();
incomingdest[source] = -1;
}
}
}
char *G_GetNameForMap(int episode, int map);
void C_SendNetData()
{
char tempstr[100];
command_t *command;
int i;
C_SetConsole();
// display message according to what we're about to do
C_Printf(consoleplayer ?
FC_HI "Please Wait" FC_NORMAL " Receiving game data..\n" :
FC_HI "Please Wait" FC_NORMAL " Sending game data..\n");
// go thru all hash chains, check for net sync variables
for(i = 0; i < CMDCHAINS; i++)
{
command = cmdroots[i];
while(command)
{
if(command->type == ct_variable && command->flags & cf_netvar &&
(consoleplayer == 0 || !(command->flags & cf_server)))
{
C_UpdateVar(command);
}
command = command->next;
}
}
demo_insurance = 1; // always use 1 in multiplayer
if(consoleplayer == 0) // if server, send command to warp to map
{
sprintf(tempstr, "map %s", startlevel);
C_RunTextCmd(tempstr);
}
}
//
// Update a network variable
//
void C_UpdateVar(command_t *command)
{
char tempstr[100];
sprintf(tempstr,"\"%s\"", C_VariableValue(command->variable) );
C_SendCmd(CN_BROADCAST, command->netcmd, tempstr);
}
// EOF
| gpl-3.0 |
zhao07/surf | Surf/Surf/TabRenderer/TitleBarTabs.cs | 33071 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Taskbar;
using Win32Interop.Enums;
using Win32Interop.Methods;
using Win32Interop.Structs;
using Point = System.Drawing.Point;
using Size = System.Drawing.Size;
namespace Surf.TabRenderer
{
/// <summary>
/// Base class that contains the functionality to render tabs within a WinForms application's title bar area. This is done through a borderless overlay
/// window (<see cref="_overlay" />) rendered on top of the non-client area at the top of this window. All an implementing class will need to do is set
/// the <see cref="TabRenderer" /> property and begin adding tabs to <see cref="Tabs" />.
/// </summary>
public abstract partial class TitleBarTabs : Form
{
/// <summary>
/// Event delegate for <see cref="TitleBarTabs.TabDeselecting" /> and <see cref="TitleBarTabs.TabSelecting" /> that allows subscribers to cancel the
/// event and keep it from proceeding.
/// </summary>
/// <param name="sender">Object for which this event was raised.</param>
/// <param name="e">Data associated with the event.</param>
public delegate void TitleBarTabCancelEventHandler(object sender, TitleBarTabCancelEventArgs e);
/// <summary>Event delegate for <see cref="TitleBarTabs.TabSelected" /> and <see cref="TitleBarTabs.TabDeselected" />.</summary>
/// <param name="sender">Object for which this event was raised.</param>
/// <param name="e">Data associated with the event.</param>
public delegate void TitleBarTabEventHandler(object sender, TitleBarTabEventArgs e);
/// <summary>Flag indicating whether or not each tab has an Aero Peek entry allowing the user to switch between tabs from the taskbar.</summary>
protected bool _aeroPeekEnabled = true;
/// <summary>Height of the non-client area at the top of the window.</summary>
protected int _nonClientAreaHeight;
/// <summary>Borderless window that is rendered over top of the non-client area of this window.</summary>
protected internal TitleBarTabsOverlay _overlay;
/// <summary>The preview images for each tab used to display each tab when Aero Peek is activated.</summary>
protected Dictionary<Form, Bitmap> _previews = new Dictionary<Form, Bitmap>();
/// <summary>
/// When switching between tabs, this keeps track of the tab that was previously active so that, when it is switched away from, we can generate a fresh
/// Aero Peek preview image for it.
/// </summary>
protected TitleBarTab _previousActiveTab = null;
/// <summary>Maintains the previous window state so that we can respond properly to maximize/restore events in <see cref="OnSizeChanged" />.</summary>
protected FormWindowState? _previousWindowState;
/// <summary>Class responsible for actually rendering the tabs in <see cref="_overlay" />.</summary>
protected base_tab_renderer _tabRenderer;
/// <summary>List of tabs to display for this window.</summary>
protected ListWithEvents<TitleBarTab> _tabs = new ListWithEvents<TitleBarTab>();
/// <summary>Default constructor.</summary>
protected TitleBarTabs()
{
_previousWindowState = null;
ExitOnLastTabClose = true;
InitializeComponent();
SetWindowThemeAttributes(WTNCA.NODRAWCAPTION | WTNCA.NODRAWICON);
_tabs.CollectionModified += _tabs_CollectionModified;
// Set the window style so that we take care of painting the non-client area, a redraw is triggered when the size of the window changes, and the
// window itself has a transparent background color (otherwise the non-client area will simply be black when the window is maximized)
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
}
/// <summary>Flag indicating whether composition is enabled on the desktop.</summary>
internal bool IsCompositionEnabled
{
get
{
// This tests that the OS will support what we want to do. Will be false on Windows XP and earlier, as well as on Vista and 7 with Aero Glass
// disabled.
bool hasComposition;
Dwmapi.DwmIsCompositionEnabled(out hasComposition);
return hasComposition;
}
}
/// <summary>Flag indicating whether or not each tab has an Aero Peek entry allowing the user to switch between tabs from the taskbar.</summary>
public bool AeroPeekEnabled
{
get
{
return _aeroPeekEnabled;
}
set
{
_aeroPeekEnabled = value;
// Clear out any previously generate thumbnails if we are no longer enabled
if (!_aeroPeekEnabled)
{
foreach (TitleBarTab tab in Tabs)
TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(tab.Content);
_previews.Clear();
}
else
{
foreach (TitleBarTab tab in Tabs)
CreateThumbnailPreview(tab);
if (SelectedTab != null)
TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(SelectedTab.Content);
}
}
}
/// <summary>List of tabs to display for this window.</summary>
public ListWithEvents<TitleBarTab> Tabs
{
get
{
return _tabs;
}
}
/// <summary>The renderer to use when drawing the tabs.</summary>
public base_tab_renderer TabRenderer
{
get
{
return _tabRenderer;
}
set
{
_tabRenderer = value;
SetFrameSize();
}
}
/// <summary>The tab that is currently selected by the user.</summary>
public TitleBarTab SelectedTab
{
get
{
return Tabs.FirstOrDefault((TitleBarTab t) => t.Active);
}
set
{
SelectedTabIndex = Tabs.IndexOf(value);
}
}
/// <summary>Gets or sets the index of the tab that is currently selected by the user.</summary>
public int SelectedTabIndex
{
get
{
return Tabs.FindIndex((TitleBarTab t) => t.Active);
}
set
{
TitleBarTab selectedTab = SelectedTab;
int selectedTabIndex = SelectedTabIndex;
if (selectedTab != null && selectedTabIndex != value)
{
// Raise the TabDeselecting event
TitleBarTabCancelEventArgs e = new TitleBarTabCancelEventArgs
{
Action = TabControlAction.Deselecting,
Tab = selectedTab,
TabIndex = selectedTabIndex
};
OnTabDeselecting(e);
// If the subscribers to the event cancelled it, return before we do anything else
if (e.Cancel)
return;
selectedTab.Active = false;
// Raise the TabDeselected event
OnTabDeselected(
new TitleBarTabEventArgs
{
Tab = selectedTab,
TabIndex = selectedTabIndex,
Action = TabControlAction.Deselected
});
}
if (value != -1)
{
// Raise the TabSelecting event
TitleBarTabCancelEventArgs e = new TitleBarTabCancelEventArgs
{
Action = TabControlAction.Selecting,
Tab = Tabs[value],
TabIndex = value
};
OnTabSelecting(e);
// If the subscribers to the event cancelled it, return before we do anything else
if (e.Cancel)
return;
Tabs[value].Active = true;
// Raise the TabSelected event
OnTabSelected(
new TitleBarTabEventArgs
{
Tab = Tabs[value],
TabIndex = value,
Action = TabControlAction.Selected
});
}
if (_overlay != null)
_overlay.Render();
}
}
/// <summary>Flag indicating whether the application itself should exit when the last tab is closed.</summary>
public bool ExitOnLastTabClose
{
get;
set;
}
/// <summary>Flag indicating whether we are in the process of closing the window.</summary>
public bool IsClosing
{
get;
set;
}
/// <summary>Application context under which this particular window runs.</summary>
public TitleBarTabsApplicationContext ApplicationContext
{
get;
internal set;
}
/// <summary>Height of the "glassed" area of the window's non-client area.</summary>
public int NonClientAreaHeight
{
get
{
return _nonClientAreaHeight;
}
}
/// <summary>Area of the screen in which tabs can be dropped for this window.</summary>
public Rectangle TabDropArea
{
get
{
return _overlay.TabDropArea;
}
}
/// <summary>Calls <see cref="Uxtheme.SetWindowThemeAttribute" /> to set various attributes on the window.</summary>
/// <param name="attributes">Attributes to set on the window.</param>
private void SetWindowThemeAttributes(WTNCA attributes)
{
WTA_OPTIONS options = new WTA_OPTIONS
{
dwFlags = attributes,
dwMask = WTNCA.VALIDBITS
};
// The SetWindowThemeAttribute API call takes care of everything
Uxtheme.SetWindowThemeAttribute(Handle, WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, ref options, (uint)Marshal.SizeOf(typeof(WTA_OPTIONS)));
}
/// <summary>
/// Event handler that is invoked when the <see cref="Form.Load" /> event is fired. Instantiates <see cref="_overlay" /> and clears out the window's
/// caption.
/// </summary>
/// <param name="e">Arguments associated with the event.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_overlay = TitleBarTabsOverlay.GetInstance(this);
if (TabRenderer != null)
{
_overlay.MouseMove += TabRenderer.Overlay_MouseMove;
_overlay.MouseUp += TabRenderer.Overlay_MouseUp;
_overlay.MouseDown += TabRenderer.Overlay_MouseDown;
}
}
/// <summary>
/// When the window's state (maximized, minimized, or restored) changes, this sets the size of the non-client area at the top of the window properly so
/// that the tabs can be displayed.
/// </summary>
protected void SetFrameSize()
{
if (TabRenderer == null || WindowState == FormWindowState.Minimized)
return;
int topPadding;
if (WindowState == FormWindowState.Maximized)
topPadding = TabRenderer.TabHeight - SystemInformation.CaptionHeight;
else
topPadding = (TabRenderer.TabHeight + SystemInformation.CaptionButtonSize.Height) - SystemInformation.CaptionHeight;
Padding = new Padding(
Padding.Left, topPadding > 0
? topPadding
: 0, Padding.Right, Padding.Bottom);
// Set the margins and extend the frame into the client area
MARGINS margins = new MARGINS
{
cxLeftWidth = 0,
cxRightWidth = 0,
cyBottomHeight = 0,
cyTopHeight = topPadding > 0
? topPadding
: 0
};
Dwmapi.DwmExtendFrameIntoClientArea(Handle, ref margins);
_nonClientAreaHeight = SystemInformation.CaptionHeight + (topPadding > 0
? topPadding
: 0);
if (AeroPeekEnabled)
{
foreach (
TabbedThumbnail preview in
Tabs.Select(tab => TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(tab.Content)).Where(preview => preview != null))
preview.PeekOffset = new Vector(Padding.Left, Padding.Top - 1);
}
}
/// <summary>Event that is raised immediately prior to a tab being deselected (<see cref="TabDeselected" />).</summary>
public event TitleBarTabCancelEventHandler TabDeselecting;
/// <summary>Event that is raised after a tab has been deselected.</summary>
public event TitleBarTabEventHandler TabDeselected;
/// <summary>Event that is raised immediately prior to a tab being selected (<see cref="TabSelected" />).</summary>
public event TitleBarTabCancelEventHandler TabSelecting;
/// <summary>Event that is raised after a tab has been selected.</summary>
public event TitleBarTabEventHandler TabSelected;
/// <summary>Event that is raised after a tab has been clicked.</summary>
public event TitleBarTabEventHandler TabClicked;
/// <summary>
/// Callback that should be implemented by the inheriting class that will create a new <see cref="TitleBarTab" /> object when the add button is
/// clicked.
/// </summary>
/// <returns>A newly created tab.</returns>
public abstract TitleBarTab CreateTab();
/// <summary>Callback for the <see cref="TabClicked" /> event.</summary>
/// <param name="e">Arguments associated with the event.</param>
protected internal void OnTabClicked(TitleBarTabEventArgs e)
{
if (TabClicked != null)
TabClicked(this, e);
}
/// <summary>
/// Callback for the <see cref="TabDeselecting" /> event. Called when a <see cref="TitleBarTab" /> is in the process of losing focus. Grabs an image of
/// the tab's content to be used when Aero Peek is activated.
/// </summary>
/// <param name="e">Arguments associated with the event.</param>
protected void OnTabDeselecting(TitleBarTabCancelEventArgs e)
{
if (_previousActiveTab != null && AeroPeekEnabled)
UpdateTabThumbnail(_previousActiveTab);
if (TabDeselecting != null)
TabDeselecting(this, e);
}
/// <summary>Generate a new thumbnail image for <paramref name="tab" />.</summary>
/// <param name="tab">Tab that we need to generate a thumbnail for.</param>
protected void UpdateTabThumbnail(TitleBarTab tab)
{
TabbedThumbnail preview = TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(tab.Content);
if (preview == null)
return;
Bitmap bitmap = TabbedThumbnailScreenCapture.GrabWindowBitmap(tab.Content.Handle, tab.Content.Size);
preview.SetImage(bitmap);
// If we already had a preview image for the tab, dispose of it
if (_previews.ContainsKey(tab.Content) && _previews[tab.Content] != null)
_previews[tab.Content].Dispose();
_previews[tab.Content] = bitmap;
}
/// <summary>Callback for the <see cref="TabDeselected" /> event.</summary>
/// <param name="e">Arguments associated with the event.</param>
protected void OnTabDeselected(TitleBarTabEventArgs e)
{
if (TabDeselected != null)
TabDeselected(this, e);
}
/// <summary>Callback for the <see cref="TabSelecting" /> event.</summary>
/// <param name="e">Arguments associated with the event.</param>
protected void OnTabSelecting(TitleBarTabCancelEventArgs e)
{
if (TabSelecting != null)
TabSelecting(this, e);
}
/// <summary>
/// Callback for the <see cref="TabSelected" /> event. Called when a <see cref="TitleBarTab" /> gains focus. Sets the active window in Aero Peek via a
/// call to <see cref="TabbedThumbnailManager.SetActiveTab(Control)" />.
/// </summary>
/// <param name="e">Arguments associated with the event.</param>
protected void OnTabSelected(TitleBarTabEventArgs e)
{
if (SelectedTabIndex != -1 && _previews.ContainsKey(SelectedTab.Content) && AeroPeekEnabled)
TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(SelectedTab.Content);
_previousActiveTab = SelectedTab;
if (TabSelected != null)
TabSelected(this, e);
}
/// <summary>
/// Handler method that's called when Aero Peek needs to display a thumbnail for a <see cref="TitleBarTab" />; finds the preview bitmap generated in
/// <see cref="TabDeselecting" /> and returns that.
/// </summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with this event.</param>
private void preview_TabbedThumbnailBitmapRequested(object sender, TabbedThumbnailBitmapRequestedEventArgs e)
{
foreach (
TitleBarTab rdcWindow in Tabs.Where(rdcWindow => rdcWindow.Content.Handle == e.WindowHandle && _previews.ContainsKey(rdcWindow.Content)))
{
e.SetImage(_previews[rdcWindow.Content]);
break;
}
}
/// <summary>
/// Callback for the <see cref="Control.ClientSizeChanged" /> event that resizes the <see cref="TitleBarTab.Content" /> form of the currently selected
/// tab when the size of the client area for this window changes.
/// </summary>
/// <param name="e">Arguments associated with the event.</param>
protected override void OnClientSizeChanged(EventArgs e)
{
base.OnClientSizeChanged(e);
ResizeTabContents();
}
/// <summary>Resizes the <see cref="TitleBarTab.Content" /> form of the <paramref name="tab" /> to match the size of the client area for this window.</summary>
/// <param name="tab">Tab whose <see cref="TitleBarTab.Content" /> form we should resize; if not specified, we default to
/// <see cref="SelectedTab" />.</param>
public void ResizeTabContents(TitleBarTab tab = null)
{
if (tab == null)
tab = SelectedTab;
if (tab != null)
{
tab.Content.Location = new Point(0, Padding.Top - 1);
tab.Content.Size = new Size(ClientRectangle.Width, ClientRectangle.Height - Padding.Top + 1);
}
}
/// <summary>Override of the handler for the paint background event that is left blank so that code is never executed.</summary>
/// <param name="e">Arguments associated with the event.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
}
/// <summary>Forwards a message received by <see cref="TitleBarTabsOverlay" /> to the underlying window.</summary>
/// <param name="m">Message received by the overlay.</param>
internal void ForwardMessage(ref Message m)
{
m.HWnd = Handle;
WndProc(ref m);
}
/// <summary>
/// Handler method that's called when the user clicks on an Aero Peek preview thumbnail. Finds the tab associated with the thumbnail and
/// focuses on it.
/// </summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with this event.</param>
private void preview_TabbedThumbnailActivated(object sender, TabbedThumbnailEventArgs e)
{
foreach (TitleBarTab tab in Tabs.Where(tab => tab.Content.Handle == e.WindowHandle))
{
SelectedTabIndex = Tabs.IndexOf(tab);
TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(tab.Content);
break;
}
// Restore the window if it was minimized
if (WindowState == FormWindowState.Minimized)
User32.ShowWindow(Handle, 3);
else
Focus();
}
/// <summary>
/// Handler method that's called when the user clicks the close button in an Aero Peek preview thumbnail. Finds the window associated with the thumbnail
/// and calls <see cref="Form.Close" /> on it.
/// </summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with this event.</param>
private void preview_TabbedThumbnailClosed(object sender, TabbedThumbnailEventArgs e)
{
foreach (TitleBarTab tab in Tabs.Where(tab => tab.Content.Handle == e.WindowHandle))
{
tab.Content.Close();
if (e.TabbedThumbnail != null)
TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(e.TabbedThumbnail);
break;
}
}
/// <summary>Callback that is invoked whenever anything is added or removed from <see cref="Tabs" /> so that we can trigger a redraw of the tabs.</summary>
/// <param name="sender">Object for which this event was raised.</param>
/// <param name="e">Arguments associated with the event.</param>
private void _tabs_CollectionModified(object sender, ListModificationEventArgs e)
{
SetFrameSize();
if (e.Modification == ListModification.ItemAdded || e.Modification == ListModification.RangeAdded)
{
for (int i = 0; i < e.Count; i++)
{
TitleBarTab currentTab = Tabs[i + e.StartIndex];
currentTab.Content.TextChanged += Content_TextChanged;
currentTab.Closing += TitleBarTabs_Closing;
if (AeroPeekEnabled)
TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(CreateThumbnailPreview(currentTab));
}
}
if (_overlay != null)
_overlay.Render(true);
}
/// <summary>
/// Creates a new thumbnail for <paramref name="tab" /> when the application is initially enabled for AeroPeek or when it is turned on sometime during
/// execution.
/// </summary>
/// <param name="tab">Tab that we are to create the thumbnail for.</param>
/// <returns>Thumbnail created for <paramref name="tab" />.</returns>
protected virtual TabbedThumbnail CreateThumbnailPreview(TitleBarTab tab)
{
TabbedThumbnail preview = new TabbedThumbnail(Handle, tab.Content)
{
Title = tab.Content.Text,
Tooltip = tab.Content.Text
};
preview.SetWindowIcon(tab.Content.Icon);
preview.TabbedThumbnailActivated += preview_TabbedThumbnailActivated;
preview.TabbedThumbnailClosed += preview_TabbedThumbnailClosed;
preview.TabbedThumbnailBitmapRequested += preview_TabbedThumbnailBitmapRequested;
preview.PeekOffset = new Vector(Padding.Left, Padding.Top - 1);
TaskbarManager.Instance.TabbedThumbnail.AddThumbnailPreview(preview);
return preview;
}
/// <summary>
/// Event handler that is called when a tab's <see cref="Form.Text" /> property is changed, which re-renders the tab text and updates the title of the
/// Aero Peek preview.
/// </summary>
/// <param name="sender">Object from which this event originated (the <see cref="TitleBarTab.Content" /> object in this case).</param>
/// <param name="e">Arguments associated with the event.</param>
private void Content_TextChanged(object sender, EventArgs e)
{
if (AeroPeekEnabled)
{
TabbedThumbnail preview = TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview((Form)sender);
if (preview != null)
preview.Title = (sender as Form).Text;
}
if (_overlay != null)
_overlay.Render(true);
}
/// <summary>
/// Event handler that is called when a tab's <see cref="TitleBarTab.Closing" /> event is fired, which removes the tab from <see cref="Tabs" /> and
/// re-renders <see cref="_overlay" />.
/// </summary>
/// <param name="sender">Object from which this event originated (the <see cref="TitleBarTab" /> in this case).</param>
/// <param name="e">Arguments associated with the event.</param>
private void TitleBarTabs_Closing(object sender, CancelEventArgs e)
{
CloseTab((TitleBarTab)sender);
if (_overlay != null)
_overlay.Render(true);
}
/// <summary>
/// Overrides the <see cref="Control.SizeChanged" /> handler so that we can detect when the user has maximized or restored the window and adjust the size
/// of the non-client area accordingly.
/// </summary>
/// <param name="e">Arguments associated with the event.</param>
protected override void OnSizeChanged(EventArgs e)
{
// If no tab renderer has been set yet or the window state hasn't changed, don't do anything
if (_previousWindowState != null && WindowState != _previousWindowState.Value)
SetFrameSize();
_previousWindowState = WindowState;
base.OnSizeChanged(e);
}
/// <summary>Overrides the message processor for the window so that we can respond to windows events to render and manipulate the tabs properly.</summary>
/// <param name="m">Message received by the pump.</param>
protected override void WndProc(ref Message m)
{
bool callDwp = true;
switch ((WM)m.Msg)
{
// When the window is activated, set the size of the non-client area appropriately
case WM.WM_ACTIVATE:
if ((m.WParam.ToInt64() & 0x0000FFFF) != 0)
{
SetFrameSize();
ResizeTabContents();
m.Result = IntPtr.Zero;
}
break;
case WM.WM_NCHITTEST:
// Call the base message handler to see where the user clicked in the window
base.WndProc(ref m);
HT hitResult = (HT)m.Result.ToInt32();
// If they were over the minimize/maximize/close buttons or the system menu, let the message pass
if (!(hitResult == HT.HTCLOSE || hitResult == HT.HTMINBUTTON || hitResult == HT.HTMAXBUTTON || hitResult == HT.HTMENU ||
hitResult == HT.HTSYSMENU))
m.Result = new IntPtr((int)HitTest(m));
callDwp = false;
break;
// Catch the case where the user is clicking the minimize button and use this opportunity to update the AeroPeek thumbnail for the current tab
case WM.WM_NCLBUTTONDOWN:
if (((HT)m.WParam.ToInt32()) == HT.HTMINBUTTON && AeroPeekEnabled && SelectedTab != null)
UpdateTabThumbnail(SelectedTab);
break;
}
if (callDwp)
base.WndProc(ref m);
}
/// <summary>Calls <see cref="CreateTab" />, adds the resulting tab to the <see cref="Tabs" /> collection, and activates it.</summary>
public virtual void AddNewTab()
{
TitleBarTab newTab = CreateTab();
Tabs.Add(newTab);
ResizeTabContents(newTab);
SelectedTabIndex = _tabs.Count - 1;
}
/// <summary>Removes <paramref name="closingTab" /> from <see cref="Tabs" /> and selects the next applicable tab in the list.</summary>
/// <param name="closingTab">Tab that is being closed.</param>
protected virtual void CloseTab(TitleBarTab closingTab)
{
int removeIndex = Tabs.IndexOf(closingTab);
int selectedTabIndex = SelectedTabIndex;
Tabs.Remove(closingTab);
if (selectedTabIndex > removeIndex)
SelectedTabIndex = selectedTabIndex - 1;
else if (selectedTabIndex == removeIndex)
SelectedTabIndex = Math.Min(selectedTabIndex, Tabs.Count - 1);
else
SelectedTabIndex = selectedTabIndex;
if (_previews.ContainsKey(closingTab.Content))
{
_previews[closingTab.Content].Dispose();
_previews.Remove(closingTab.Content);
}
if (_previousActiveTab != null && closingTab.Content == _previousActiveTab.Content)
_previousActiveTab = null;
if (!closingTab.Content.IsDisposed && AeroPeekEnabled)
TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(closingTab.Content);
if (Tabs.Count == 0 && ExitOnLastTabClose)
Close();
}
private HT HitTest(Message m)
{
// Get the point that the user clicked
int lParam = (int)m.LParam;
Point point = new Point(lParam & 0xffff, lParam >> 16);
return HitTest(point, m.HWnd);
}
/// <summary>Called when a <see cref="WM.WM_NCHITTEST" /> message is received to see where in the non-client area the user clicked.</summary>
/// <param name="point">Screen location that we are to test.</param>
/// <param name="windowHandle">Handle to the window for which we are performing the test.</param>
/// <returns>One of the <see cref="HT" /> values, depending on where the user clicked.</returns>
private HT HitTest(Point point, IntPtr windowHandle)
{
RECT rect;
User32.GetWindowRect(windowHandle, out rect);
Rectangle area = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
int row = 1;
int column = 1;
bool onResizeBorder = false;
// Determine if we are on the top or bottom border
if (point.Y >= area.Top && point.Y < area.Top + SystemInformation.VerticalResizeBorderThickness + _nonClientAreaHeight - 2)
{
onResizeBorder = point.Y < (area.Top + SystemInformation.VerticalResizeBorderThickness);
row = 0;
}
else if (point.Y < area.Bottom && point.Y > area.Bottom - SystemInformation.VerticalResizeBorderThickness)
row = 2;
// Determine if we are on the left border or the right border
if (point.X >= area.Left && point.X < area.Left + SystemInformation.HorizontalResizeBorderThickness)
column = 0;
else if (point.X < area.Right && point.X >= area.Right - SystemInformation.HorizontalResizeBorderThickness)
column = 2;
HT[,] hitTests =
{
{
onResizeBorder
? HT.HTTOPLEFT
: HT.HTLEFT,
onResizeBorder
? HT.HTTOP
: HT.HTCAPTION,
onResizeBorder
? HT.HTTOPRIGHT
: HT.HTRIGHT
},
{
HT.HTLEFT, HT.HTNOWHERE, HT.HTRIGHT
},
{
HT.HTBOTTOMLEFT, HT.HTBOTTOM,
HT.HTBOTTOMRIGHT
}
};
return hitTests[row, column];
}
}
} | gpl-3.0 |
dplc/dwin | dm/include/win32/WSVNS.H | 1250 | /*******************************************************************************
*
* wsvns.h
*
* Windows Sockets include file for VINES IP. This file contains all
* standardized VINES IP information. Include this header file after
* winsock.h.
*
* To open an VINES IP socket, call socket() with an address family of
* AF_BAN, a socket type of SOCK_DGRAM, SOCK_STREAM, or SOCK_SEQPACKET,
* and protocol of 0.
*
******************************************************************************/
#ifndef _WSVNS_
#define _WSVNS_
/*
* Socket address, VINES IP style. Address fields and port field are defined
* as a sequence of bytes. This is done because they are byte ordered
* BIG ENDIAN, ala most significant byte first.
*/
typedef struct sockaddr_vns {
u_short sin_family; // = AF_BAN
u_char net_address[4]; // network address
u_char subnet_addr[2]; // subnet address
u_char port[2]; // msb=port[0], lsb=port[1]
u_char hops; // # hops for broadcasts
u_char filler[5]; // filler, zeros
} SOCKADDR_VNS, *PSOCKADDR_VNS, FAR *LPSOCKADDR_VNS;
#define VNSPROTO_IPC 1
#define VNSPROTO_RELIABLE_IPC 2
#define VNSPROTO_SPP 3
#endif _WSVNS_
| gpl-3.0 |
aceberg/HomeWork2 | src/com/sibext/skeleton/myArrayAdapter.java | 2415 | package com.sibext.skeleton;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aceberg on 11/9/13.
*/
public class myArrayAdapter extends BaseAdapter
{
private final Context context;
//private final String[] values;
private final ArrayList<DataClass> list;
public myArrayAdapter(Context context, ArrayList<DataClass> list)
{
// super(context, R.layout.adapter, values);
this.context = context;
//this.values = values;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position).url;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.adapter, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.text_view);
//final ImageView imageView = (ImageView) rowView.findViewById(R.id.im_view);
textView.setText(list.get(position).value);
//imageView.setImageResource(list.get(position).id);
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), new BitmapLruCache());
imageLoader.get(list.get(position).imUrl, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
ImageView image = (ImageView) rowView.findViewById(R.id.im_view);
image.setImageBitmap(imageContainer.getBitmap());
}
@Override
public void onErrorResponse(VolleyError volleyError) {
// TODO: Please inform about failed
}
});
return rowView;
}
}
| gpl-3.0 |
m241dan/darkstar | scripts/zones/Behemoths_Dominion/mobs/King_Behemoth.lua | 2051 | -----------------------------------
-- Area: Behemoth's Dominion
-- HNM: King Behemoth
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/melfnm");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_MAGIC_COOL, 60);
end;
function onMobFight(mob, target)
end;
function onMobSpawn( mob )
mob:addMod(MOD_SLEEPRES, 1000);
mob:addMod(MOD_SILENCERES,100);
mob:addMod(MOD_STUNRES,100);
mob:addMod(MOD_BINDRES,50);
mob:setMobMod(MOBMOD_DRAW_IN,100);
mob:setMod( MOD_REGAIN, 50 );
mob:speed( 50 );
mob:addMod( MOD_INT, 20 );
mob:setMod( MOD_REGEN, 65 );
mob:addMod( MOD_MDEF, 20 );
mob:addMod( MOD_MEVA, 85 );
mob:addMod( MOD_DEF, 150 );
mob:addMod( MOD_EVA, 60 );
mob:addMod( MOD_MATT, 17 );
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(BEHEMOTH_DETHRONER);
-- Set King_Behemoth's Window Open Time
if (LandKingSystem_HQ ~= 1) then
local wait = 72 * 3600;
SetServerVariable("[POP]King_Behemoth", os.time(t) + wait); -- 3 days
if (LandKingSystem_HQ == 0) then -- Is time spawn only
DeterMob(mob:getID(), true);
end
end
-- Set Behemoth's spawnpoint and respawn time (21-24 hours)
if (LandKingSystem_NQ ~= 1) then
SetServerVariable("[PH]King_Behemoth", 0);
local Behemoth = mob:getID()-1;
DeterMob(Behemoth, false);
UpdateNMSpawnPoint(Behemoth);
GetMobByID(Behemoth):setRespawnTime(math.random(75600,86400));
end
end;
function onSpellPrecast(mob, spell)
if (spell:getID() == 218) then
spell:setAoE(SPELLAOE_RADIAL);
spell:setFlag(SPELLFLAG_HIT_ALL);
spell:setRadius(30);
spell:setAnimation(280);
spell:setMPCost(1);
end
end;
| gpl-3.0 |
Brandon-T/Sudoku-Ravager | Puzzles/28.hpp | 234 | 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 7, 9, 0, 5, 0, 1, 8, 0
8, 0, 0, 0, 0, 0, 0, 0, 7
0, 0, 7, 3, 0, 6, 8, 0, 0
4, 5, 0, 7, 0, 8, 0, 9, 6
0, 0, 3, 5, 0, 2, 7, 0, 0
7, 0, 0, 0, 0, 0, 0, 0, 5
0, 1, 6, 0, 3, 0, 4, 2, 0
0, 0, 0, 0, 0, 0, 0, 0, 0
| gpl-3.0 |
stfx/freelancermodstudio | DockPanelSuite/Docking/VS2005DockPaneStrip.cs | 58950 | using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
}
#region consts
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 4;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 3;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonWindowList;
private static Bitmap ImageButtonWindowList
{
get
{
if (_imageButtonWindowList == null)
_imageButtonWindowList = Resources.DockPane_Option;
return _imageButtonWindowList;
}
}
private static Bitmap _imageButtonWindowListOverflow;
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (_imageButtonWindowListOverflow == null)
_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return _imageButtonWindowListOverflow;
}
}
private InertButton m_buttonWindowList;
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer m_components;
private ToolTip m_toolTip;
private IContainer Components
{
get { return m_components; }
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipSelect;
private static string ToolTipSelect
{
get
{
if (_toolTipSelect == null)
_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return _toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
public VS2005DockPaneStrip(DockPane pane)
: base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose(disposing);
}
private static Font TextFont
{
get { return SystemInformation.MenuFont; }
}
private Font m_font;
private Font m_boldFont;
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int m_startDisplayingTab = 0;
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int m_endDisplayingTab = 0;
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int m_firstDisplayingTab = 0;
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool m_documentTabsOverflow = false;
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
if (rect.Width > 0 && rect.Height > 0)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
base.OnPaint(e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
protected internal override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
int y = rectTab.Top;
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; )
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth--;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i = 0; i < count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2005, rectTab);
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, tabActive, rectTab);
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i = 0; i < Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
// Draws the full angle piece for active content (or first tab)
if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
// Draws the partial angle for non-active content
else
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90);
}
else
{
// Draws the top horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
// Draws the rounded corner oppposite the angled side
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
}
else
{
// Draw the vertical line opposite the angled side
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
else
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
g.DrawPath(PenToolWindowTabBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += rect.X;
rectBack.X = 0;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabActiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabInactiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip m_selectMenu;
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
private void WindowList_Click(object sender, EventArgs e)
{
int x = 0;
int y = ButtonWindowList.Location.Y + ButtonWindowList.Height;
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
SelectMenu.Show(ButtonWindowList, x, y);
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
ButtonClose.Enabled = showCloseButton;
ButtonClose.Visible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance != DockPane.AppearanceStyle.Document)
{
base.OnLayout(levent);
return;
}
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (ButtonClose.Visible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
OnRefreshChanges();
base.OnLayout(levent);
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
return -1;
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| gpl-3.0 |
Thomsch/seshat | test/ch/ceruleansands/collection/AutoDiscardingStackTest.java | 3848 | package ch.ceruleansands.collection;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Thomsch
*/
public class AutoDiscardingStackTest {
@Test(expected = IllegalArgumentException.class)
public void constructor_ShouldThrowExceptionIfSizeIsZero() throws Exception {
new AutoDiscardingStack(0);
}
@Test(expected = IllegalArgumentException.class)
public void constructor_ShouldThrowExceptionIfSizeIsBelowZero() throws Exception {
new AutoDiscardingStack(-1);
}
@Test
public void constructor_ShouldBeEmptyWithNewInstance() throws Exception {
AutoDiscardingStack stack = new AutoDiscardingStack(1);
assertTrue(stack.isEmpty());
}
@Test
public void push_ShouldMakeStackNotEmpty() throws Exception {
AutoDiscardingStack<Object> stack = new AutoDiscardingStack<>(1);
stack.push(new Object());
assertFalse(stack.isEmpty());
assertEquals(1, stack.size());
}
@Test
public void push_ShouldReplaceOlderElementWhenFull() throws Exception {
AutoDiscardingStack<Integer> stack = new AutoDiscardingStack<>(1);
stack.push(1);
stack.push(2);
assertEquals(1, stack.size());
assertEquals(2, (int) stack.pop());
}
@Test
public void push_ShouldThrowIllegalArgumentExceptionIfNullItem() throws Exception {
AutoDiscardingStack<Integer> stack = new AutoDiscardingStack<>(1);
try {
stack.push(null);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
@Test
public void push_ShouldIncreaseStackSizeIfRoom() throws Exception {
AutoDiscardingStack<Object> stack = new AutoDiscardingStack<>(2);
stack.push(new Object());
assertEquals(1, stack.size());
stack.push(new Object());
assertEquals(2, stack.size());
stack.push(new Object());
assertEquals(2, stack.size());
}
@Test
public void clear_ShouldRemoveAllItems() throws Exception {
AutoDiscardingStack<Object> stack = new AutoDiscardingStack<>(2);
stack.push(new Object());
stack.push(new Object());
stack.clear();
assertEquals(0, stack.size());
assertNull(stack.pop());
}
@Test
public void clear_ShouldDoNothingIfStackIsEmpty() throws Exception {
AutoDiscardingStack<Object> stack = new AutoDiscardingStack<>(2);
stack.clear();
assertEquals(0, stack.size());
assertNull(stack.pop());
}
@Test
public void size_ShouldCountNumberOfItems() throws Exception {
AutoDiscardingStack<Object> stack = new AutoDiscardingStack<>(2);
stack.push(new Object());
stack.push(new Object());
stack.pop();
stack.push(new Object());
assertEquals(2, stack.size());
}
@Test
public void pop_ShouldRetrieveLastElementAdded() throws Exception {
AutoDiscardingStack<Integer> stack = new AutoDiscardingStack<>(2);
stack.push(1);
stack.push(2);
assertEquals(2, (int) stack.pop());
assertEquals(1, (int) stack.pop());
assertEquals(null, stack.pop());
assertEquals(null, stack.pop());
}
@Test
public void emptyProperty_ShouldHaveTheSameValue() throws Exception {
AutoDiscardingStack<Integer> stack = new AutoDiscardingStack<>(2);
assertTrue(stack.emptyProperty().get());
assertEquals(stack.isEmpty(), stack.emptyProperty().get());
stack.push(1);
assertFalse(stack.emptyProperty().get());
assertEquals(stack.isEmpty(), stack.emptyProperty().get());
stack.pop();
assertTrue(stack.emptyProperty().get());
assertEquals(stack.isEmpty(), stack.emptyProperty().get());
}
}
| gpl-3.0 |
gpospelov/BornAgain | mvvm/model/mvvm/model/externalproperty.cpp | 1863 | // ************************************************************************************************
//
// qt-mvvm: Model-view-view-model framework for large GUI applications
//
//! @file mvvm/model/mvvm/model/externalproperty.cpp
//! @brief Implements class CLASS?
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2020
//! @authors Gennady Pospelov et al, Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************************************
#include "mvvm/model/externalproperty.h"
using namespace ModelView;
ExternalProperty::ExternalProperty() = default;
ExternalProperty::ExternalProperty(std::string text, QColor color, std::string id)
: m_text(std::move(text)), m_color(std::move(color)), m_identifier(std::move(id))
{
}
ExternalProperty ExternalProperty::undefined()
{
return ExternalProperty("Undefined", QColor(Qt::red));
}
std::string ExternalProperty::text() const
{
return m_text;
}
QColor ExternalProperty::color() const
{
return m_color;
}
std::string ExternalProperty::identifier() const
{
return m_identifier;
}
bool ExternalProperty::isValid() const
{
return !(m_identifier.empty() && m_text.empty() && !m_color.isValid());
}
bool ExternalProperty::operator==(const ExternalProperty& other) const
{
return m_identifier == other.m_identifier && m_text == other.m_text && m_color == other.m_color;
}
bool ExternalProperty::operator!=(const ExternalProperty& other) const
{
return !(*this == other);
}
bool ExternalProperty::operator<(const ExternalProperty& other) const
{
return m_identifier < other.m_identifier && m_text < other.m_text
&& m_color.name() < other.m_color.name();
}
| gpl-3.0 |
luwrain/luwrain | src/main/java/org/luwrain/core/Sounds.java | 1416 | /*
Copyright 2012-2021 Michael Pozhidaev <[email protected]>
This file is part of LUWRAIN.
LUWRAIN 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.
LUWRAIN 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.
*/
//LWR_API 1.0
package org.luwrain.core;
public enum Sounds
{
ALERT,
ANNOUNCEMENT,
ATTENTION,
BLOCKED,
CANCEL,
CHAT_MESSAGE,
CLICK,
COLLAPSED,
COMMANDER_LOCATION,
COPIED,
CUT,
DELETED,
DESKTOP_ITEM,
DOC_SECTION,
DONE,
EMPTY_LINE,
END_OF_LINE,
ERROR,
EVENT_NOT_PROCESSED,
EXPANDED,
FATAL,
GENERAL_TIME,
INTRO_APP,
INTRO_POPUP,
INTRO_REGULAR,
LIST_ITEM,
MAIN_MENU,
MAIN_MENU_ITEM,
MESSAGE,
NO_APPLICATIONS,
NO_CONTENT,
NO_ITEMS_ABOVE,
NO_ITEMS_BELOW,
NO_LINES_ABOVE,
NO_LINES_BELOW,
OK,
PARAGRAPH,
PASTE,
PICTURE,
PLAYING,
PROTECTED_RESOURCE,
REGION_POINT,
SEARCH,
SELECTED,
SHUTDOWN,
STARTUP,
TABLE_CELL,
TERM_BELL,
UNSELECTED,
}
| gpl-3.0 |
SuperTux/supertux | src/addon/addon_manager.hpp | 3618 | // SuperTux - Add-on Manager
// Copyright (C) 2007 Christoph Sommer <[email protected]>
// 2014 Ingo Ruhnke <[email protected]>
//
// 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/>.
#ifndef HEADER_SUPERTUX_ADDON_ADDON_MANAGER_HPP
#define HEADER_SUPERTUX_ADDON_ADDON_MANAGER_HPP
#include <memory>
#include <string>
#include <vector>
#include "addon/downloader.hpp"
#include "supertux/gameconfig.hpp"
#include "util/currenton.hpp"
class Addon;
using TransferStatusPtr = std::shared_ptr<TransferStatus>;
typedef std::string AddonId;
/** Checks for, installs and removes Add-ons */
class AddonManager final : public Currenton<AddonManager>
{
public:
using AddonList = std::vector<std::unique_ptr<Addon> >;
private:
Downloader m_downloader;
std::string m_addon_directory;
std::string m_repository_url;
std::vector<Config::Addon>& m_addon_config;
AddonList m_installed_addons;
AddonList m_repository_addons;
bool m_has_been_updated;
TransferStatusPtr m_transfer_status;
public:
AddonManager(const std::string& addon_directory,
std::vector<Config::Addon>& addon_config);
~AddonManager() override;
bool has_online_support() const;
bool has_been_updated() const;
void check_online();
TransferStatusPtr request_check_online();
std::vector<AddonId> get_repository_addons() const;
std::vector<AddonId> get_installed_addons() const;
Addon& get_repository_addon(const AddonId& addon) const;
Addon& get_installed_addon(const AddonId& addon) const;
TransferStatusPtr request_install_addon(const AddonId& addon_id);
void install_addon(const AddonId& addon_id);
void uninstall_addon(const AddonId& addon_id);
void enable_addon(const AddonId& addon_id);
void disable_addon(const AddonId& addon_id);
bool is_old_enabled_addon(const std::unique_ptr<Addon>& addon) const;
bool is_old_addon_enabled() const;
void disable_old_addons();
void mount_old_addons();
void unmount_old_addons();
bool is_from_old_addon(const std::string& filename) const;
bool is_addon_installed(const std::string& id) const;
void update();
void check_for_langpack_updates();
#ifdef EMSCRIPTEN
void onDownloadProgress(int id, int loaded, int total);
void onDownloadFinished(int id);
void onDownloadError(int id);
void onDownloadAborted(int id);
#endif
private:
std::vector<std::string> scan_for_archives() const;
void add_installed_addons();
AddonList parse_addon_infos(const std::string& filename) const;
/** add \a archive, given as physfs path, to the list of installed
archives */
void add_installed_archive(const std::string& archive, const std::string& md5);
/** search for an .nfo file in the top level directory that
originates from \a archive, \a archive is a OS path */
std::string scan_for_info(const std::string& archive) const;
private:
AddonManager(const AddonManager&) = delete;
AddonManager& operator=(const AddonManager&) = delete;
};
#endif
/* EOF */
| gpl-3.0 |
bluviolin/TrainMonitor | test/all_tests.py | 341 | import glob
import unittest
def create_test_suite():
test_file_strings = glob.glob('test/test_*.py')
module_strings = ['test.'+str[5:len(str)-3] for str in test_file_strings]
suites = [unittest.defaultTestLoader.loadTestsFromName(name) for name in module_strings]
testSuite = unittest.TestSuite(suites)
return testSuite
| gpl-3.0 |
beezwax/WP-Publish-to-Apple-News | tests/exporter/builders/test-class-component-text-styles.php | 703 | <?php
use \Exporter\Exporter_Content as Exporter_Content;
use \Exporter\Settings as Settings;
use \Exporter\Builders\Component_Text_Styles as Component_Text_Styles;
class Component_Text_Styles_Tests extends PHPUnit_Framework_TestCase {
protected function setup() {
$this->settings = new Settings();
$this->content = new Exporter_Content( 1, 'My Title', '<p>Hello, World!</p>' );
}
public function testBuiltArray() {
$styles = new Component_Text_Styles( $this->content, $this->settings );
$styles->register_style( 'some-name', 'my value' );
$result = $styles->to_array();
$this->assertEquals( 1, count( $result ) );
$this->assertEquals( 'my value', $result[ 'some-name' ] );
}
}
| gpl-3.0 |
sgsdxzy/adc | Debug.cpp | 248 | #include "Debug.h"
void info(string inf)
{
std::cout << "Info: " << inf << std::endl;
}
void warn(string info)
{
std::cerr << "Warning: " << info << std::endl;
}
void err(string info)
{
std::cerr << "Error: " << info << std::endl;
}
| gpl-3.0 |
divyanshgaba/Competitive-Coding | In The Quest of Logic/main.cpp | 541 | #include <iostream>
#include <cstring>
#include <ctype.h>
#include <algorithm>
using namespace std;
int main()
{
int test;
cin>>test;
while(test--)
{
string s;
cin>>s;
reverse(s.begin(),s.end());
int n = s.length();
for(int i =0;i<n;i++)
{
if(islower(s[i]))
cout<<char(s[i]-32);
else if(isupper(s[i]))
cout<<char(s[i]+32);
else
cout<<s[i];
}
cout<<endl;
}
return 0;
}
| gpl-3.0 |
hhoechtl/neos-development-collection | Neos.Neos/Classes/ViewHelpers/Rendering/LiveViewHelper.php | 1134 | <?php
namespace Neos\Neos\ViewHelpers\Rendering;
/*
* This file is part of the Neos.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\ContentRepository\Domain\Model\NodeInterface;
/**
* ViewHelper to find out if Neos is rendering the live website.
*
* = Examples =
*
* Given we are currently seeing the Neos backend:
*
* <code title="Basic usage">
* <f:if condition="{neos:rendering.live()}">
* <f:then>
* Shown outside the backend.
* </f:then>
* <f:else>
* Shown in the backend.
* </f:else>
* </f:if>
* </code>
* <output>
* Shown in the backend.
* </output>
*/
class LiveViewHelper extends AbstractRenderingStateViewHelper
{
/**
* @param NodeInterface $node
* @return boolean
*/
public function render(NodeInterface $node = null)
{
$context = $this->getNodeContext($node);
return $context->isLive();
}
}
| gpl-3.0 |
WohlSoft/PGE-Project | Editor/data_configs/conf_sound.cpp | 3065 | /*
* Platformer Game Engine by Wohlstand, a free platform for game making
* Copyright (c) 2014-2021 Vitaly Novichkov <[email protected]>
*
* 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
* 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/>.
*/
#include <QFile>
#include <main_window/global_settings.h>
#include "data_configs.h"
long DataConfig::getSndI(unsigned long itemID)
{
if((itemID>0) && main_sound.contains(int(itemID)))
return long(itemID);
return 0;
}
void DataConfig::loadSound()
{
unsigned int i;
obj_sound sound;
unsigned long sound_total=0;
QString sound_ini = getFullIniPath("sounds.ini");
if(sound_ini.isEmpty())
return;
IniProcessing soundset(sound_ini);
main_sound.clear(); //Clear old
if(!openSection(&soundset, "sound-main")) return;
{
soundset.read("total", sound_total, 0);
total_data +=sound_total;
}
closeSection(&soundset);
emit progressPartNumber(9);
emit progressMax(int(sound_total));
emit progressValue(0);
emit progressTitle(QObject::tr("Loading Sound..."));
ConfStatus::total_sound = long(sound_total);
if(ConfStatus::total_sound==0)
{
addError(QString("ERROR LOADING sounds.ini: number of items not define, or empty config"), PGE_LogLevel::Critical);
return;
}
//////////////////////////////
main_sound.allocateSlots(int(sound_total));
//Sound
for(i=1; i <= sound_total; i++)
{
bool valid=true;
emit progressValue(int(i));
if(!openSection(&soundset, QString("sound-%1").arg(i).toStdString()) )
break;
{
soundset.read("name", sound.name, "");
if(sound.name.isEmpty())
{
valid = false;
addError(QString("Sound-%1 Item name isn't defined").arg(i));
}
soundset.read("file", sound.file, "");
if(sound.file.isEmpty())
{
valid = false;
addError(QString("Sound-%1 Item file isn't defined").arg(i));
}
sound.hidden = soundset.value("hidden", "0").toBool();
sound.id = i;
main_sound.storeElement(int(i), sound, valid);
}
closeSection(&soundset);
if( soundset.lastError() != IniProcessing::ERR_OK )
{
addError(QString("ERROR LOADING sounds.ini N:%1 (sound %2)").arg(soundset.lastError()).arg(i), PGE_LogLevel::Critical);
break;
}
}
}
| gpl-3.0 |
Rosebotics/pymata-aio | test/test_all.py | 5964 | """
Copyright (c) 2015 Alan Yorinks All rights reserved.
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 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
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
class TestAnalogInput:
board = PyMata3(2)
result = None
def my_callback(self, data):
self.result = data
# print(self.result)
# set pot to maximum to pass and anything else to fail
def test_analog_read_write(self):
# have a potentiometer on A2 and set it to max
self.board.set_pin_mode(2, Constants.ANALOG)
self.board.sleep(1)
av = self.board.analog_read(2)
assert av == 1023
# set pot to maximum to pass and anything else to fail
def test_analog_read_write_cb(self):
# have a potentiometer on A2 and set it to max
self.board.set_pin_mode(2, Constants.ANALOG, self.my_callback)
self.board.sleep(1)
self.board.analog_read(2)
assert self.result == [2, 1023]
# set slide switch to on for pass or off for fail
def test_digital_read_write(self):
self.board.set_pin_mode(13, Constants.INPUT)
self.board.set_pin_mode(6, Constants.OUTPUT)
dv = None
for i in range(0, 5):
dv = self.board.digital_read(13)
self.board.sleep(.1)
self.board.digital_write(6, dv)
assert dv == 1
self.board.sleep(1)
self.board.digital_write(6, 0)
# set slide switch to on for pass or off for fail
def test_digital_read_write_cb(self):
self.board.set_pin_mode(13, Constants.INPUT, self.my_callback)
self.board.set_pin_mode(6, Constants.OUTPUT)
for i in range(0, 5):
# noinspection PyUnusedLocal
dv = self.result
self.board.sleep(.1)
dv = None
self.board.digital_write(6, dv)
assert self.result == [13, 1]
self.board.sleep(1)
self.board.digital_write(6, 0)
self.board.sleep(2)
def test_get_protocol_version(self):
pv = self.board.get_protocol_version()
assert pv == "2.4"
def test_get_protocol_version_cb(self):
self.board.get_protocol_version(self.my_callback)
assert self.result == "2.4"
def test_get_firmware_version(self):
fv = self.board.get_firmware_version()
assert fv == "2.4 FirmataPlus.ino"
def test_get_firmware_version_cb(self):
self.board.get_firmware_version(self.my_callback)
assert self.result == "2.4 FirmataPlus.ino"
def test_get_capability_report(self):
cr = self.board.get_capability_report()
l = len(cr)
assert l == 156
def test_get_capability_report_cb(self):
self.board.get_capability_report(True, self.my_callback)
l = len(self.result)
assert l == 156
def test_get_analog_map(self):
am = self.board.get_analog_map()
l = len(am)
assert l == 20
def test_get_analog_map_cb(self):
self.board.get_analog_map(self.my_callback)
l = len(self.result)
assert l == 20
def test_get_pin_state_mode(self):
self.board.set_pin_mode(5, Constants.OUTPUT)
ps = self.board.get_pin_state(5)
assert ps == [5, 1, 0]
def test_get_pin_state_mode_cb(self):
self.board.set_pin_mode(5, Constants.INPUT)
self.board.get_pin_state(5, self.my_callback)
assert self.result == [5, 0, 0]
def test_servo(self):
# observer that motor moves
# noinspection PyPep8Naming
SERVO_MOTOR = 5 # servo attached to this pin
# configure the servo
self.board.servo_config(SERVO_MOTOR)
for x in range(0, 2):
# move the servo to 20 degrees
self.board.analog_write(SERVO_MOTOR, 20)
self.board.sleep(1)
# move the servo to 100 degrees
self.board.analog_write(SERVO_MOTOR, 100)
self.board.sleep(1)
# move the servo to 20 degrees
self.board.analog_write(SERVO_MOTOR, 20)
ps = self.board.get_pin_state(5)
assert ps == [5, 4, 20]
def test_analog_latch_gt_cb(self):
self.board.set_pin_mode(2, Constants.ANALOG)
self.board.set_analog_latch(2, Constants.LATCH_GTE, 512, self.my_callback)
self.board.sleep(.5)
assert self.result[Constants.LATCH_CALL_BACK_DATA] >= 512
assert self.result[Constants.LATCH_CALL_BACK_PIN] == 'A2'
def test_digital_latch_high_cb(self):
self.board.set_pin_mode(13, Constants.INPUT)
self.board.set_digital_latch(13, 1, self.my_callback)
self.board.sleep(.5)
assert self.result[Constants.LATCH_CALL_BACK_DATA] == 1
assert self.result[Constants.LATCH_CALL_BACK_PIN] == 'D13'
def test_analog_latch_gt(self):
self.board.set_pin_mode(2, Constants.ANALOG)
self.board.set_analog_latch(2, Constants.LATCH_GTE, 512)
self.board.sleep(.5)
l = self.board.get_analog_latch_data(2)
assert l[Constants.LATCHED_DATA] >= 512
def test_digital_latch_high(self):
self.board.set_pin_mode(13, Constants.INPUT)
self.board.set_digital_latch(13, 1)
self.board.sleep(1)
l = self.board.get_digital_latch_data(13)
assert l[Constants.LATCHED_DATA] == 1
| gpl-3.0 |
suiryc/atari-st-tools | src/main/scala/atari/st/disk/MSADisk.scala | 8324 | package atari.st.disk
import atari.st.disk.exceptions.InvalidFormatException
import java.io.{
BufferedOutputStream,
DataInputStream,
DataOutputStream,
EOFException,
FilterInputStream,
FilterOutputStream,
InputStream,
OutputStream
}
object MSADisk {
val magicHeader = 0x0E0F
}
class MSAInputDisk(input: InputStream) {
import MSADisk._
protected val dis = new DataInputStream(input)
if (dis.readUnsignedShort() != magicHeader)
throw new InvalidFormatException("Invalid magic number")
val sectorsPerTrack: Int = dis.readUnsignedShort()
protected val trackSize = sectorsPerTrack * DiskFormat.bytesPerSector
val sides: Int = dis.readUnsignedShort() + 1
val trackStart: Int = dis.readUnsignedShort()
val trackEnd: Int = dis.readUnsignedShort()
val tracks: Int = trackEnd - trackStart + 1
val sectors: Int = sectorsPerTrack * tracks * sides
val size: Int = sectors * DiskFormat.bytesPerSector
val filtered = new FilterInputStream(dis) {
protected var currentTrackSide = 0
protected var trackData: Option[Array[Byte]] = None
protected var trackOffset = 0
protected def nextTrack() =
if (currentTrackSide == tracks * sides) {
trackData = None
trackOffset = 0
false
}
else {
val compressedTrackSize = dis.readUnsignedShort()
val array = trackData getOrElse {
val array = new Array[Byte](trackSize)
trackData = Some(array)
array
}
if (compressedTrackSize == trackSize) {
/* not compressed */
@scala.annotation.tailrec
def loop(offset: Int): Int =
dis.read(array, offset, array.length - offset) match {
case -1 =>
offset
case n =>
val newOffset = offset + n
if (newOffset >= array.length) newOffset
else loop(offset + n)
}
val actual = loop(0)
if (actual != trackSize)
throw new InvalidFormatException(s"Invalid track size: $actual expected $trackSize")
}
else {
/* compressed */
@inline def uncompressedByte(offset: Int, b: Byte) {
if (offset >= trackSize)
throw new InvalidFormatException(s"Invalid compressed track size: can uncompress more than expected $trackSize")
array(offset) = b
}
@scala.annotation.tailrec
def loop(offset: Int, remaining: Int): Int = {
if (remaining <= 0) offset
else dis.read() match {
case -1 =>
offset
case 0xE5 =>
val byte = dis.read().byteValue()
val count = dis.readUnsignedShort()
for (i <- offset until (offset + count))
uncompressedByte(i, byte)
loop(offset + count, remaining - 4)
case v =>
uncompressedByte(offset, v.byteValue)
loop(offset + 1, remaining - 1)
}
}
val actual = loop(0, compressedTrackSize)
if (actual != trackSize)
throw new InvalidFormatException(s"Invalid compressed track size: uncompressed $actual expected $trackSize")
}
currentTrackSide += 1
trackOffset = 0
true
}
protected def ensureData() =
if (trackData.isDefined && (trackOffset < trackSize)) true
else nextTrack()
override def read(): Int =
if (!ensureData()) -1
else {
/* Note: make sure to return the byte value in the range 0-255 as needed */
val r = 0xFF & trackData.get(trackOffset)
trackOffset += 1
r
}
override def read(buf: Array[Byte], off: Int, len: Int): Int = {
@scala.annotation.tailrec
def loop(off: Int, len: Int): Int =
if (len <= 0) len
else if (!ensureData()) len
else {
val array = trackData.get
val need = scala.math.min(len, trackSize - trackOffset)
Array.copy(array, trackOffset, buf, off, need)
trackOffset += need
loop(off + need, len - need)
}
if (len <= 0) 0
else if (!ensureData()) -1
else len - loop(off, len)
}
override def skip(len: Long): Long = {
val buffer = new Array[Byte](1024)
@scala.annotation.tailrec
def loop(remaining: Long): Long =
if (remaining <= 0) remaining
else {
val len = scala.math.min(remaining, buffer.length.toLong).intValue()
val actual = read(buffer, 0, len)
if (actual == -1) remaining
else loop(remaining - actual)
}
if (len <= 0) 0
else len - loop(len)
}
}
}
class MSAOutputDisk(output: OutputStream, format: StandardDiskFormat) {
import MSADisk._
protected val dos = new DataOutputStream(output)
dos.writeShort(magicHeader)
dos.writeShort(format.sectorsPerTrack)
protected val trackSize = format.sectorsPerTrack * DiskFormat.bytesPerSector
dos.writeShort(format.sides - 1)
dos.writeShort(0)
dos.writeShort(format.tracks - 1)
val filtered = new MASOutputStream(new BufferedOutputStream(dos))
class MASOutputStream(out: OutputStream)
extends FilterOutputStream(out)
{
protected var currentTrackSide = 0
protected var trackData: Option[Array[Byte]] = None
protected var trackOffset = 0
protected def nextTrack(track: Array[Byte]) {
val compressed = new Array[Byte](trackSize)
/* Encoding takes 4 bytes:
* - 0xE5 marker
* - 1 byte: value to repeat
* - 2 bytes: repeat count
* Even though encoding a byte repeated 4 times saves no space,
* implementations still do it.
* Thus the rules are:
* - encode a byte if repeated at least 4 times
* - always encode 0xE5 (the marker value)
* - only keep the compressed track if its size is less than the
* uncompressed track
*/
@scala.annotation.tailrec
def compress(compressedOffset: Int, trackOffset: Int): Int =
/* Note: give up as soon as we reach uncompressed track size */
if ((trackOffset == trackSize) || (compressedOffset == trackSize)) compressedOffset
else {
val b = track(trackOffset)
@scala.annotation.tailrec
def loop(trackOffset: Int, repeat: Int): Int =
if (trackOffset == trackSize) repeat
else if (track(trackOffset) == b) loop(trackOffset + 1, repeat + 1)
else repeat
val repeat = loop(trackOffset + 1, 1)
/* Note: *always* encode the marker */
if ((repeat > 4) || (b == 0xE5.byteValue())) {
if (compressedOffset + 4 >= trackSize) trackSize
else {
compressed(compressedOffset) = 0xE5.byteValue()
compressed(compressedOffset + 1) = b
compressed(compressedOffset + 2) = ((repeat >>> 8) & 0xFF).byteValue()
compressed(compressedOffset + 3) = ((repeat >>> 0) & 0xFF).byteValue()
compress(compressedOffset + 4, trackOffset + repeat)
}
}
else {
compressed(compressedOffset) = b
compress(compressedOffset + 1, trackOffset + 1)
}
}
val compressedOffset = compress(0, 0)
if (compressedOffset < trackSize) {
/* compressed */
dos.writeShort(compressedOffset)
dos.write(compressed, 0, compressedOffset)
}
else {
/* not compressed */
dos.writeShort(track.length)
dos.write(track)
}
currentTrackSide += 1
trackOffset = 0
}
override def write(b: Int) {
if (currentTrackSide == format.tracks * format.sides)
throw new EOFException("Cannot write beyond disk format")
val array = trackData getOrElse {
val array = new Array[Byte](trackSize)
trackData = Some(array)
array
}
array(trackOffset) = b.byteValue()
trackOffset += 1
if (trackOffset == trackSize)
nextTrack(array)
}
def checkComplete() {
if (currentTrackSide != format.tracks * format.sides)
throw new EOFException("Did not write full disk")
}
}
}
| gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/modules/catalog/general/store_docs_type.php | 124 | Bitrix 16.5 Business Demo = 03de0fb0c05e2d626d833b8b4188eee0
Bitrix 17.0.9 Business Demo = 898fb8df11129564dd12e4582136fd37
| gpl-3.0 |
RogerRordo/ACM | Source/87.cpp | 8145 | /*
Time: 161205
Prob: ZOJ2107
By RogerRo
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<algorithm>
#include<ctime>
#include<bitset>
#define ll long long
#define tr(i,l,r) for((i)=(l);(i)<=(r);++i)
#define rtr(i,r,l) for((i)=(r);(i)>=(l);--i)
#define oo 0x7F7F7F7F
#define maxpn 100010
#define nonx 1E100
#define eps 1E-8
const double pi=acos(-1.0);
using namespace std;
//===========================================================
int cmp(double x)
{
if (x>eps) return 1;
if (x<-eps) return -1;
return 0;
}
double sqr(double a){return a*a;}
int gcd(int a,int b){return a%b==0?b:gcd(b,a%b);}
//===========================================================
struct point
{
double x,y;
point(){}
point(double a,double b){x=a;y=b;}
friend point operator+(point a,point b){return point(a.x+b.x,a.y+b.y);}
friend point operator-(point a,point b){return point(a.x-b.x,a.y-b.y);}
friend point operator-(point a){return point(-a.x,-a.y);}
friend double operator*(point a,point b){return a.x*b.x+a.y*b.y;}
friend point operator*(double a,point b){return point(a*b.x,a*b.y);}
friend point operator*(point a,double b){return point(a.x*b,a.y*b);}
friend point operator/(point a,double b){return point(a.x/b,a.y/b);}
friend double operator^(point a,point b){return a.x*b.y-a.y*b.x;}
friend bool operator==(point a,point b){return cmp(a.x-b.x)==0&&cmp(a.y-b.y)==0;}
} ;
const point nonp=point(nonx,nonx);
struct line
{
point a,b;
line(){}
line(point pa,point pb){a=pa;b=pb;}
point dir(){return b-a;}
} ;
const line nonl=line(nonp,nonp);
struct circle
{
point o; double r;
circle(){}
circle(point a,double b){o=a;r=b;}
} ;
struct triangle//t 因triangle亦属polygon,故省去许多函数
{
point a,b,c;
triangle(){}
triangle(point ta,point tb,point tc){a=ta;b=tb;c=tc;}
} ;
struct polygon
{
int n; point a[maxpn]; //逆时针!
polygon(){}
polygon(triangle t){n=3;a[1]=t.a;a[2]=t.b;a[3]=t.c;}
point& operator[](int _){return a[_];}
} ;
//===========================================================
double sqr(point a){return a*a;}
double len(point a){return sqrt(sqr(a));} //模长
point rotate(point a,double b){return point(a.x*cos(b)-a.y*sin(b),a.x*sin(b)+a.y*cos(b));} //逆时针旋转
double angle(point a,point b){return acos(a*b/len(a)/len(b));} //夹角
point reflect(point a,point b){return 2*a-b;} //以a为中心对称
//===========================================================
point quad(double A,double B,double C)
{
double delta=sqr(B)-4*A*C;
if (delta<0) return nonp;
return point((-B-sqrt(delta))/(2*A),(-B+sqrt(delta))/(2*A));
}
point proj(point a,line b){double t=(a-b.a)*b.dir()/sqr(b.dir());return point(b.a+t*b.dir());} //垂足
double dist(point a,line b){return ((a-b.a)^(b.b-b.a))/len(b.dir());} //点到线距离
bool onray(point a,line b){return cmp((a-b.a)^b.dir())==0&&cmp((a-b.a)*b.dir())>=0;} //判断点在射线上
bool onseg(point a,line b){return cmp((a-b.a)^b.dir())==0&&cmp((a-b.a)*(a-b.b))<=0;} //判断点在线段上
bool online(point a,line b){return cmp((a-b.a)^b.dir())==0;} //判断点在直线上
bool parallel(line a,line b){return cmp(a.dir()^b.dir())==0;} //判断两线平行
point cross(line a,line b) //线交
{
double t;
if (cmp(t=a.dir()^b.dir())==0) return nonp;
return a.a+((b.a-a.a)^b.dir())/t*a.dir();
}
//===========================================================
double S(circle a){return pi*sqr(a.r);} //面积
double C(circle a){return 2*pi*a.r;} //周长
line cross(line a,circle b) //线圆交
{
point t=quad(sqr(a.dir()),2*a.dir()*(a.a-b.o),sqr(a.a-b.o)-sqr(b.r));
if (t==nonp) return nonl;
return line(a.a+t.x*a.dir(),a.a+t.y*a.dir());
}
int in(point a,circle b){double t=len(a-b.o);return t==b.r?2:t<b.r;} //点与圆位置关系 0外 1内 2上
//line cross(circle a,circle b){}
//line tangent(point a,circle b){}
//pair<line,line> tangent(circle a,circle b){}
//double unionS(int n,circle*a) //圆面积并
//{}
//===========================================================
double S(triangle a){return abs((a.b-a.a)^(a.c-a.a))/2;} //面积
double C(triangle a){return len(a.a-a.b)+len(a.a-a.c)+len(a.a-a.c);} //周长
circle outcircle(triangle a) //外接圆
{
circle res; point t1=a.b-a.a,t2=a.c-a.a;
double t=2*t1^t2;
res.o.x=a.a.x+(sqr(t1)*t2.y-sqr(t2)*t1.y)/t;
res.o.y=a.a.y+(sqr(t2)*t1.x-sqr(t1)*t2.x)/t;
res.r=len(res.o-a.a);
return res;
}
circle incircle(triangle a) //内切圆
{
circle res; double x=len(a.b-a.c),y=len(a.c-a.a),z=len(a.a-a.b);
res.o=(a.a*x+a.b*y+a.c*z)/(x+y+z);
res.r=dist(res.o,line(a.a,a.b));
return res;
}
point gc(triangle a){return (a.a+a.b+a.c)/3;} //重心
point hc(triangle a){return 3*gc(a)-2*outcircle(a).o;} //垂心
//===========================================================
double S(polygon a) //面积 O(n)
{
int i; double res=0;
a[a.n+1]=a[1];
tr(i,1,a.n) res+=a[i]^a[i+1];
return res/2;
}
double C(polygon a) //周长 O(n)
{
int i; double res=0;
a[a.n+1]=a[1];
tr(i,1,a.n) res+=len(a[i+1]-a[i]);
return res;
}
int in(point a,polygon b) //点与多边形位置关系 0外 1内 2上 O(n)
{
int s=0,i,d1,d2,k;
b[b.n+1]=b[1];
tr(i,1,b.n)
{
if (onseg(a,line(b[i],b[i+1]))) return 2;
k=cmp((b[i+1]-b[i])^(b[i]-a));
d1=cmp(b[i].y-a.y);
d2=cmp(b[i+1].y-a.y);
s=s+(k>0&&d2<=0&&d1>0)-(k<0&&d1<=0&&d2>0);
}
return s!=0;
}
point gc(polygon a) //重心 O(n)
{
double s=S(a); point t(0,0); int i;
if (cmp(s)==0) return nonp;
a[a.n+1]=a[1];
tr(i,1,a.n) t=t+(a[i]+a[i+1])*(a[i]^a[i+1]);
return t/s/6;
}
int pick_on(polygon a) //皮克求边上格点数 O(n)
{
int s=0,i;
a[a.n+1]=a[1];
tr(i,1,a.n) s+=gcd(abs(int(a[i+1].x-a[i].x)),abs(int(a[i+1].y-a[i].y)));
return s;
}
int pick_in(polygon a){return int(S(a))+1-pick_on(a)/2;} //皮克求多边形内格点数 O(n)
bool __cmpx(point a,point b){return cmp(a.x-b.x)<0;}
bool __cmpy(point a,point b){return cmp(a.y-b.y)<0;}
double __mindist(point *a,int l,int r)
{
double ans=nonx;
if (l==r) return ans;
int i,j,tl,tr,mid=(l+r)/2;
ans=min(__mindist(a,l,mid),__mindist(a,mid+1,r));
for(tl=mid;tl>=l&&a[tl].x>=a[mid].x-ans;tl--); tl++;
for(tr=mid+1;tr<=r&&a[tr].x<=a[mid].x+ans;tr++); tr--;
sort(a+tl+1,a+tr+1,__cmpy);
tr(i,tl,tr-1) tr(j,i+1,min(tr,i+4)) ans=min(ans,len(a[i]-a[j]));
sort(a+tl+1,a+tr+1,__cmpx);
return ans;
}
double mindist(polygon a) //a只是点集 O(nlogn)
{
sort(a.a+1,a.a+a.n+1,__cmpx);
return __mindist(a.a,1,a.n);
}
//line convex_maxdist(polygon a){}
//polygon convex_hull(polygon a) //a只是点集 O(nlogn)
//{
//}
//int convex_in(point a,polygon b){} //0外 1内 2上 O(logn)
//polygon cross(polygon a,polygon b){}
//polygon cross(line a,polygon b){}
//double unionS(circle a,polygon b){}
circle mincovercircle(polygon a) //最小圆覆盖 O(n)
{
circle t; int i,j,k;
srand(time(0));
random_shuffle(a.a+1,a.a+a.n+1);
for(i=2,t=circle(a[1],0);i<=a.n;i++) if (!in(a[i],t))
for(j=1,t=circle(a[i],0);j<i;j++) if (!in(a[j],t))
for(k=1,t=circle((a[i]+a[j])/2,len(a[i]-a[j])/2);k<j;k++) if (!in(a[k],t))
t=outcircle(triangle(a[i],a[j],a[k]));
return t;
}
//===========================================================
int read()
{
int x=0; bool f=0;
char ch=getchar();
while (ch<'0'||ch>'9') {f|=ch=='-'; ch=getchar();}
while (ch>='0'&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0'; ch=getchar();}
return (x^-f)+f;
}
void write(int x)
{
char a[20],s=0;
if (x==0){putchar('0'); return ;}
if (x<0) {putchar('-'); x=-x;}
while (x) {a[s++]=x%10+'0'; x=x/10;}
while (s--) putchar(a[s]);
}
void writeln(int x){write(x); putchar('\n');}
int main()
{
polygon a; int i;
while (a.n=read())
{
tr(i,1,a.n) scanf("%lf%lf",&a[i].x,&a[i].y);
printf("%.2lf\n",mindist(a)/2);
}
return 0;
}
| gpl-3.0 |
Waikato/moa | moa/src/main/java/moa/clusterers/clustree/Node.java | 10537 | /*
* Node.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Sanchez Villaamil ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.clusterers.clustree;
import java.io.Serializable;
public class Node implements Serializable {
final int NUMBER_ENTRIES = 3;
static int INSERTIONS_BETWEEN_CLEANUPS = 10000;
/**
* The children of this node.
*/
private Entry[] entries;
// Information about the state in the tree.
/**
* The depth at which this <code>Node</code> is in the tree.
*/
private int level;
/**
* Initialze a normal node, which is not fake.
* @param numberDimensions The dimensionality of the data points it
* manipulates.
* @param level The INVERSE level at which this node hangs.
*/
public Node(int numberDimensions, int level) {
this.level = level;
this.entries = new Entry[NUMBER_ENTRIES];
// Generate all entries when we generate a Node.
// That no entry can be null makes it much easier to handle.
for (int i = 0; i < NUMBER_ENTRIES; i++) {
entries[i] = new Entry(numberDimensions);
entries[i].setNode(this);
}
}
/**
* Initialiazes a node which is a fake root depending on the given
* <code>boolean</code>.
* @param numberDimensions The dimensionality of the data points it
* manipulates.
* @param level The level at which this node hangs.
* @param fakeRoot A parameter the says if the node is to be fake or not.
*/
protected Node(int numberDimensions, int numberClasses, int level,
boolean fakeRoot) {
this.level = level;
this.entries = new Entry[NUMBER_ENTRIES];
// Generate all entries when we generate a Node.
// That no entry can be null makes it much easier to handle.
for (int i = 0; i < NUMBER_ENTRIES; i++) {
entries[i] = new Entry(numberDimensions);
}
}
/**
* USED FOR EM_TOP_DOWN BULK LOADING
* @param numberDimensions
* @param level
* @param argEntries
*/
public Node(int numberDimensions, int level, Entry[] argEntries) {
this.level = level;
this.entries = new Entry[NUMBER_ENTRIES];
// Generate all entries when we generate a Node.
// That no entry can be null makes it much easier to handle.
for (int i = 0; i < NUMBER_ENTRIES; i++) {
entries[i] = argEntries[i];
}
}
/**
* Checks if this node is a leaf. A node is a leaf when none of the entries
* in the node have children.
* @return <code>true</code> if the node is leaf, <code>false</code>
* otherwise.
*/
protected boolean isLeaf() {
for (int i = 0; i < entries.length; i++) {
Entry entry = entries[i];
if (entry.getChild() != null) {
return false;
}
}
return true;
}
/**
* Returns the neareast <code>Entry</code> to the given <code>Cluster</code>.
* The distance is minimized over <code>Entry.calcDistance(Cluster)</code>.
* @param buffer The cluster to which the distance has to be compared.
* @return The <code>Entry</code> with minimal distance to the given
* cluster.
* @see ClusKernel
* @see Entry#calcDistance(ClusKernel)
*/
public Entry nearestEntry(ClusKernel buffer) {
// TODO: (Fernando) Adapt the nearestEntry(...) function to the new algorithm.
Entry res = entries[0];
double min = res.calcDistance(buffer);
for (int i = 1; i < entries.length; i++) {
Entry entry = entries[i];
if (entry.isEmpty()) {
break;
}
double distance = entry.calcDistance(buffer);
if (distance < min) {
min = distance;
res = entry;
}
}
return res;
}
/**
* Return the nearest entry to the given one. The
* <code>calcDistance(Entry)</code> function is find the one with the
* shortest distance in this node to the given one.
* @param newEntry The entry to which the entry with the minimal distance
* to it is calculated.
* @return The entry with the minimal distance to the given one.
*/
protected Entry nearestEntry(Entry newEntry) {
assert (!this.entries[0].isEmpty());
Entry res = entries[0];
double min = res.calcDistance(newEntry);
for (int i = 1; i < entries.length; i++) {
if (this.entries[i].isEmpty()) {
break;
}
Entry entry = entries[i];
double distance = entry.calcDistance(newEntry);
if (distance < min) {
min = distance;
res = entry;
}
}
return res;
}
/**
* Return the number of free <code>Entry</code>s in this node.
* @return The number of free <code>Entry</code>s in this node.
* @see Entry
*/
protected int numFreeEntries() {
int res = 0;
for (int i = 0; i < entries.length; i++) {
Entry entry = entries[i];
if (entry.isEmpty()) {
res++;
}
}
assert (NUMBER_ENTRIES == entries.length);
return res;
}
/**
* Add a new <code>Entry</code> to this node. If there is no space left a
* <code>NoFreeEntryException</code> is thrown.
* @param newEntry The <code>Entry</code> to be added.
* @throws RuntimeException Is thrown when there is no space left in
* the node for the new entry.
*/
public void addEntry(Entry newEntry, long currentTime){
newEntry.setNode(this);
int freePosition = getNextEmptyPosition();
entries[freePosition].initializeEntry(newEntry, currentTime);
}
/**
* Returns the position of the next free Entry.
* @return The position of the next free Entry.
* @throws RuntimeException Is thrown when there is no free entry left in
* the node.
*/
private int getNextEmptyPosition(){
int counter;
for (counter = 0; counter < entries.length; counter++) {
Entry e = entries[counter];
if (e.isEmpty()) {
break;
}
}
if (counter == entries.length) {
throw new RuntimeException("Entry added to a node which is already full.");
}
return counter;
}
/**
* If there exists an entry, whose relevance is under the threshold given
* as a parameter to the tree, this entry is returned. Otherwise
* <code>null</code> is returned.
* @return An irrelevant <code>Entry</code> if there exists one,
* <code>null</code> otherwise.
* @see Entry
* @see Entry#isIrrelevant(double)
*/
protected Entry getIrrelevantEntry(double threshold) {
for (int i = 0; i < this.entries.length; i++) {
Entry entry = this.entries[i];
if (entry.isIrrelevant(threshold)) {
return entry;
}
}
return null;
}
/**
* Return an array with references to the children of this node. These are
* not copies, that means side effects are possible!
* @return An array with references to the children of this node.
* @see Entry
*/
public Entry[] getEntries() {
return entries;
}
/**
* Return the level number in the node. This is not the real level. For the
* real level one has to call <code>getLevel(Tree tree)</code>.
* @return The raw level of the node.
* @see #getLevel(ClusTree)
*/
protected int getRawLevel() {
return level;
}
/**
* Returns the level at which this node is in the tree. If a tree is passed
* to which the node does not belonged a value is returned, but it is
* gibberish.
* @param tree The tree to which this node belongs.
* @return The level at which this node hangs.
*/
protected int getLevel(ClusTree tree) {
int numRootSplits = tree.getNumRootSplits();
return numRootSplits - this.getRawLevel();
}
/**
* Clear this Node, which means that the noiseBuffer is cleared, that
* <code>shallowClear</code> is called upon all the entries of the node,
* that the split counter is set to zero and the node is set to not be a
* fake root. Notice that the level stays the same after calling this
* function.
* @see ClusKernel#clear()
* @see Entry#shallowClear()
*/
// Level stays the same.
protected void clear() {
for (int i = 0; i < NUMBER_ENTRIES; i++) {
entries[i].shallowClear();
}
}
/**
* Merge the two entries at the given position. The entries are reordered in
* the <code>entries</code> array so that the non-empty entries are still
* at the beginning.
* @param pos1 The position of the first entry to be merged. This position
* has to be smaller than the the second position.
* @param pos2 The position of the second entry to be merged. This position
* has to be greater than the the first position.
*/
protected void mergeEntries(int pos1, int pos2) {
assert (this.numFreeEntries() == 0);
assert (pos1 < pos2);
this.entries[pos1].mergeWith(this.entries[pos2]);
for (int i = pos2; i < entries.length - 1; i++) {
entries[i] = entries[i + 1];
}
entries[entries.length - 1].clear();
}
protected void makeOlder(long currentTime, double negLambda) {
for (int i = 0; i < this.entries.length; i++) {
Entry entry = this.entries[i];
if (entry.isEmpty()) {
break;
}
entry.makeOlder(currentTime, negLambda);
}
}
}
| gpl-3.0 |
huangshucheng/WXHBTools2.0 | app/src/main/java/com/junyou/hbks/utils/AccessibilityUtil.java | 2811 | package com.junyou.hbks.utils;
import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.view.accessibility.AccessibilityNodeInfo;
import java.util.List;
public class AccessibilityUtil {
/** 通过id查找*/
public static AccessibilityNodeInfo findNodeInfosById(AccessibilityNodeInfo nodeInfo, String resId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(resId);
if(list != null && !list.isEmpty()) {
return list.get(0);
}
}
return null;
}
/** 通过文本查找*/
public static AccessibilityNodeInfo findNodeInfosByText(AccessibilityNodeInfo nodeInfo, String text) {
List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText(text);
if(list == null || list.isEmpty()) {
return null;
}
return list.get(0);
}
/** 返回主界面事件*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void performHome(AccessibilityService service) {
if(service == null) {
return;
}
service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void performRecentApp(AccessibilityService service){
if(service == null) {
return;
}
service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
}
/**
* 返回桌面
*/
public static void gotoDeskTop(AccessibilityService service)
{
try{
Intent home = new Intent(Intent.ACTION_MAIN);
home.addCategory(Intent.CATEGORY_HOME);
home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
service.getApplicationContext().startActivity(home);
}catch (Exception e){
e.printStackTrace();
}
}
/** 返回事件*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void performBack(AccessibilityService service) {
if(service == null) {
return;
}
service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
}
/** 点击事件*/
public static void performClick(AccessibilityNodeInfo nodeInfo) {
if(nodeInfo == null) {
return;
}
if(nodeInfo.isClickable()) {
// LogUtil.i("可点击。。。。。。");
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
} else {
// LogUtil.i("不可点击TTTTTTTTTT");
performClick(nodeInfo.getParent());
}
}
}
| gpl-3.0 |
zuonima/sql-utils | src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableEnableLifecycle.java | 1272 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.ast.statement;
import com.alibaba.druid.sql.ast.SQLObjectImpl;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
import java.util.ArrayList;
import java.util.List;
public class SQLAlterTableEnableLifecycle extends SQLObjectImpl implements SQLAlterTableItem {
private final List<SQLAssignItem> partition = new ArrayList<SQLAssignItem>(4);
public List<SQLAssignItem> getPartition() {
return partition;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, partition);
}
visitor.endVisit(this);
}
}
| gpl-3.0 |
cy92830/DataTypeGUI | src/scripts/dts/union.js | 113 | // dts/union.js
// Add a union type
export function Add (count, parent) {
console.warn('Not yet finished!')
}
| gpl-3.0 |
ocd-jacobs/swift | lib/swift_classes/swift_message_header.rb | 1335 | # ******************************************************************************
# File : SWIFT_MESSAGE_HEADER.RB
# ------------------------------------------------------------------------------
# Author : J.M. Jacobs
# Date : 03 March 2014
# Version : 1.0
#
# (C) 2014: 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/>.
#
# Notes : Class representing a Swift MT940 message header
# ******************************************************************************
require_relative 'swift_line'
module SwiftClasses
class SwiftMessageHeader < SwiftLine
def convert
@fields[ :tag ] = 'header'
@fields[ :header ] = raw
end
end
end
| gpl-3.0 |
PhilippSchlieper/CONRAD | src/edu/stanford/rsl/tutorial/praktikum/OpenCLBackprojection.java | 6524 | package edu.stanford.rsl.tutorial.praktikum;
import ij.ImageJ;
import java.io.IOException;
import java.io.InputStream;
import java.nio.FloatBuffer;
import com.jogamp.opencl.CLBuffer;
import com.jogamp.opencl.CLCommandQueue;
import com.jogamp.opencl.CLContext;
import com.jogamp.opencl.CLDevice;
import com.jogamp.opencl.CLImage2d;
import com.jogamp.opencl.CLImageFormat;
import com.jogamp.opencl.CLKernel;
import com.jogamp.opencl.CLProgram;
import com.jogamp.opencl.CLImageFormat.ChannelOrder;
import com.jogamp.opencl.CLImageFormat.ChannelType;
import com.jogamp.opencl.CLMemory.Mem;
import edu.stanford.rsl.conrad.data.numeric.Grid1D;
import edu.stanford.rsl.conrad.data.numeric.Grid2D;
import edu.stanford.rsl.conrad.data.numeric.opencl.OpenCLGrid2D;
import edu.stanford.rsl.conrad.opencl.OpenCLUtil;
public class OpenCLBackprojection {
public static Grid2D reconstructionCL(int worksize, int[] size, float[] spacing, double deltaS, float maxS, int maxTheta, double deltaTheta, Grid2D rampFilteredSinogram) throws IOException {
float deltaSFl = (float)deltaS;
float deltaThetaFl = (float)deltaTheta;
OpenCLExercise obj = new OpenCLExercise();
OpenCLGrid2D sinoCL = obj.convertGrid(rampFilteredSinogram);
// allocate the resulting grid
OpenCLGrid2D result = new OpenCLGrid2D(new Grid2D(size[0],size[1]));
float[] imgSize = new float[size.length];
imgSize[0] = size[0];
imgSize[1] = size[1];
// Create the context
CLContext context = OpenCLUtil.getStaticContext();
// Get the fastest device from context
CLDevice device = context.getMaxFlopsDevice();
// Create the command queue
CLCommandQueue commandQueue = device.createCommandQueue();
//InputStream is = OpenCLGridTest.class
// Load and compile the cl-code and create the kernel function
InputStream is = OpenCLBackprojection.class.getResourceAsStream("openCLBackprojector.cl");
CLProgram program = context.createProgram(is).build();
CLKernel kernelFunction = program.createCLKernel("backprojectorKernel");
// Create the OpenCL Grids and set their texture
// Grid1
CLBuffer<FloatBuffer> sinoCLImgSize = context.createFloatBuffer(imgSize.length, Mem.READ_ONLY);
sinoCLImgSize.getBuffer().put(imgSize);
sinoCLImgSize.getBuffer().rewind();
// Create the CLBuffer for the grids
CLImageFormat format = new CLImageFormat(ChannelOrder.INTENSITY, ChannelType.FLOAT);
// make sure OpenCL is turned on / and things are on the device
sinoCL.getDelegate().prepareForDeviceOperation();
sinoCL.getDelegate().getCLBuffer().getBuffer().rewind();
// Create and set the texture
CLImage2d<FloatBuffer> sinoCLTex = null;
sinoCLTex = context.createImage2d(sinoCL.getDelegate().getCLBuffer().getBuffer(), size[0], size[1], format, Mem.READ_ONLY);
sinoCL.getDelegate().release();
sinoCL.getDelegate().getCLBuffer().getBuffer().rewind();
// Grid3
result.getDelegate().prepareForDeviceOperation();
result.getDelegate().getCLBuffer().getBuffer().rewind();
float [] imsize = new float[(int)(imgSize[0]*imgSize[1])];
CLBuffer<FloatBuffer> result2 = context.createFloatBuffer((int)(imgSize[0]*imgSize[1]), Mem.WRITE_ONLY);
result2.getBuffer().put(imsize).rewind();
// Write memory on the GPU
commandQueue
.putWriteImage(sinoCLTex, true) // writes the first texture
.putReadBuffer(result.getDelegate().getCLBuffer(), true) // writes the third image buffer
.putWriteBuffer(sinoCLImgSize, true)
.finish();
// Write kernel parameters
kernelFunction.rewind();
kernelFunction
.putArg(sinoCLTex)
.putArg(result2)
.putArg(sinoCLImgSize)
.putArg(maxTheta)
.putArg(maxS)
.putArg(deltaSFl)
.putArg(deltaThetaFl)
.putArg(spacing[0])
.putArg(spacing[1]);
// Check correct work group sizes
int bpBlockSize[] = {worksize,worksize};
int maxWorkGroupSize = device.getMaxWorkGroupSize();
int[] realLocalSize = new int[] {Math.min((int)Math.pow(maxWorkGroupSize, 1/2.0),
bpBlockSize[0]),Math.min((int)Math.pow(maxWorkGroupSize, 1/2.0), bpBlockSize[1])};
// rounded up to the nearest multiple of localWorkSize
int[] globalWorkSize = new int[]{OpenCLUtil.roundUp(realLocalSize[0], (int)imgSize[0]), OpenCLUtil.roundUp(realLocalSize[1],(int)imgSize[1])};
// execute kernel
commandQueue.putWriteImage(sinoCLTex,true).finish();
commandQueue.put2DRangeKernel(kernelFunction, 0, 0, globalWorkSize[0], globalWorkSize[1], realLocalSize[0], realLocalSize[1]).finish();
commandQueue.putReadBuffer(result2,true).finish();
//lesen
result2.getBuffer().get(imsize);
//result2.getDelegate().notifyDeviceChange();
Grid2D resultGrid = new Grid2D(imsize,size[0],size[1]);
return resultGrid;
}
public static void main(String[] args){
new ImageJ();
// Size of the grid
int[] size = new int[] {128,128};
double [] spacing = {1,1};
float [] spacingConv = {1,1};
Phantom phantom = new Phantom(size[0],size[1],spacing);
int sizeX = phantom.getSize()[0];
int sizeY = phantom.getSize()[1];
phantom.show("The phantom");
ParallelBeam parallel = new ParallelBeam();
// size of the phantom
double angularRange = 180;
// number of projection images
int projectionNumber = 180;
// detector size in pixel
float detectorSize = 512;
// size of a detector Element [mm]
double detectorSpacing = 1.0f;
Grid2D sino = parallel.projectRayDriven(phantom, projectionNumber, detectorSpacing, detectorSize, angularRange);
sino.show("The Unfiltered Sinogram");
// Ramp Filtering
Grid2D rampFilteredSinogram = new Grid2D(sino);
for (int theta = 0; theta < sino.getSize()[1]; ++theta) //sino.getSize()[1];
{
// Filter each line of the sinogram independently
Grid1D tmp = parallel.rampFiltering(sino.getSubGrid(theta), detectorSpacing);
for(int i = 0; i < tmp.getSize()[0]; i++)
{
rampFilteredSinogram.putPixelValue(i, theta, tmp.getAtIndex(i));
}
}
rampFilteredSinogram.show("The Ramp Filtered Sinogram");
Grid2D recon;
try {
recon = reconstructionCL(32, size, spacingConv, detectorSpacing, detectorSize, projectionNumber, angularRange, rampFilteredSinogram);
recon.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | gpl-3.0 |
julianmaster/TinyRL | src/model/turns/TurnComponent.java | 989 | package model.turns;
import model.entities.ResolveTurnEvent;
import pattern.Component;
import pattern.Engine;
import pattern.Event;
public abstract class TurnComponent implements Component {
private int energy = 0;
private int energyNeedToAction = 100;
private int reduceEnergyNeedToAction = 0;
public TurnComponent() {
}
public TurnComponent(int energyNeedToAction) {
this.energyNeedToAction = energyNeedToAction;
}
@Override
public void process(Event e, double deltaTime) {
if(e instanceof TickTurnEvent) {
TickTurnEvent tickTurnEvent = (TickTurnEvent)e;
energy++;
if(energy >= energyNeedToAction - reduceEnergyNeedToAction) {
energy -= energyNeedToAction - reduceEnergyNeedToAction;
Engine.getInstance().addHeadEvent(new PerformTurnControllerEvent());
Engine.getInstance().addHeadEvent(new ResolveTurnEvent(tickTurnEvent.getEntity()));
}
else {
Engine.getInstance().addHeadEvent(new NextTickTurnControllerEvent());
}
}
}
}
| gpl-3.0 |
dparks1134/PETs | source/MCQD.hpp | 3437 | /*
Copyright 2007-2012 Janez Konc
If you use this program, please cite:
Janez Konc and Dusanka Janezic. An improved branch and bound algorithm for the
maximum clique problem. MATCH Commun. Math. Comput. Chem., 2007, 58, 569-590.
More information at: http://www.sicmm.org/~konc
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/>.
*/
#pragma once
class Maxclique
{
const bool* const* e;
int pk, level;
const float Tlimit;
class Vertices
{
class Vertex
{
int i, d;
public:
void set_i(const int ii) { i = ii; }
int get_i() const { return i; }
void set_degree(int dd) { d = dd; }
int get_degree() const { return d; }
};
Vertex *v;
int sz;
static bool desc_degree(const Vertex vi, const Vertex vj) { return (vi.get_degree() > vj.get_degree()); }
public:
Vertices(int size) : sz(0) { v = new Vertex[size]; }
~Vertices () {}
void dispose() { if (v) delete [] v; }
void sort() { std::sort(v, v+sz, desc_degree); }
void init_colors();
void set_degrees(Maxclique&);
int size() const { return sz; }
void push(const int ii) { v[sz++].set_i(ii); };
void pop() { sz--; };
Vertex& at(const int ii) const { return v[ii]; };
Vertex& end() const { return v[sz - 1]; };
};
class ColorClass
{
int *i;
int sz;
public:
ColorClass() : sz(0), i(0) {}
ColorClass(const int sz) : sz(sz), i(0) { init(sz); }
~ColorClass() { if (i) delete [] i; }
void init(const int sz) { i = new int[sz]; rewind(); }
void push(const int ii) { i[sz++] = ii; };
void pop() { sz--; };
void rewind() { sz = 0; };
int size() const { return sz; }
int& at(const int ii) const { return i[ii]; }
ColorClass& operator=(const ColorClass& dh) {
for (int j = 0; j < dh.sz; j++) i[j] = dh.i[j];
sz = dh.sz;
return *this;
}
};
Vertices V;
ColorClass *C, QMAX, Q;
class StepCount
{
int i1, i2;
public:
StepCount() : i1(0), i2(0) {}
void set_i1(const int ii) { i1 = ii; }
int get_i1() const { return i1; }
void set_i2(const int ii) { i2 = ii; }
int get_i2() const { return i2; }
void inc_i1() { i1++; }
};
StepCount *S;
bool connection(const int i, const int j) const { return e[i][j]; }
bool cut1(const int, const ColorClass&);
void cut2(const Vertices&, Vertices&);
void color_sort(Vertices&);
void expand(Vertices);
void expand_dyn(Vertices);
void _mcq(int*&, int&, bool);
void degree_sort(Vertices &R) { R.set_degrees(*this); R.sort(); }
public:
Maxclique(const bool* const*, const int, const float=0.025);
int steps() const { return pk; }
void mcq(int* &maxclique, int &sz) { _mcq(maxclique, sz, false); }
void mcqdyn(int* &maxclique, int &sz) { _mcq(maxclique, sz, true); }
~Maxclique();
}; | gpl-3.0 |
Anisorf/ENCODE | encode/src/org/wandora/application/tools/extractors/europeana/EuropeanaExtractor.java | 2838 | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2015 Wandora Team
*
* 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 org.wandora.application.tools.extractors.europeana;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
/**
*
* @author nlaitinen
*/
public class EuropeanaExtractor extends AbstractEuropeanaExtractor {
private EuropeanaExtractorUI ui = null;
@Override
public void execute(Wandora wandora, Context context) {
try {
if(ui == null) {
ui = new EuropeanaExtractorUI();
}
ui.open(wandora, context);
if(ui.wasAccepted()) {
WandoraTool[] extrs = null;
try{
extrs = ui.getExtractors(this);
} catch(Exception e) {
log(e.getMessage());
return;
}
if(extrs != null && extrs.length > 0) {
setDefaultLogger();
int c = 0;
log("Performing Europeana API query...");
for(int i=0; i<extrs.length && !forceStop(); i++) {
try {
WandoraTool e = extrs[i];
e.setToolLogger(getDefaultLogger());
e.execute(wandora);
setState(EXECUTE);
c++;
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
else {
log("Couldn't find a suitable subextractor to perform or there was an error with an extractor.");
}
}
}
catch(Exception e) {
singleLog(e);
}
if(ui != null && ui.wasAccepted()) setState(WAIT);
else setState(CLOSE);
}
}
| gpl-3.0 |
fbusabiaga/fluam | src/simpleCubic.cpp | 1620 | // Filename: simpleCubic.cpp
//
// Copyright (c) 2010-2016, Florencio Balboa Usabiaga
//
// This file is part of Fluam
//
// Fluam 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.
//
// Fluam 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 Fluam. If not, see <http://www.gnu.org/licenses/>.
#include "header.h"
#include "cells.h"
#include "particles.h"
void simpleCubic(const int dimension){
double dx, dy, dz;
int nx, ny, nz, n;
if(dimension == 3){
sigma = pow(lx*ly*lz/(np),1./3.);
nz = (int(lz/sigma) ? int(lz/sigma) : 1);
}
else{
sigma = sqrt(lx*ly/np);
nz = 1;
}
nx = (int(lx/sigma) ? int(lx/sigma) : 1);
ny = (int(ly/sigma) ? int(ly/sigma) : 1);
while((nx*ny*nz)<np){
if((nx*ny*nz)<np) nx++;
if((nx*ny*nz)<np) ny++;
if((nx*ny*nz)<np) nz++;
}
dx = lx/double(nx);
dy = ly/double(ny);
dz = lz/double(nz);
n = 0;
for (int i=0;i<=nz-1;i++){
for(int j=0;j<=ny-1;j++){
for(int k=0;k<=nx-1;k++){
if(n<np){
n = n + 1;
rxParticle[n-1] = (k + 0.5) * dx - lx/2.;
ryParticle[n-1] = (j + 0.5) * dy - ly/2.;
rzParticle[n-1] = (i + 0.5) * dz - lz/2.;
}
}
}
}
}
| gpl-3.0 |
crcro/librenms | includes/html/table/sensors-common.php | 7595 | <?php
/*
* LibreNMS
*
* 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. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*
* @package LibreNMS
* @subpackage webui
* @link http://librenms.org
* @copyright 2018 LibreNMS
* @author LibreNMS Contributors
*/
use LibreNMS\Config;
$graph_type = mres($vars['graph_type']);
$unit = mres($vars['unit']);
$class = mres($vars['class']);
$sql = " FROM `$table` AS S, `devices` AS D";
$sql .= " WHERE S.sensor_class=? AND S.device_id = D.device_id ";
$param[] = mres($vars['class']);
if (!Auth::user()->hasGlobalRead()) {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$sql .= " AND `D`.`device_id` IN " .dbGenPlaceholders(count($device_ids));
$param = array_merge($param, $device_ids);
}
if (isset($searchPhrase) && !empty($searchPhrase)) {
$sql .= " AND (`D`.`hostname` LIKE ? OR `sensor_descr` LIKE ? OR `sensor_current` LIKE ?)";
$param[] = "%$searchPhrase%";
$param[] = "%$searchPhrase%";
$param[] = "%$searchPhrase";
}
$count_sql = "SELECT COUNT(`sensor_id`) $sql";
$count = dbFetchCell($count_sql, $param);
if (empty($count)) {
$count = 0;
}
if (!isset($sort) || empty($sort)) {
$sort = '`D`.`hostname`, `S`.`sensor_descr`';
}
$sql .= " ORDER BY $sort";
if (isset($current)) {
$limit_low = (($current * $rowCount) - ($rowCount));
$limit_high = $rowCount;
}
if ($rowCount != -1) {
$sql .= " LIMIT $limit_low,$limit_high";
}
$sql = "SELECT * $sql";
foreach (dbFetchRows($sql, $param) as $sensor) {
$alert = '';
if (!isset($sensor['sensor_current'])) {
$sensor['sensor_current'] = 'NaN';
} elseif ((!is_null($sensor['sensor_limit']) && $sensor['sensor_current'] >= $sensor['sensor_limit']) ||
(!is_null($sensor['sensor_limit_low']) && $sensor['sensor_current'] <= $sensor['sensor_limit_low'])
) {
$alert = '<i class="fa fa-flag fa-lg" style="color:red" aria-hidden="true"></i>';
}
// FIXME - make this "four graphs in popup" a function/include and "small graph" a function.
// FIXME - So now we need to clean this up and move it into a function. Isn't it just "print-graphrow"?
// FIXME - DUPLICATED IN device/overview/sensors
$graph_colour = str_replace('#', '', $row_colour);
$graph_array = array();
$graph_array['height'] = '100';
$graph_array['width'] = '210';
$graph_array['to'] = Config::get('time.now');
$graph_array['id'] = $sensor['sensor_id'];
$graph_array['type'] = $graph_type;
$graph_array['from'] = Config::get('time.day');
$graph_array['legend'] = 'no';
$link_array = $graph_array;
$link_array['page'] = 'graphs';
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link_graph = generate_url($link_array);
$link = generate_url(array('page' => 'device', 'device' => $sensor['device_id'], 'tab' => $group, 'metric' => $sensor['sensor_class']));
$overlib_content = '<div style="width: 580px;"><span class="overlib-text">'.$sensor['hostname'].' - '.$sensor['sensor_descr'].'</span>';
foreach (array('day', 'week', 'month', 'year') as $period) {
$graph_array['from'] = Config::get("time.$period");
$overlib_content .= str_replace('"', "\\'", generate_graph_tag($graph_array));
}
$overlib_content .= '</div>';
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
// the 00 at the end makes the area transparent.
$graph_array['from'] = Config::get('time.day');
$sensor_minigraph = generate_lazy_graph_tag($graph_array);
$sensor['sensor_descr'] = substr($sensor['sensor_descr'], 0, 48);
$sensor_current = $graph_type == 'sensor_state' ? get_state_label($sensor) : get_sensor_label_color($sensor, $translations);
$response[] = array(
'hostname' => generate_device_link($sensor),
'sensor_descr' => overlib_link($link, $sensor['sensor_descr'], $overlib_content, null),
'graph' => overlib_link($link_graph, $sensor_minigraph, $overlib_content, null),
'alert' => $alert,
'sensor_current' => $sensor_current,
'sensor_limit_low' => is_null($sensor['sensor_limit_low']) ? '-' :
'<span class=\'label label-default\'>' . trim(format_si($sensor['sensor_limit_low']) . $unit) . '</span>',
'sensor_limit' => is_null($sensor['sensor_limit']) ? '-' :
'<span class=\'label label-default\'>' . trim(format_si($sensor['sensor_limit']) . $unit) . '</span>',
);
if ($vars['view'] == 'graphs') {
$daily_graph = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.day') . '&to=' . Config::get('time.now') . '&width=211&height=100';
$daily_url = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.day') . '&to=' . Config::get('time.now') . '&width=400&height=150';
$weekly_graph = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.week') . '&to=' . Config::get('time.now') . '&width=211&height=100';
$weekly_url = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.week') . '&to=' . Config::get('time.now') . '&width=400&height=150';
$monthly_graph = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.month') . '&to=' . Config::get('time.now') . '&width=211&height=100';
$monthly_url = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.month') . '&to=' . Config::get('time.now') . '&width=400&height=150';
$yearly_graph = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.year') . '&to=' . Config::get('time.now') . '&width=211&height=100';
$yearly_url = 'graph.php?id=' . $sensor['sensor_id'] . '&type=' . $graph_type . '&from=' . Config::get('time.year') . '&to=' . Config::get('time.now') . '&width=400&height=150';
$response[] = array(
'hostname' => "<a onmouseover=\"return overlib('<img src=\'$daily_url\'>', LEFT);\" onmouseout=\"return nd();\">
<img src='$daily_graph' border=0></a> ",
'sensor_descr' => "<a onmouseover=\"return overlib('<img src=\'$weekly_url\'>', LEFT);\" onmouseout=\"return nd();\">
<img src='$weekly_graph' border=0></a> ",
'graph' => "<a onmouseover=\"return overlib('<img src=\'$monthly_url\'>', LEFT);\" onmouseout=\"return nd();\">
<img src='$monthly_graph' border=0></a>",
'alert' => '',
'sensor_current' => "<a onmouseover=\"return overlib('<img src=\'$yearly_url\'>', LEFT);\" onmouseout=\"return nd();\">
<img src='$yearly_graph' border=0></a>",
'sensor_range' => '',
);
} //end if
}//end foreach
$output = array(
'current' => $current,
'rowCount' => $rowCount,
'rows' => $response,
'total' => $count,
);
echo _json_encode($output);
| gpl-3.0 |
nulloy/nulloy | src/aboutDialog.cpp | 7564 | /********************************************************************
** Nulloy Music Player, http://nulloy.com
** Copyright (C) 2010-2022 Sergey Vlasov <[email protected]>
**
** This program can be distributed under the terms of the GNU
** General Public License version 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the
** following information to ensure the GNU General Public License
** version 3.0 requirements will be met:
**
** http://www.gnu.org/licenses/gpl-3.0.html
**
*********************************************************************/
#include "aboutDialog.h"
#include <QCoreApplication>
#include <QFile>
#include <QLabel>
#include <QPushButton>
#include <QSpacerItem>
#include <QTabWidget>
#include <QTextBrowser>
#include <QTextStream>
#include <QVBoxLayout>
#ifdef Q_OS_MAC
#include <QBitmap>
#endif
NAboutDialog::NAboutDialog(QWidget *parent) : QDialog(parent)
{
// clang-format off
QString aboutHtml = QString() +
#ifdef Q_OS_MAC
"<span style=\"font-size:14pt;\">" +
#else
"<span style=\"font-size:9pt;\">" +
#endif
"<b>" + QCoreApplication::applicationName() + " Music Player</b>" +
"<br>" +
"<a href='http://" + QCoreApplication::organizationDomain() + "'>http://" +
QCoreApplication::organizationDomain() + "</a>" +
"</span><br><br>" +
#ifdef Q_OS_MAC
"<span style=\"font-size:10pt;\">" +
#else
"<span style=\"font-size:8pt;\">" +
#endif
tr("Version: ") + QCoreApplication::applicationVersion() +
"<br><br>" +
"Copyright (C) 2010-2018 Sergey Vlasov <[email protected]>" +
"</span>";
// clang-format on
setWindowTitle(QObject::tr("About ") + QCoreApplication::applicationName());
setMaximumSize(0, 0);
QVBoxLayout *layout = new QVBoxLayout;
setLayout(layout);
QTabWidget *tabWidget = new QTabWidget(parent);
layout->addWidget(tabWidget);
// about tab >>
QWidget *aboutTab = new QWidget;
tabWidget->addTab(aboutTab, tr("Common"));
QVBoxLayout *aboutTabLayout = new QVBoxLayout;
aboutTab->setLayout(aboutTabLayout);
QLabel *iconLabel = new QLabel;
QPixmap pixmap(":icon-96.png");
iconLabel->setPixmap(pixmap);
#ifdef Q_OS_MAC
iconLabel->setMask(pixmap.mask());
#endif
QHBoxLayout *iconLayout = new QHBoxLayout;
iconLayout->addStretch();
iconLayout->addWidget(iconLabel);
iconLayout->addStretch();
aboutTabLayout->addLayout(iconLayout);
QTextBrowser *aboutTextBrowser = new QTextBrowser;
aboutTextBrowser->setObjectName("aboutTextBrowser");
aboutTextBrowser->setStyleSheet("background: transparent");
aboutTextBrowser->setFrameShape(QFrame::NoFrame);
aboutTextBrowser->setMinimumWidth(350);
aboutTextBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
aboutTextBrowser->setOpenExternalLinks(true);
aboutTextBrowser->setHtml("<center>" + aboutHtml + "</center>");
aboutTabLayout->addWidget(aboutTextBrowser);
// << about tab
// thanks tab >>
QWidget *thanksTab = new QWidget;
tabWidget->addTab(thanksTab, tr("Thanks"));
QVBoxLayout *thanksTabLayout = new QVBoxLayout;
thanksTabLayout->setContentsMargins(0, 0, 0, 0);
thanksTab->setLayout(thanksTabLayout);
QFile thanksFile(":/THANKS");
thanksFile.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream thanksStream(&thanksFile);
QString thanksText = thanksStream.readAll();
thanksText.replace(QRegExp("(\\w)\\n(\\w)"), "\\1 \\2");
thanksText.remove("\n\n\n");
thanksFile.close();
QTextBrowser *thanksTextBrowser = new QTextBrowser;
thanksTextBrowser->setText(thanksText);
thanksTabLayout->addWidget(thanksTextBrowser);
// << thanks tab
// changelog tab >>
QWidget *changelogTab = new QWidget;
tabWidget->addTab(changelogTab, tr("Changelog"));
QVBoxLayout *changelogTabLayout = new QVBoxLayout;
changelogTabLayout->setContentsMargins(0, 0, 0, 0);
changelogTab->setLayout(changelogTabLayout);
QFile changelogFile(":/ChangeLog");
changelogFile.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream changelogStream(&changelogFile);
QString changelogHtml = changelogStream.readAll();
changelogHtml.replace("\n", "<br>\n");
changelogHtml.replace(QRegExp("(\\*[^<]*)(<br>)"), "<b>\\1</b>\\2");
changelogFile.close();
QTextBrowser *changelogTextBrowser = new QTextBrowser;
changelogTextBrowser->setHtml(changelogHtml);
changelogTextBrowser->setOpenExternalLinks(true);
changelogTabLayout->addWidget(changelogTextBrowser);
// << changelog tab
// license tab >>
QWidget *licenseTab = new QWidget;
tabWidget->addTab(licenseTab, tr("License"));
QVBoxLayout *licenseTabLayout = new QVBoxLayout;
licenseTab->setLayout(licenseTabLayout);
// clang-format off
QString licenseHtml =
#ifdef Q_OS_MAC
"<span style=\"font-size:10pt;\">"
#else
"<span style=\"font-size:8pt;\">"
#endif
"This program is free software: you can redistribute it and/or modify "
"it under the terms of the GNU General Public License version 3.0 "
"as published by the Free Software Foundation.<br>"
"<br>"
"This program is distributed in the hope that it will be useful, "
"but <b>WITHOUT ANY WARRANTY</b>; without even the implied warranty of "
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the "
"GNU General Public License for more details.<br>"
"<br>"
"You should have received a copy of the GNU General Public License "
"along with this program. If not, see "
"<a href='http://www.gnu.org/licenses/gpl-3.0.html'>http://www.gnu.org/licenses/gpl-3.0.html</a>."
"</span>";
// clang-format on
QTextBrowser *licenseTextBrowser = new QTextBrowser;
licenseTextBrowser->setObjectName("licenseTextBrowser");
licenseTextBrowser->setStyleSheet("background: transparent");
licenseTextBrowser->setFrameShape(QFrame::NoFrame);
licenseTextBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
licenseTextBrowser->setOpenExternalLinks(true);
licenseTextBrowser->setAlignment(Qt::AlignVCenter);
licenseTextBrowser->setHtml(licenseHtml);
licenseTabLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
licenseTabLayout->addWidget(licenseTextBrowser);
licenseTabLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
// << license tab
QPushButton *closeButton = new QPushButton(tr("Close"));
connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addStretch();
buttonLayout->addWidget(closeButton);
buttonLayout->addStretch();
layout->addLayout(buttonLayout);
}
NAboutDialog::~NAboutDialog() {}
void NAboutDialog::show()
{
QDialog::show();
// resize according to content
foreach (QString objectName, QStringList() << "aboutTextBrowser"
<< "licenseTextBrowser") {
QTextBrowser *textBrowser = parent()->findChild<QTextBrowser *>(objectName);
QSize textSize = textBrowser->document()->size().toSize();
textBrowser->setMinimumHeight(textSize.height());
}
}
| gpl-3.0 |
FrankM1/qazana | includes/extensions/dynamictags-acf/tags/acf-gallery.php | 1677 | <?php
namespace Qazana\Extensions\Tags;
use Qazana\Controls_Manager;
use Qazana\Core\DynamicTags\Data_Tag;
use Qazana\Extensions\DynamicTags_ACF as ACF;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class ACF_Gallery extends Data_Tag {
public function get_name() {
return 'acf-gallery';
}
public function get_title() {
return sprintf( '%s (%s)', __( 'ACF', 'qazana' ), __( 'Gallery Field', 'qazana' ) );
}
public function get_categories() {
return [ ACF::GALLERY_CATEGORY ];
}
public function get_group() {
return ACF::ACF_GROUP;
}
public function get_panel_template_setting_key() {
return 'key';
}
public function get_value( array $options = [] ) {
$key = $this->get_settings( 'key' );
$images = [];
if ( ! empty( $key ) ) {
list( $field_key, $meta_key ) = explode( ':', $key );
if ( 'options' === $field_key ) {
$field = get_field_object( $meta_key, $field_key );
} else {
$field = get_field_object( $field_key );
}
if ( $field ) {
$value = $field['value'];
} else {
// Field settings has been deleted or not available.
$value = get_field( $meta_key );
}
if ( is_array( $value ) && ! empty( $value ) ) {
foreach ( $value as $image ) {
$images[] = [
'id' => $image['ID'],
];
}
}
}
return $images;
}
protected function _register_controls() {
$this->add_control(
'key',
[
'label' => __( 'Key', 'qazana' ),
'type' => Controls_Manager::SELECT,
'groups' => ACF::get_control_options( $this->get_supported_fields() ),
]
);
}
protected function get_supported_fields() {
return [
'gallery',
];
}
}
| gpl-3.0 |
miguelalba/sbml_pmf | src/main/java/org/sbml/jsbml/ext/pmf/CompartmentMetaData.java | 4338 | package org.sbml.jsbml.ext.pmf;
import org.sbml.jsbml.AbstractSBase;
import org.sbml.jsbml.PropertyUndefinedError;
import org.sbml.jsbml.util.StringTools;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/**
* Extended meta data for a {@link org.sbml.jsbml.Compartment}
* <p>
* Example: <code><compartmentMetaData source="7" detail="some details" /></code>
*
* @author Miguel Alba
* @date 9.09.2016
*/
public class CompartmentMetaData extends AbstractSBase {
/**
* Integer code from the PMF matrix vocabulary.
*/
private Integer source;
/**
* Description of the compartment.
*/
private String detail;
/**
* Creates a CompartmentMetaData instance.
*/
public CompartmentMetaData() {
packageName = PmfConstants.shortLabel;
}
public CompartmentMetaData(int level, int version) {
super(level, version);
packageName = PmfConstants.shortLabel;
}
/**
* Clone constructor.
*/
public CompartmentMetaData(CompartmentMetaData obj) {
super(obj);
source = obj.source;
detail = obj.detail;
}
/**
* Clones this class.
*/
@Override
public CompartmentMetaData clone() {
return new CompartmentMetaData(this);
}
@Override
public Map<String, String> writeXMLAttributes() {
Map<String, String> attributes = new TreeMap<>();
if (isSetSource()) {
attributes.put(PmfConstants.compartment_source, source.toString());
}
if (isSetDetail()) {
attributes.put(PmfConstants.compartment_detail, detail);
}
return attributes;
}
@Override
public boolean readAttribute(String attributeName, String prefix, String value) {
switch (attributeName) {
case PmfConstants.compartment_source:
source = StringTools.parseSBMLInt(value);
return true;
case PmfConstants.compartment_detail:
detail = value;
return true;
default:
return false;
}
}
@Override
public String toString() {
String sb = PmfConstants.compartmentMetaData + " [";
sb += PmfConstants.compartment_source + "=\"" + (isSetSource() ? source : "") + "\" ";
sb += PmfConstants.compartment_detail + "=\"" + (isSetDetail() ? detail : "") + "\"]";
return sb;
}
// --- source attribute ---
public int getSource() {
if (isSetSource())
return source;
throw new PropertyUndefinedError(PmfConstants.compartment_source, this);
}
public boolean isSetSource() {
return source != null;
}
public void setSource(int source) {
Integer oldSource = this.source;
this.source = source;
firePropertyChange(PmfConstants.compartment_source, oldSource, this.source);
}
public boolean unsetSource() {
if (isSetSource()) {
Integer oldSource = this.source;
this.source = null;
firePropertyChange(PmfConstants.compartment_source, oldSource, this.source);
return true;
}
return false;
}
// --- detail attribute ---
public String getDetail() {
return isSetDetail() ? detail : null;
}
public boolean isSetDetail() {
return detail != null;
}
public void setDetail(String detail) {
String oldDetail = this.detail;
this.detail = detail;
firePropertyChange(PmfConstants.compartment_detail, oldDetail, this.detail);
}
public boolean unsetDetail() {
if (isSetDetail()) {
String oldDetail = this.detail;
this.detail = null;
firePropertyChange(PmfConstants.compartment_detail, oldDetail, this.detail);
return true;
}
return false;
}
@Override
public boolean equals(Object object) {
if (object == null || getClass() != object.getClass())
return false;
CompartmentMetaData other = (CompartmentMetaData) object;
return Objects.equals(source, other.source) && Objects.equals(detail, other.detail);
}
@Override
public int hashCode() {
return Objects.hash(source, detail);
}
}
| gpl-3.0 |
RobertGollagher/Freeputer | pre-alpha/pre-alpha2.0/dev/fvm/js/prg-pc-cell-0.js | 3370 | var prgSrc = `
/*
Copyright 2017, Robert Gollagher.
SPDX-License-Identifier: GPL-3.0+
Program: prg.js (also known as 'prg.c')
Author : Robert Gollagher [email protected]
Created: 20170911
Updated: 20180410+
------------------
FREE:
LAST SYMBOL: g6
------------------
NOTES:
- Radical experiment has partially begun: generic stacks (see far below).
- This is written in an assembly language which aims to be C-compatible.
- This is a demonstration program for FVM2 pre-alpha (see 'fvm2.js').
- The assembler is very simplistic (see 'fvma.js') and uses little memory.
- m0.x0 is the only forward reference the assembler allows
- x symbols are exported from a module (e.g. x0 in m1 is m1.x0)
- u symbols are local to a module (u0..uff)
- s symbols are local to a unit (s0..sff)
- Units begin with u{ and end with }u
- Modules begin with m{ and end with }m
- Modules are named by mod(m1)
- The C-preprocessor would replace u{ with { __label__ s0, s1 ...
- TODO Enforce use of u{ keyword prior to any locals
- See 'fvma.js' for further caveats
*/
m{ mod(m1) /*forward*/ jump(m0.x0) }m
m{ mod(m2) /*incs*/
// ( n1 -- n2 ) doIncs
// Increment n1 times to give the number of increments n2.
// This is only to test that the VM is working correctly.
u{ x1: cpush lit(0x0) s0: inc rpt(s0) ret }u
// ( -- 0x100000 ) doManyIncs
// Do 1,048,576 increments to test VM performance.
// Temporarily disable tracing while doing so.
// See browser console for timer output.
u{ x2: lit(0x100000) troff call(x1) /*doIncs*/ tron ret }u
}m
m{ mod(m3) /*io*/
// ( n -- ) send
// Output n to stdout or fail if not possible.
u{ s0: fail x1: out(s0) ret }u
// ( -- ) sendA
// Output 'A' to stdout
u{ x2: lit(0x41) call(x1) /*send*/ ret }u
// ( n -- ) nInOut
// Output to stdout no more than n characters from stdin.
u{ s0: fail u1: cpush s1: in(s0) call(x1) /*send*/ rpt(s1) ret }u
// ( -- ) max9InOut
// Output to stdout no more than 9 characters from stdin.
u{ x3: lit(0x9) call(u1) /*nInOut*/ ret }u
}m
// Testing remapping of module names -----------------------------------------
m{ mod(m4) /*foo*/
// ( -- ) banana
u{ x1: nop ret }u
// ( -- ) nopHalt
u{ x2: nop halt }u
}m
m{ mod(m5) /*bar*/
// ( -- ) peach
u{ x1: call(m4.x1) /*foo.banana*/ ret }u
}m
// ---------------------------------------------------------------------------
m{ mod(m0) /*run*/
u{
x0:
sp(0x100) // Radical experiment
lit(0x12345678)
/*
The following result in the same flow control. A simple jump:
jump(m4.x2)
Or jumping by copying the destination address into cell 0 (i.e. the PC):
lit(0x0)
lit(m4.x2)
put
*/
lit(0x0)
lit(m4.x2)
put
halt
// TODO NEXT: add another instruction rp(0x200), to declare
// the location of the return stack. Thereafter the sp() and rp()
// instructions can be used to generically use multiple
// stacks programmatically within the VM without
// requiring the VM implementation itself to
// provide any fixed number of stacks.
lit(0x3) call(m2.x1) /*incs.doIncs*/ // Do 3 increments
lit(0x41) add call(m3.x1) /*io.send*/ // Output 'D' by addition
call(m5.x1) /*bar.peach*/
halt
}u
}m
`;
| gpl-3.0 |
gohdan/DFC | known_files/hashes/upload/admin/controller/setting/store.php | 156 | OpenCart 2.1.0.2 = 1f086d120a8e340c0f32763511ef5b2f
OpenCart 2.0.1.1 = ed2fea10cb9b3f20e9a1dfdf4d884ef6
OpenCart 2.0.3.1 = 7508279473356b426db0620dcded20f4
| gpl-3.0 |
ownport/ansible-lookups | src/lookups/lookup/lines.py | 701 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import subprocess
from lookups.lookup import LookupError
from lookups.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
ret = []
for term in terms:
p = subprocess.Popen(term, cwd=self._loader.get_basedir(), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode == 0:
ret.extend(stdout.splitlines())
else:
raise LookupError("lookup.lines(%s) returned %d" % (term, p.returncode))
return ret
| gpl-3.0 |
google-code/biocode | fasta/fasta_size_distribution_plot.py | 3921 | #!/usr/bin/env python3.2
import argparse
import matplotlib
# back-end options are here: http://matplotlib.sourceforge.net/faq/usage_faq.html#what-is-a-backend
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import os
import re
def fasta_entry_sizes(file):
seq_lengths = []
## these are reset as each seq entry is encountered
seq_lines = []
seq_count = 0
for line in open(file, 'r'):
if re.match('^\>', line):
seq_count += 1
seq = ''.join(seq_lines)
seq = re.sub(r'\s', '', seq)
seq_lengths.append( len(seq) )
seq_lines = []
else:
seq_lines.append(line)
return seq_lengths
def get_legend_labels(label_arg, file_count):
labels = []
if label_arg is not None:
labels = label_arg.split(',')
if len(labels) != file_count:
raise Exception("Error: number of input files doesn't match number of labels specified in --legend_names")
return labels
def main():
parser = argparse.ArgumentParser( description='Put a description of your script here')
parser.add_argument('fasta_files', metavar='N', type=str, nargs='+', help='Pass one or more FASTA files')
parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output file to be created' )
parser.add_argument('-t', '--title', type=str, required=False, default='FASTA size distribution', \
help='Pass a title for the graph')
parser.add_argument('-b', '--bin_count', type=int, required=False, default=30, \
help='Data will be placed into this many bins. This is the default behavior. ' + \
'Alternatively, use --bin_size and --bin_max')
parser.add_argument('-s', '--bin_size', type=int, required=False, default=0, \
help='Instead of a --bin_count, use this to specify the size of your bins.')
parser.add_argument('-m', '--bin_max', type=int, required=False, default=0, \
help='If specifying --bin_size, you can optionally use this to limit the ' + \
'maximum bound of your bins (prevents long tails in plots)')
parser.add_argument('-l', '--legend_names', type=str, required=False, help='For a legend with labels ' + \
'of each of your datasets, pass a comma-separated list with no spaces.')
args = parser.parse_args()
data_ranges = []
fasta_files = args.fasta_files
size_max = 0
seqs_above_size_max = 0
for fasta_file in fasta_files:
print("INFO: parsing seq lengths in file: {0}".format(fasta_file))
sizes = fasta_entry_sizes(fasta_file)
print("INFO: {0} sequences found in {1}".format(len(sizes), fasta_file))
data_ranges.append(sizes)
this_max_size = max(sizes)
if this_max_size > size_max:
size_max = this_max_size
## calculate the bins. default is to use the bin_count
bin_opt = args.bin_count
if args.bin_size != 0:
bin_opt = []
for bin_min in range(args.bin_size, size_max, args.bin_size):
if args.bin_max == 0 or args.bin_max > bin_min:
bin_opt.append(bin_min)
if args.bin_max > bin_min:
seqs_above_size_max += 1
plot.xlabel('Sequence size (bins)')
plot.ylabel('Sequence counts')
plot.title(args.title)
n, bins, patches = plot.hist( data_ranges, bin_opt, normed=0, histtype='bar' )
plot.grid(True)
legend_labels = get_legend_labels( args.legend_names, len(fasta_files) )
if len(legend_labels) > 0:
plot.legend(legend_labels)
plot.savefig(args.output_file)
print("INFO: there were {0} data points above the range defined in the histogram".format(seqs_above_size_max))
if __name__ == '__main__':
main()
| gpl-3.0 |
gluster/gmc | src/org.gluster.storage.management.client/src/org/gluster/storage/management/client/UsersClient.java | 3308 | /*******************************************************************************
* Copyright (c) 2006-2011 Gluster, Inc. <http://www.gluster.com>
* This file is part of Gluster Management Console.
*
* Gluster Management Console 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.
*
* Gluster Management Console is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*******************************************************************************/
package org.gluster.storage.management.client;
import static org.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_NEW_PASSWORD;
import static org.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_OLD_PASSWORD;
import org.gluster.storage.management.core.constants.RESTConstants;
import org.gluster.storage.management.core.exceptions.GlusterRuntimeException;
import org.gluster.storage.management.core.model.Status;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.core.util.Base64;
public class UsersClient extends AbstractClient {
private String generateSecurityToken(String user, String password) {
return new String(Base64.encode(user + ":" + password));
}
public UsersClient() {
super();
}
public void authenticate(String user, String password) {
setSecurityToken(generateSecurityToken(user, password));
fetchSubResource(user, Status.class);
}
public void changePassword(String user, String oldPassword, String newPassword) {
String oldSecurityToken = getSecurityToken();
String newSecurityToken = generateSecurityToken(user, oldPassword);
if(!oldSecurityToken.equals(newSecurityToken)) {
throw new GlusterRuntimeException("Invalid old password!");
}
Form form = new Form();
form.add(FORM_PARAM_OLD_PASSWORD, oldPassword);
form.add(FORM_PARAM_NEW_PASSWORD, newPassword);
putRequest(user, form);
// password changed. set the new security token
setSecurityToken(generateSecurityToken(user, newPassword));
//authenticate(user, newPassword);
}
public static void main(String[] args) {
UsersClient authClient = new UsersClient();
// authenticate user
authClient.authenticate("gluster", "gluster");
// change password to gluster1
authClient.changePassword("gluster", "gluster", "gluster1");
// change it back to gluster
authClient.changePassword("gluster", "gluster1", "gluster");
System.out.println("success");
}
/*
* (non-Javadoc)
*
* @see org.gluster.storage.management.client.AbstractClient#getResourceName()
*/
@Override
public String getResourcePath() {
return RESTConstants.RESOURCE_USERS;
}
/*
* (non-Javadoc)
*
* @see org.gluster.storage.management.client.AbstractClient#getSecurityToken()
*/
@Override
public String getSecurityToken() {
return super.getSecurityToken();
}
}
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-47.js | 875 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-47.js
* @description Object.create - 'enumerable' property of one property in 'Properties' is not present (8.10.5 step 3)
*/
function testcase() {
var accessed = false;
var newObj = Object.create({}, {
prop: {}
});
for (var property in newObj) {
if (property === "prop") {
accessed = true;
}
}
return !accessed;
}
runTestCase(testcase);
| gpl-3.0 |
jimcunderwood/MissionPlanner | Mavlink/MAVLink.cs | 128357 | using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections; // hashs
using System.Diagnostics; // stopwatch
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Drawing;
using System.Threading;
using MissionPlanner.Controls;
using System.ComponentModel;
using log4net;
using MissionPlanner.Comms;
using MissionPlanner.Utilities;
using System.Windows.Forms;
using MissionPlanner.HIL;
namespace MissionPlanner
{
public class MAVLinkInterface: MAVLink, IDisposable
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ICommsSerial BaseStream { get; set; }
public ICommsSerial MirrorStream { get; set; }
public event EventHandler ParamListChanged;
/// <summary>
/// used to prevent comport access for exclusive use
/// </summary>
public bool giveComport { get { return _giveComport; } set { _giveComport = value; } }
bool _giveComport = false;
public Dictionary<string, MAV_PARAM_TYPE> param_types = new Dictionary<string, MAV_PARAM_TYPE>();
internal string plaintxtline = "";
string buildplaintxtline = "";
public event ProgressEventHandler Progress;
public MAVState MAV = new MAVState();
public class MAVState
{
public MAVState()
{
this.sysid = 0;
this.compid = 0;
this.param = new Hashtable();
this.packets = new byte[0x100][];
this.packetseencount = new int[0x100];
this.aptype = 0;
this.apname = 0;
this.recvpacketcount = 0;
this.VersionString = "";
this.SoftwareVersions = "";
this.SerialString = "";
}
// all
public string VersionString { get; set; }
// px4+ only
public string SoftwareVersions { get; set; }
// px4+ only
public string SerialString { get; set; }
/// <summary>
/// the static global state of the currently connected MAV
/// </summary>
public CurrentState cs = new CurrentState();
/// <summary>
/// mavlink remote sysid
/// </summary>
public byte sysid { get; set; }
/// <summary>
/// mavlink remove compid
/// </summary>
public byte compid { get; set; }
/// <summary>
/// storage for whole paramater list
/// </summary>
public Hashtable param { get; set; }
/// <summary>
/// storage of a previous packet recevied of a specific type
/// </summary>
public byte[][] packets { get; set; }
public int[] packetseencount { get; set; }
/// <summary>
/// mavlink ap type
/// </summary>
public MAV_TYPE aptype { get; set; }
public MAV_AUTOPILOT apname { get; set; }
public Common.ap_product Product_ID { get { if (param.ContainsKey("INS_PRODUCT_ID")) return (Common.ap_product)(float)param["INS_PRODUCT_ID"]; return Common.ap_product.AP_PRODUCT_ID_NONE; } }
/// <summary>
/// used as a snapshot of what is loaded on the ap atm. - derived from the stream
/// </summary>
public Dictionary<int, mavlink_mission_item_t> wps = new Dictionary<int, mavlink_mission_item_t>();
public Dictionary<int, mavlink_rally_point_t> rallypoints = new Dictionary<int, mavlink_rally_point_t>();
public Dictionary<int, mavlink_fence_point_t> fencepoints = new Dictionary<int, mavlink_fence_point_t>();
/// <summary>
/// Store the guided mode wp location
/// </summary>
public mavlink_mission_item_t GuidedMode = new mavlink_mission_item_t();
internal int recvpacketcount = 0;
}
public double CONNECT_TIMEOUT_SECONDS = 30;
/// <summary>
/// progress form to handle connect and param requests
/// </summary>
ProgressReporterDialogue frmProgressReporter;
/// <summary>
/// used for outbound packet sending
/// </summary>
internal int packetcount = 0;
/// <summary>
/// used to calc packets per second on any single message type - used for stream rate comparaison
/// </summary>
public double[] packetspersecond { get; set; }
/// <summary>
/// time last seen a packet of a type
/// </summary>
DateTime[] packetspersecondbuild = new DateTime[256];
private readonly Subject<int> _bytesReceivedSubj = new Subject<int>();
private readonly Subject<int> _bytesSentSubj = new Subject<int>();
/// <summary>
/// Observable of the count of bytes received, notified when the bytes themselves are received
/// </summary>
public IObservable<int> BytesReceived { get { return _bytesReceivedSubj; } }
/// <summary>
/// Observable of the count of bytes sent, notified when the bytes themselves are received
/// </summary>
public IObservable<int> BytesSent { get { return _bytesSentSubj; } }
/// <summary>
/// Observable of the count of packets skipped (on reception),
/// calculated from periods where received packet sequence is not
/// contiguous
/// </summary>
public Subject<int> WhenPacketLost { get; set; }
public Subject<int> WhenPacketReceived { get; set; }
/// <summary>
/// used as a serial port write lock
/// </summary>
volatile object objlock = new object();
/// <summary>
/// used for a readlock on readpacket
/// </summary>
volatile object readlock = new object();
/// <summary>
/// time seen of last mavlink packet
/// </summary>
public DateTime lastvalidpacket { get; set; }
/// <summary>
/// old log support
/// </summary>
bool oldlogformat = false;
/// <summary>
/// mavlink version
/// </summary>
byte mavlinkversion = 0;
/// <summary>
/// turns on console packet display
/// </summary>
public bool debugmavlink { get; set; }
/// <summary>
/// enabled read from file mode
/// </summary>
public bool logreadmode { get; set; }
public DateTime lastlogread { get; set; }
public BinaryReader logplaybackfile { get; set; }
public BufferedStream logfile { get; set; }
public BufferedStream rawlogfile { get; set; }
int bps1 = 0;
int bps2 = 0;
public int bps { get; set; }
public DateTime bpstime { get; set; }
float synclost;
internal float packetslost = 0;
internal float packetsnotlost = 0;
DateTime packetlosttimer = DateTime.MinValue;
public MAVLinkInterface()
{
// init fields
this.BaseStream = new SerialPort();
this.packetcount = 0;
this.packetspersecond = new double[0x100];
this.packetspersecondbuild = new DateTime[0x100];
this._bytesReceivedSubj = new Subject<int>();
this._bytesSentSubj = new Subject<int>();
this.WhenPacketLost = new Subject<int>();
this.WhenPacketReceived = new Subject<int>();
this.readlock = new object();
this.lastvalidpacket = DateTime.MinValue;
this.oldlogformat = false;
this.mavlinkversion = 0;
this.debugmavlink = false;
this.logreadmode = false;
this.lastlogread = DateTime.MinValue;
this.logplaybackfile = null;
this.logfile = null;
this.rawlogfile = null;
this.bps1 = 0;
this.bps2 = 0;
this.bps = 0;
this.bpstime = DateTime.MinValue;
this.packetslost = 0f;
this.packetsnotlost = 0f;
this.packetlosttimer = DateTime.MinValue;
this.lastbad = new byte[2];
}
public void Close()
{
try
{
if (logfile != null)
logfile.Close();
}
catch { }
try
{
if (rawlogfile != null)
rawlogfile.Close();
}
catch { }
try
{
if (logplaybackfile != null)
logplaybackfile.Close();
}
catch { }
try
{
if (BaseStream.IsOpen)
BaseStream.Close();
}
catch { }
}
public void Open()
{
Open(false);
}
public void Open(bool getparams)
{
if (BaseStream.IsOpen)
return;
frmProgressReporter = new ProgressReporterDialogue
{
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
Text = "Connecting Mavlink"
};
if (getparams)
{
frmProgressReporter.DoWork += FrmProgressReporterDoWorkAndParams;
}
else
{
frmProgressReporter.DoWork += FrmProgressReporterDoWorkNOParams;
}
frmProgressReporter.UpdateProgressAndStatus(-1, "Mavlink Connecting...");
ThemeManager.ApplyThemeTo(frmProgressReporter);
frmProgressReporter.RunBackgroundOperationAsync();
if (ParamListChanged != null)
{
ParamListChanged(this, null);
}
}
void FrmProgressReporterDoWorkAndParams(object sender, ProgressWorkerEventArgs e, object passdata = null)
{
OpenBg(sender,true, e);
}
void FrmProgressReporterDoWorkNOParams(object sender, ProgressWorkerEventArgs e, object passdata = null)
{
OpenBg(sender,false, e);
}
private void OpenBg(object PRsender, bool getparams, ProgressWorkerEventArgs progressWorkerEventArgs)
{
frmProgressReporter.UpdateProgressAndStatus(-1, "Mavlink Connecting...");
giveComport = true;
// allow settings to settle - previous dtr
System.Threading.Thread.Sleep(500);
// reset
MAV.sysid = 0;
MAV.compid = 0;
MAV.param = new Hashtable();
MAV.packets.Initialize();
MAV.VersionString = "";
MAV.SoftwareVersions = "";
MAV.SerialString = "";
bool hbseen = false;
try
{
BaseStream.ReadBufferSize = 16 * 1024;
lock (objlock) // so we dont have random traffic
{
log.Info("Open port with " + BaseStream.PortName + " " + BaseStream.BaudRate);
BaseStream.Open();
BaseStream.DiscardInBuffer();
// other boards seem to have issues if there is no delay? posible bootloader timeout issue
Thread.Sleep(1000);
}
byte[] buffer = new byte[0];
byte[] buffer1 = new byte[0];
DateTime start = DateTime.Now;
DateTime deadline = start.AddSeconds(CONNECT_TIMEOUT_SECONDS);
var countDown = new System.Timers.Timer { Interval = 1000, AutoReset = false };
countDown.Elapsed += (sender, e) =>
{
int secondsRemaining = (deadline - e.SignalTime).Seconds;
//if (Progress != null)
// Progress(-1, string.Format("Trying to connect.\nTimeout in {0}", secondsRemaining));
frmProgressReporter.UpdateProgressAndStatus(-1, string.Format("Trying to connect.\nTimeout in {0}", secondsRemaining));
if (secondsRemaining > 0) countDown.Start();
};
countDown.Start();
int count = 0;
while (true)
{
if (progressWorkerEventArgs.CancelRequested)
{
progressWorkerEventArgs.CancelAcknowledged = true;
countDown.Stop();
if (BaseStream.IsOpen)
BaseStream.Close();
giveComport = false;
return;
}
// incase we are in setup mode
//BaseStream.WriteLine("planner\rgcs\r");
log.Info(DateTime.Now.Millisecond + " Start connect loop ");
if (DateTime.Now > deadline)
{
//if (Progress != null)
// Progress(-1, "No Heatbeat Packets");
countDown.Stop();
this.Close();
if (hbseen)
{
progressWorkerEventArgs.ErrorMessage = "Only 1 Heatbeat Received";
throw new Exception("Only 1 Mavlink Heartbeat Packets was read from this port - Verify your hardware is setup correctly\nMission Planner waits for 2 valid heartbeat packets before connecting");
}
else
{
progressWorkerEventArgs.ErrorMessage = "No Heatbeat Packets Received";
throw new Exception(@"Can not establish a connection\n
Please check the following
1. You have firmware loaded
2. You have the correct serial port selected
3. PX4 - You have the microsd card installed
4. Try a diffrent usb port\n\n"+"No Mavlink Heartbeat Packets where read from this port - Verify Baud Rate and setup\nMission Planner waits for 2 valid heartbeat packets before connecting");
}
}
System.Threading.Thread.Sleep(1);
// incase we are in setup mode
//BaseStream.WriteLine("planner\rgcs\r");
// can see 2 heartbeat packets at any time, and will connect - was one after the other
if (buffer.Length == 0)
buffer = getHeartBeat();
// incase we are in setup mode
//BaseStream.WriteLine("planner\rgcs\r");
System.Threading.Thread.Sleep(1);
if (buffer1.Length == 0)
buffer1 = getHeartBeat();
if (buffer.Length > 0 || buffer1.Length > 0)
hbseen = true;
count++;
if (buffer.Length > 5 && buffer1.Length > 5 && buffer[3] == buffer1[3] && buffer[4] == buffer1[4])
{
mavlink_heartbeat_t hb = buffer.ByteArrayToStructure<mavlink_heartbeat_t>(6);
if (hb.type != (byte)MAVLink.MAV_TYPE.GCS)
{
mavlinkversion = hb.mavlink_version;
MAV.aptype = (MAV_TYPE)hb.type;
MAV.apname = (MAV_AUTOPILOT)hb.autopilot;
setAPType();
MAV.sysid = buffer[3];
MAV.compid = buffer[4];
MAV.recvpacketcount = buffer[2];
log.InfoFormat("ID sys {0} comp {1} ver{2}", MAV.sysid, MAV.compid, mavlinkversion);
break;
}
}
}
countDown.Stop();
frmProgressReporter.UpdateProgressAndStatus(0, "Getting Params.. (sysid " + MAV.sysid + " compid " + MAV.compid + ") ");
if (getparams)
{
getParamListBG();
}
if (frmProgressReporter.doWorkArgs.CancelAcknowledged == true)
{
giveComport = false;
if (BaseStream.IsOpen)
BaseStream.Close();
return;
}
}
catch (Exception e)
{
try
{
BaseStream.Close();
}
catch { }
giveComport = false;
if (string.IsNullOrEmpty(progressWorkerEventArgs.ErrorMessage))
progressWorkerEventArgs.ErrorMessage = "Connect Failed";
log.Error(e);
throw;
}
//frmProgressReporter.Close();
giveComport = false;
frmProgressReporter.UpdateProgressAndStatus(100, "Done.");
log.Info("Done open " + MAV.sysid + " " + MAV.compid);
packetslost = 0;
synclost = 0;
}
public byte[] getHeartBeat()
{
giveComport = true;
DateTime start = DateTime.Now;
int readcount = 0;
while (true)
{
byte[] buffer = readPacket();
readcount++;
if (buffer.Length > 5)
{
//log.Info("getHB packet received: " + buffer.Length + " btr " + BaseStream.BytesToRead + " type " + buffer[5] );
if (buffer[5] == (byte)MAVLINK_MSG_ID.HEARTBEAT)
{
mavlink_heartbeat_t hb = buffer.ByteArrayToStructure<mavlink_heartbeat_t>(6);
if (hb.type != (byte)MAVLink.MAV_TYPE.GCS)
{
giveComport = false;
return buffer;
}
}
}
if (DateTime.Now > start.AddMilliseconds(2200) || readcount > 200) // was 1200 , now 2.2 sec
{
giveComport = false;
return new byte[0];
}
}
}
public void sendPacket(object indata)
{
bool validPacket = false;
byte a = 0;
foreach (Type ty in MAVLink.MAVLINK_MESSAGE_INFO)
{
if (ty == indata.GetType())
{
validPacket = true;
generatePacket(a, indata);
return;
}
a++;
}
if (!validPacket)
{
log.Info("Mavlink : NOT VALID PACKET sendPacket() " + indata.GetType().ToString());
}
}
/// <summary>
/// Generate a Mavlink Packet and write to serial
/// </summary>
/// <param name="messageType">type number = MAVLINK_MSG_ID</param>
/// <param name="indata">struct of data</param>
void generatePacket(byte messageType, object indata)
{
if (!BaseStream.IsOpen)
{
return;
}
lock (objlock)
{
byte[] data;
data = MavlinkUtil.StructureToByteArray(indata);
//Console.WriteLine(DateTime.Now + " PC Doing req "+ messageType + " " + this.BytesToRead);
byte[] packet = new byte[data.Length + 6 + 2];
packet[0] = 254;
packet[1] = (byte)data.Length;
packet[2] = (byte)packetcount;
packetcount++;
packet[3] = 255; // this is always 255 - MYGCS
packet[4] = (byte)MAV_COMPONENT.MAV_COMP_ID_MISSIONPLANNER;
packet[5] = messageType;
int i = 6;
foreach (byte b in data)
{
packet[i] = b;
i++;
}
ushort checksum = MavlinkCRC.crc_calculate(packet, packet[1] + 6);
checksum = MavlinkCRC.crc_accumulate(MAVLINK_MESSAGE_CRCS[messageType], checksum);
byte ck_a = (byte)(checksum & 0xFF); ///< High byte
byte ck_b = (byte)(checksum >> 8); ///< Low byte
packet[i] = ck_a;
i += 1;
packet[i] = ck_b;
i += 1;
if (BaseStream.IsOpen)
{
BaseStream.Write(packet, 0, i);
_bytesSentSubj.OnNext(i);
}
try
{
if (logfile != null && logfile.CanWrite)
{
lock (logfile)
{
byte[] datearray = BitConverter.GetBytes((UInt64)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds * 1000));
Array.Reverse(datearray);
logfile.Write(datearray, 0, datearray.Length);
logfile.Write(packet, 0, i);
}
}
}
catch { }
/*
if (messageType == (byte)MAVLink.MSG_NAMES.REQUEST_DATA_STREAM)
{
try
{
BinaryWriter bw = new BinaryWriter(File.OpenWrite("serialsent.raw"));
bw.Seek(0, SeekOrigin.End);
bw.Write(packet, 0, i);
bw.Write((byte)'\n');
bw.Close();
}
catch { } // been getting errors from this. people must have it open twice.
}*/
}
}
public bool Write(string line)
{
lock (objlock)
{
BaseStream.Write(line);
}
_bytesSentSubj.OnNext(line.Length);
return true;
}
/// <summary>
/// set param on apm, used for param rename
/// </summary>
/// <param name="paramname"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool setParam(string[] paramnames, float value)
{
foreach (string paramname in paramnames)
{
if (setParam(paramname, value))
{
return true;
}
}
return false;
}
/// <summary>
/// Set parameter on apm
/// </summary>
/// <param name="paramname">name as a string</param>
/// <param name="value"></param>
public bool setParam(string paramname, float value)
{
if (!MAV.param.ContainsKey(paramname))
{
log.Warn("Trying to set Param that doesnt exist " + paramname + "=" + value);
return false;
}
if ((float)MAV.param[paramname] == value)
{
log.Warn("setParam " + paramname + " not modified as same");
return true;
}
giveComport = true;
// param type is set here, however it is always sent over the air as a float 100int = 100f.
var req = new mavlink_param_set_t { target_system = MAV.sysid, target_component = MAV.compid, param_type = (byte)param_types[paramname] };
byte[] temp = Encoding.ASCII.GetBytes(paramname);
Array.Resize(ref temp, 16);
req.param_id = temp;
req.param_value = (value);
generatePacket((byte)MAVLINK_MSG_ID.PARAM_SET, req);
log.InfoFormat("setParam '{0}' = '{1}' sysid {2} compid {3}", paramname, req.param_value, MAV.sysid, MAV.compid);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("setParam Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.PARAM_SET, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - setParam " + paramname);
}
byte[] buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.PARAM_VALUE)
{
mavlink_param_value_t par = buffer.ByteArrayToStructure<mavlink_param_value_t>(6);
string st = System.Text.ASCIIEncoding.ASCII.GetString(par.param_id);
int pos = st.IndexOf('\0');
if (pos != -1)
{
st = st.Substring(0, pos);
}
if (st != paramname)
{
log.InfoFormat("MAVLINK bad param responce - {0} vs {1}", paramname, st);
continue;
}
MAV.param[st] = (par.param_value);
giveComport = false;
//System.Threading.Thread.Sleep(100);//(int)(8.5 * 5)); // 8.5ms per byte
return true;
}
}
}
}
/*
public Bitmap getImage()
{
MemoryStream ms = new MemoryStream();
}
*/
public void getParamList()
{
frmProgressReporter = new ProgressReporterDialogue
{
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
Text = "Getting Params"
};
frmProgressReporter.DoWork += FrmProgressReporterGetParams;
frmProgressReporter.UpdateProgressAndStatus(-1, "Getting Params...");
ThemeManager.ApplyThemeTo(frmProgressReporter);
frmProgressReporter.RunBackgroundOperationAsync();
if (ParamListChanged != null)
{
ParamListChanged(this, null);
}
// nan check
foreach (string item in MAV.param.Keys)
{
if (float.IsNaN((float)MAV.param[item]))
CustomMessageBox.Show("BAD PARAM, "+item+" = NAN \n Fix this NOW!!","Error");
}
}
void FrmProgressReporterGetParams(object sender, ProgressWorkerEventArgs e, object passdata = null)
{
Hashtable old = new Hashtable(MAV.param);
getParamListBG();
if (frmProgressReporter.doWorkArgs.CancelRequested)
{
MAV.param = old;
}
}
/// <summary>
/// Get param list from apm
/// </summary>
/// <returns></returns>
private Hashtable getParamListBG()
{
giveComport = true;
List<int> indexsreceived = new List<int>();
// clear old
MAV.param = new Hashtable();
int retrys = 6;
int param_count = 0;
int param_total = 1;
mavlink_param_request_list_t req = new mavlink_param_request_list_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
generatePacket((byte)MAVLINK_MSG_ID.PARAM_REQUEST_LIST, req);
DateTime start = DateTime.Now;
DateTime restart = DateTime.Now;
DateTime lastmessage = DateTime.MinValue;
//hires.Stopwatch stopwatch = new hires.Stopwatch();
int packets = 0;
do
{
if (frmProgressReporter.doWorkArgs.CancelRequested)
{
frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
giveComport = false;
frmProgressReporter.doWorkArgs.ErrorMessage = "User Canceled";
return MAV.param;
}
// 4 seconds between valid packets
if (!(start.AddMilliseconds(4000) > DateTime.Now) && !logreadmode)
{
log.Info("Get param 1 by 1 - got " + indexsreceived.Count + " of " + param_total);
// try getting individual params
for (short i = 0; i <= (param_total - 1); i++)
{
if (!indexsreceived.Contains(i))
{
if (frmProgressReporter.doWorkArgs.CancelRequested)
{
frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
giveComport = false;
frmProgressReporter.doWorkArgs.ErrorMessage = "User Canceled";
return MAV.param;
}
// prevent dropping out of this get params loop
try
{
GetParam(i);
param_count++;
indexsreceived.Add(i);
this.frmProgressReporter.UpdateProgressAndStatus((indexsreceived.Count * 100) / param_total, "Got param index " + i);
}
catch (Exception excp)
{
log.Info("GetParam Failed index: " + i + " " + excp);
try
{
// GetParam(i);
// param_count++;
// indexsreceived.Add(i);
}
catch { }
// fail over to full list
//break;
}
}
}
if (retrys == 4)
{
requestDatastream(MAVLink.MAV_DATA_STREAM.ALL, 1);
}
if (retrys > 0)
{
log.InfoFormat("getParamList Retry {0} sys {1} comp {2}", retrys, MAV.sysid, MAV.compid);
generatePacket((byte)MAVLINK_MSG_ID.PARAM_REQUEST_LIST, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
if (packets > 0 && param_total == 1)
{
throw new Exception("Timeout on read - getParamList\n" + packets + " Packets where received, but no paramater packets where received\n");
}
if (packets == 0)
{
throw new Exception("Timeout on read - getParamList\nNo Packets where received\n");
}
throw new Exception("Timeout on read - getParamList\nReceived: " + indexsreceived.Count + " of " + param_total + " after 6 retrys\n\nPlease Check\n1. Link Speed\n2. Link Quality\n3. Hardware hasn't hung");
}
//Console.WriteLine(DateTime.Now.Millisecond + " gp0 ");
byte[] buffer = readPacket();
//Console.WriteLine(DateTime.Now.Millisecond + " gp1 ");
if (buffer.Length > 5)
{
packets++;
// stopwatch.Start();
if (buffer[5] == (byte)MAVLINK_MSG_ID.PARAM_VALUE)
{
restart = DateTime.Now;
start = DateTime.Now;
mavlink_param_value_t par = buffer.ByteArrayToStructure<mavlink_param_value_t>(6);
// set new target
param_total = (par.param_count);
string paramID = System.Text.ASCIIEncoding.ASCII.GetString(par.param_id);
int pos = paramID.IndexOf('\0');
if (pos != -1)
{
paramID = paramID.Substring(0, pos);
}
// check if we already have it
if (indexsreceived.Contains(par.param_index))
{
log.Info("Already got " + (par.param_index) + " '" + paramID + "'");
this.frmProgressReporter.UpdateProgressAndStatus((indexsreceived.Count * 100) / param_total, "Already Got param " + paramID);
continue;
}
//Console.WriteLine(DateTime.Now.Millisecond + " gp2 ");
if (!MainV2.MONO)
log.Info(DateTime.Now.Millisecond + " got param " + (par.param_index) + " of " + (par.param_count) + " name: " + paramID);
//Console.WriteLine(DateTime.Now.Millisecond + " gp2a ");
MAV.param[paramID] = (par.param_value);
//Console.WriteLine(DateTime.Now.Millisecond + " gp2b ");
param_count++;
indexsreceived.Add(par.param_index);
param_types[paramID] = (MAV_PARAM_TYPE)par.param_type;
//Console.WriteLine(DateTime.Now.Millisecond + " gp3 ");
this.frmProgressReporter.UpdateProgressAndStatus((indexsreceived.Count * 100) / param_total, "Got param " + paramID);
// we hit the last param - lets escape eq total = 176 index = 0-175
if (par.param_index == (param_total - 1))
start = DateTime.MinValue;
}
if (buffer[5] == (byte)MAVLINK_MSG_ID.STATUSTEXT)
{
var msg = MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT].ByteArrayToStructure<MAVLink.mavlink_statustext_t>(6);
string logdata = Encoding.ASCII.GetString(msg.text);
int ind = logdata.IndexOf('\0');
if (ind != -1)
logdata = logdata.Substring(0, ind);
if (logdata.ToLower().Contains("copter")||logdata.ToLower().Contains("rover")||logdata.ToLower().Contains("plane"))
{
MAV.VersionString = logdata;
}
else if (logdata.ToLower().Contains("nuttx"))
{
MAV.SoftwareVersions = logdata;
}
else if (logdata.ToLower().Contains("px4v2"))
{
MAV.SerialString = logdata;
}
}
//stopwatch.Stop();
// Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
// Console.WriteLine(DateTime.Now.Millisecond + " gp4 " + BaseStream.BytesToRead);
}
if (logreadmode && logplaybackfile.BaseStream.Position >= logplaybackfile.BaseStream.Length)
{
break;
}
} while (indexsreceived.Count < param_total);
if (indexsreceived.Count != param_total)
{
throw new Exception("Missing Params");
}
giveComport = false;
return MAV.param;
}
public float GetParam(string name)
{
return GetParam(name, -1);
}
public float GetParam(short index)
{
return GetParam("", index);
}
/// <summary>
/// Get param by either index or name
/// </summary>
/// <param name="index"></param>
/// <param name="name"></param>
/// <returns></returns>
internal float GetParam(string name = "", short index = -1)
{
if (name == "" && index == -1)
return 0;
log.Info("GetParam name: '" + name + "' or index: " + index);
giveComport = true;
byte[] buffer;
mavlink_param_request_read_t req = new mavlink_param_request_read_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.param_index = index;
req.param_id = new byte[] {0x0};
if (index == -1)
{
req.param_id = System.Text.ASCIIEncoding.ASCII.GetBytes(name);
}
Array.Resize(ref req.param_id, 16);
generatePacket((byte)MAVLINK_MSG_ID.PARAM_REQUEST_READ, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("GetParam Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.PARAM_REQUEST_READ, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - GetParam");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.PARAM_VALUE)
{
giveComport = false;
mavlink_param_value_t par = buffer.ByteArrayToStructure<mavlink_param_value_t>(6);
string st = System.Text.ASCIIEncoding.ASCII.GetString(par.param_id);
int pos = st.IndexOf('\0');
if (pos != -1)
{
st = st.Substring(0, pos);
}
// not the correct id
if (!(par.param_index == index || st == name))
{
log.ErrorFormat("Wrong Answer {0} - {1} - {2} --- '{3}' vs '{4}'", par.param_index, ASCIIEncoding.ASCII.GetString(par.param_id), par.param_value, ASCIIEncoding.ASCII.GetString(req.param_id).TrimEnd(), st);
continue;
}
// update table
MAV.param[st] = par.param_value;
param_types[st] = (MAV_PARAM_TYPE)par.param_type;
log.Info(DateTime.Now.Millisecond + " got param " + (par.param_index) + " of " + (par.param_count) + " name: " + st);
return par.param_value;
}
}
}
}
public static void modifyParamForDisplay(bool fromapm, string paramname, ref float value)
{
int planforremoval;
if (paramname.ToUpper().EndsWith("_IMAX") || paramname.ToUpper().EndsWith("ALT_HOLD_RTL") || paramname.ToUpper().EndsWith("APPROACH_ALT") || paramname.ToUpper().EndsWith("TRIM_ARSPD_CM") || paramname.ToUpper().EndsWith("MIN_GNDSPD_CM")
|| paramname.ToUpper().EndsWith("XTRK_ANGLE_CD") || paramname.ToUpper().EndsWith("LIM_PITCH_MAX") || paramname.ToUpper().EndsWith("LIM_PITCH_MIN")
|| paramname.ToUpper().EndsWith("LIM_ROLL_CD") || paramname.ToUpper().EndsWith("PITCH_MAX") || paramname.ToUpper().EndsWith("WP_SPEED_MAX"))
{
if (paramname.ToUpper().EndsWith("THR_RATE_IMAX") || paramname.ToUpper().EndsWith("THR_HOLD_IMAX")
|| paramname.ToUpper().EndsWith("RATE_RLL_IMAX") || paramname.ToUpper().EndsWith("RATE_PIT_IMAX"))
return;
if (fromapm)
{
value /= 100.0f;
}
else
{
value *= 100.0f;
}
}
else if (paramname.ToUpper().StartsWith("TUNE_"))
{
if (fromapm)
{
value /= 1000.0f;
}
else
{
value *= 1000.0f;
}
}
}
/// <summary>
/// Stops all requested data packets.
/// </summary>
public void stopall(bool forget)
{
mavlink_request_data_stream_t req = new mavlink_request_data_stream_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.req_message_rate = 10;
req.start_stop = 0; // stop
req.req_stream_id = 0; // all
// no error on bad
try
{
generatePacket((byte)MAVLINK_MSG_ID.REQUEST_DATA_STREAM, req);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.REQUEST_DATA_STREAM, req);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.REQUEST_DATA_STREAM, req);
log.Info("Stopall Done");
}
catch { }
}
public void setWPACK()
{
MAVLink.mavlink_mission_ack_t req = new MAVLink.mavlink_mission_ack_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.type = 0;
generatePacket((byte)MAVLINK_MSG_ID.MISSION_ACK, req);
}
public bool setWPCurrent(ushort index)
{
giveComport = true;
byte[] buffer;
mavlink_mission_set_current_t req = new mavlink_mission_set_current_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.seq = index;
generatePacket((byte)MAVLINK_MSG_ID.MISSION_SET_CURRENT, req);
DateTime start = DateTime.Now;
int retrys = 5;
while (true)
{
if (!(start.AddMilliseconds(2000) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("setWPCurrent Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_SET_CURRENT, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - setWPCurrent");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_CURRENT)
{
giveComport = false;
return true;
}
}
}
}
[Obsolete("Mavlink 09 - use doCommand", true)]
public bool doAction(object actionid)
{
// mavlink 09
throw new NotImplementedException();
}
/// <summary>
/// send lots of packets to reset the hardware, this asumes we dont know the sysid in the first place
/// </summary>
/// <returns></returns>
public bool doReboot(bool bootloadermode = false)
{
byte[] buffer = getHeartBeat();
if (buffer.Length > 5)
{
mavlink_heartbeat_t hb = buffer.ByteArrayToStructure<mavlink_heartbeat_t>(6);
mavlinkversion = hb.mavlink_version;
MAV.aptype = (MAV_TYPE)hb.type;
MAV.apname = (MAV_AUTOPILOT)hb.autopilot;
MAV.sysid = buffer[3];
MAV.compid = buffer[4];
}
int param1 = 1;
if (bootloadermode)
{
param1 = 3;
}
if (MAV.sysid != 0 && MAV.compid != 0)
{
doCommand(MAV_CMD.PREFLIGHT_REBOOT_SHUTDOWN, param1, 0, 0, 0, 0, 0, 0);
doCommand(MAV_CMD.PREFLIGHT_REBOOT_SHUTDOWN, 1, 0, 0, 0, 0, 0, 0);
}
else
{
for (byte a = byte.MinValue; a < byte.MaxValue; a++)
{
giveComport = true;
MAV.sysid = a;
doCommand(MAV_CMD.PREFLIGHT_REBOOT_SHUTDOWN, param1, 0, 0, 0, 0, 0, 0);
}
}
giveComport = false;
return true;
}
public bool doARM(bool armit)
{
return doCommand(MAV_CMD.COMPONENT_ARM_DISARM, armit ? 1 : 0, 0, 0, 0, 0, 0, 0);
}
public bool doCommand(MAV_CMD actionid, float p1, float p2, float p3, float p4, float p5, float p6, float p7)
{
giveComport = true;
byte[] buffer;
mavlink_command_long_t req = new mavlink_command_long_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
if (actionid == MAV_CMD.COMPONENT_ARM_DISARM)
{
req.target_component = (byte)MAV_COMPONENT.MAV_COMP_ID_SYSTEM_CONTROL;
}
req.command = (ushort)actionid;
req.param1 = p1;
req.param2 = p2;
req.param3 = p3;
req.param4 = p4;
req.param5 = p5;
req.param6 = p6;
req.param7 = p7;
log.InfoFormat("doCommand cmd {0} {1} {2} {3} {4} {5} {6} {7}",actionid.ToString(),p1,p2,p3,p4,p5,p6,p7);
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_LONG, req);
DateTime start = DateTime.Now;
int retrys = 3;
int timeout = 2000;
// imu calib take a little while
if (actionid == MAV_CMD.PREFLIGHT_CALIBRATION && p5 == 1)
{
// this is for advanced accel offsets, and blocks execution
return true;
}
else if (actionid == MAV_CMD.PREFLIGHT_CALIBRATION)
{
retrys = 1;
timeout = 25000;
}
else if (actionid == MAV_CMD.PREFLIGHT_REBOOT_SHUTDOWN)
{
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_LONG, req);
giveComport = false;
return true;
}
else if (actionid == MAV_CMD.COMPONENT_ARM_DISARM)
{
// 10 seconds as may need an imu calib
timeout = 10000;
}
else if (actionid == MAV_CMD.PREFLIGHT_CALIBRATION && p6 == 1)
{ // compassmot
// send again just incase
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_LONG, req);
giveComport = false;
return true;
}
while (true)
{
if (!(start.AddMilliseconds(timeout) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("doAction Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_LONG, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - doAction");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.COMMAND_ACK)
{
var ack = buffer.ByteArrayToStructure<mavlink_command_ack_t>(6);
if (ack.result == (byte)MAV_RESULT.ACCEPTED)
{
giveComport = false;
return true;
}
else
{
giveComport = false;
return false;
}
}
}
}
}
public void SendAck()
{
mavlink_command_ack_t ack = new mavlink_command_ack_t();
ack.command = (byte)MAV_CMD.PREFLIGHT_CALIBRATION;
ack.result = 0;
// send twice
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_ACK,ack);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.COMMAND_ACK, ack);
}
public void SendSerialControl(SERIAL_CONTROL_DEV port, ushort timeoutms, byte[] data, uint baudrate = 0,bool close = false)
{
mavlink_serial_control_t ctl = new mavlink_serial_control_t();
ctl.baudrate = baudrate; // no change
ctl.device = (byte)port;
ctl.timeout = timeoutms;
ctl.data = new byte[70];
ctl.count = 0;
if (close)
{
ctl.flags = 0;
}
else
{
ctl.flags = (byte)(SERIAL_CONTROL_FLAG.EXCLUSIVE | SERIAL_CONTROL_FLAG.RESPOND);
}
if (data != null && data.Length != 0)
{
int len = data.Length;
while (len > 0)
{
byte n = (byte)Math.Min(70, len);
ctl.count = n;
Array.Copy(data, data.Length - len, ctl.data, 0, n);
// dont flod the port
System.Threading.Thread.Sleep(10);
generatePacket((byte)MAVLINK_MSG_ID.SERIAL_CONTROL, ctl);
len -= n;
}
}
else
{
generatePacket((byte)MAVLINK_MSG_ID.SERIAL_CONTROL, ctl);
}
}
public void requestDatastream(MAVLink.MAV_DATA_STREAM id, byte hzrate)
{
double pps = 0;
switch (id)
{
case MAVLink.MAV_DATA_STREAM.ALL:
break;
case MAVLink.MAV_DATA_STREAM.EXTENDED_STATUS:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.SYS_STATUS] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.SYS_STATUS];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.EXTRA1:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.ATTITUDE] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.ATTITUDE];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.EXTRA2:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.VFR_HUD] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.VFR_HUD];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.EXTRA3:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.AHRS] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.AHRS];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.POSITION:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.GLOBAL_POSITION_INT] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.GLOBAL_POSITION_INT];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.RAW_CONTROLLER:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.RC_CHANNELS_SCALED] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.RC_CHANNELS_SCALED];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.RAW_SENSORS:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.RAW_IMU] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.RAW_IMU];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
case MAVLink.MAV_DATA_STREAM.RC_CHANNELS:
if (packetspersecondbuild[(byte)MAVLINK_MSG_ID.RC_CHANNELS_RAW] < DateTime.Now.AddSeconds(-2))
break;
pps = packetspersecond[(byte)MAVLINK_MSG_ID.RC_CHANNELS_RAW];
if (hzratecheck(pps, hzrate))
{
return;
}
break;
}
//packetspersecond[temp[5]];
if (pps == 0 && hzrate == 0)
{
return;
}
log.InfoFormat("Request stream {0} at {1} hz", Enum.Parse(typeof(MAV_DATA_STREAM), id.ToString()), hzrate);
getDatastream(id, hzrate);
}
// returns true for ok
bool hzratecheck(double pps, int hzrate)
{
if (hzrate == 0 && pps == 0)
{
return true;
}
else if (hzrate == 1 && pps >= 0.5 && pps <= 2)
{
return true;
}
else if (hzrate == 3 && pps >= 2 && hzrate < 5)
{
return true;
}
else if (hzrate == 10 && pps > 5 && hzrate < 15)
{
return true;
}
else if (hzrate > 15 && pps > 15)
{
return true;
}
return false;
}
void getDatastream(MAVLink.MAV_DATA_STREAM id, byte hzrate)
{
mavlink_request_data_stream_t req = new mavlink_request_data_stream_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.req_message_rate = hzrate;
req.start_stop = 1; // start
req.req_stream_id = (byte)id; // id
// send each one twice.
generatePacket((byte)MAVLINK_MSG_ID.REQUEST_DATA_STREAM, req);
generatePacket((byte)MAVLINK_MSG_ID.REQUEST_DATA_STREAM, req);
}
/// <summary>
/// Returns WP count
/// </summary>
/// <returns></returns>
public byte getWPCount()
{
giveComport = true;
byte[] buffer;
mavlink_mission_request_list_t req = new mavlink_mission_request_list_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
// request list
generatePacket((byte)MAVLINK_MSG_ID.MISSION_REQUEST_LIST, req);
DateTime start = DateTime.Now;
int retrys = 6;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("getWPCount Retry " + retrys + " - giv com " + giveComport);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_REQUEST_LIST, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
//return (byte)int.Parse(param["WP_TOTAL"].ToString());
throw new Exception("Timeout on read - getWPCount");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_COUNT)
{
var count = buffer.ByteArrayToStructure<mavlink_mission_count_t>(6);
log.Info("wpcount: " + count.count);
giveComport = false;
return (byte)count.count; // should be ushort, but apm has limited wp count < byte
}
else
{
log.Info(DateTime.Now + " PC wpcount " + buffer[5] + " need " + MAVLINK_MSG_ID.MISSION_COUNT);
}
}
}
}
/// <summary>
/// Gets specfied WP
/// </summary>
/// <param name="index"></param>
/// <returns>WP</returns>
public Locationwp getWP(ushort index)
{
giveComport = true;
Locationwp loc = new Locationwp();
mavlink_mission_request_t req = new mavlink_mission_request_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.seq = index;
//Console.WriteLine("getwp req "+ DateTime.Now.Millisecond);
// request
generatePacket((byte)MAVLINK_MSG_ID.MISSION_REQUEST, req);
DateTime start = DateTime.Now;
int retrys = 5;
while (true)
{
if (!(start.AddMilliseconds(800) > DateTime.Now)) // apm times out after 1000ms
{
if (retrys > 0)
{
log.Info("getWP Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_REQUEST, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - getWP");
}
//Console.WriteLine("getwp read " + DateTime.Now.Millisecond);
byte[] buffer = readPacket();
//Console.WriteLine("getwp readend " + DateTime.Now.Millisecond);
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_ITEM)
{
//Console.WriteLine("getwp ans " + DateTime.Now.Millisecond);
//Array.Copy(buffer, 6, buffer, 0, buffer.Length - 6);
var wp = buffer.ByteArrayToStructure<mavlink_mission_item_t>(6);
loc.options = (byte)(wp.frame & 0x1);
loc.id = (byte)(wp.command);
loc.p1 = (wp.param1);
loc.p2 = (wp.param2);
loc.p3 = (wp.param3);
loc.p4 = (wp.param4);
loc.alt = ((wp.z));
loc.lat = ((wp.x));
loc.lng = ((wp.y));
log.InfoFormat("getWP {0} {1} {2} {3} {4} opt {5}", loc.id, loc.p1, loc.alt, loc.lat, loc.lng, loc.options);
break;
}
else
{
log.Info(DateTime.Now + " PC getwp " + buffer[5]);
}
}
}
giveComport = false;
return loc;
}
public object DebugPacket(byte[] datin)
{
string text = "";
return DebugPacket(datin, ref text, true);
}
public object DebugPacket(byte[] datin, bool PrintToConsole)
{
string text = "";
return DebugPacket(datin, ref text, PrintToConsole);
}
public object DebugPacket(byte[] datin, ref string text)
{
return DebugPacket(datin, ref text, true);
}
/// <summary>
/// Print entire decoded packet to console
/// </summary>
/// <param name="datin">packet byte array</param>
/// <returns>struct of data</returns>
public object DebugPacket(byte[] datin, ref string text, bool PrintToConsole, string delimeter = " ")
{
string textoutput;
try
{
if (datin.Length > 5)
{
byte header = datin[0];
byte length = datin[1];
byte seq = datin[2];
byte sysid = datin[3];
byte compid = datin[4];
byte messid = datin[5];
textoutput = string.Format("{0,2:X}{6}{1,2:X}{6}{2,2:X}{6}{3,2:X}{6}{4,2:X}{6}{5,2:X}{6}", header, length, seq, sysid, compid, messid, delimeter);
object data = Activator.CreateInstance(MAVLINK_MESSAGE_INFO[messid]);
MavlinkUtil.ByteArrayToStructure(datin, ref data, 6);
Type test = data.GetType();
if (PrintToConsole)
{
textoutput = textoutput + test.Name + delimeter;
foreach (var field in test.GetFields())
{
// field.Name has the field's name.
object fieldValue = field.GetValue(data); // Get value
if (field.FieldType.IsArray)
{
textoutput = textoutput + field.Name + delimeter;
byte[] crap = (byte[])fieldValue;
foreach (byte fiel in crap)
{
if (fiel == 0)
{
break;
}
else
{
textoutput = textoutput + (char)fiel;
}
}
textoutput = textoutput + delimeter;
}
else
{
textoutput = textoutput + field.Name + delimeter + fieldValue.ToString() + delimeter;
}
}
textoutput = textoutput + delimeter + "Len" + delimeter + datin.Length + "\r\n";
if (PrintToConsole)
Console.Write(textoutput);
if (text != null)
text = textoutput;
}
return data;
}
}
catch { }
return null;
}
public object GetPacket(byte[] datin)
{
if (datin.Length > 5)
{
byte header = datin[0];
byte length = datin[1];
byte seq = datin[2];
byte sysid = datin[3];
byte compid = datin[4];
byte messid = datin[5];
try
{
object data = Activator.CreateInstance(MAVLINK_MESSAGE_INFO[messid]);
MavlinkUtil.ByteArrayToStructure(datin, ref data, 6);
return data;
}
catch { }
}
return null;
}
/// <summary>
/// Set start and finish for partial wp upload.
/// </summary>
/// <param name="startwp"></param>
/// <param name="endwp"></param>
public void setWPPartialUpdate(short startwp, short endwp)
{
mavlink_mission_write_partial_list_t req = new mavlink_mission_write_partial_list_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.start_index = startwp;
req.end_index = endwp;
generatePacket((byte)MAVLINK_MSG_ID.MISSION_WRITE_PARTIAL_LIST, req);
}
/// <summary>
/// Sets wp total count
/// </summary>
/// <param name="wp_total"></param>
public void setWPTotal(ushort wp_total)
{
giveComport = true;
mavlink_mission_count_t req = new mavlink_mission_count_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid; // MSG_NAMES.MISSION_COUNT
req.count = wp_total;
generatePacket((byte)MAVLINK_MSG_ID.MISSION_COUNT, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("setWPTotal Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_COUNT, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - setWPTotal");
}
byte[] buffer = readPacket();
if (buffer.Length > 9)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_REQUEST)
{
var request = buffer.ByteArrayToStructure<mavlink_mission_request_t>(6);
if (request.seq == 0)
{
if (MAV.param["WP_TOTAL"] != null)
MAV.param["WP_TOTAL"] = (float)wp_total - 1;
if (MAV.param["CMD_TOTAL"] != null)
MAV.param["CMD_TOTAL"] = (float)wp_total - 1;
MAV.wps.Clear();
giveComport = false;
return;
}
}
else
{
//Console.WriteLine(DateTime.Now + " PC getwp " + buffer[5]);
}
}
}
}
/// <summary>
/// Save wp to eeprom
/// </summary>
/// <param name="loc">location struct</param>
/// <param name="index">wp no</param>
/// <param name="frame">global or relative</param>
/// <param name="current">0 = no , 2 = guided mode</param>
public MAV_MISSION_RESULT setWP(Locationwp loc, ushort index, MAV_FRAME frame, byte current = 0, byte autocontinue = 1)
{
giveComport = true;
mavlink_mission_item_t req = new mavlink_mission_item_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid; // MSG_NAMES.MISSION_ITEM
req.command = loc.id;
req.current = current;
req.autocontinue = autocontinue;
req.frame = (byte)frame;
req.y = (float)(loc.lng);
req.x = (float)(loc.lat);
req.z = (float)(loc.alt);
req.param1 = loc.p1;
req.param2 = loc.p2;
req.param3 = loc.p3;
req.param4 = loc.p4;
req.seq = index;
log.InfoFormat("setWP {6} frame {0} cmd {1} p1 {2} x {3} y {4} z {5}", req.frame, req.command, req.param1, req.x, req.y, req.z, index);
// request
generatePacket((byte)MAVLINK_MSG_ID.MISSION_ITEM, req);
DateTime start = DateTime.Now;
int retrys = 10;
while (true)
{
if (!(start.AddMilliseconds(400) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("setWP Retry " + retrys);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_ITEM, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - setWP");
}
byte[] buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_ACK)
{
var ans = buffer.ByteArrayToStructure<mavlink_mission_ack_t>(6);
log.Info("set wp " + index + " ACK 47 : " + buffer[5] + " ans " + Enum.Parse(typeof(MAV_MISSION_RESULT), ans.type.ToString()));
if (req.current == 2)
{
MAV.GuidedMode = req;
}
else if (req.current == 3)
{
}
else
{
MAV.wps[req.seq] = req;
}
return (MAV_MISSION_RESULT)ans.type;
}
else if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_REQUEST)
{
var ans = buffer.ByteArrayToStructure<mavlink_mission_request_t>(6);
if (ans.seq == (index + 1))
{
log.Info("set wp doing " + index + " req " + ans.seq + " REQ 40 : " + buffer[5]);
giveComport = false;
if (req.current == 2)
{
MAV.GuidedMode = req;
}
else if (req.current == 3)
{
}
else
{
MAV.wps[req.seq] = req;
}
return MAV_MISSION_RESULT.MAV_MISSION_ACCEPTED;
}
else
{
log.InfoFormat("set wp fail doing " + index + " req " + ans.seq + " ACK 47 or REQ 40 : " + buffer[5] + " seq {0} ts {1} tc {2}", req.seq, req.target_system, req.target_component);
// resend point now
start = DateTime.MinValue;
}
}
else
{
//Console.WriteLine(DateTime.Now + " PC setwp " + buffer[5]);
}
}
}
// return MAV_MISSION_RESULT.MAV_MISSION_INVALID;
}
public void setNextWPTargetAlt(ushort wpno, float alt)
{
// get the existing wp
Locationwp current = getWP(wpno);
mavlink_mission_write_partial_list_t req = new mavlink_mission_write_partial_list_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.start_index = (short)wpno;
req.end_index = (short)wpno;
// change the alt
current.alt = alt;
// send a request to update single point
generatePacket((byte)MAVLINK_MSG_ID.MISSION_WRITE_PARTIAL_LIST, req);
Thread.Sleep(10);
generatePacket((byte)MAVLINK_MSG_ID.MISSION_WRITE_PARTIAL_LIST, req);
MAV_FRAME frame = (current.options & 0x1) == 0 ? MAV_FRAME.GLOBAL : MAV_FRAME.GLOBAL_RELATIVE_ALT;
//send the point with new alt
setWP(current, wpno, MAV_FRAME.GLOBAL_RELATIVE_ALT, 0);
// set the point as current to reload the modified command
setWPCurrent(wpno);
}
public void setGuidedModeWP(Locationwp gotohere)
{
if (gotohere.alt == 0 || gotohere.lat == 0 || gotohere.lng == 0)
return;
giveComport = true;
try
{
gotohere.id = (byte)MAV_CMD.WAYPOINT;
MAV_MISSION_RESULT ans = setWP(gotohere, 0, MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT, (byte)2);
if (ans != MAV_MISSION_RESULT.MAV_MISSION_ACCEPTED)
throw new Exception("Guided Mode Failed");
}
catch (Exception ex) { log.Error(ex); }
giveComport = false;
}
public void setNewWPAlt(Locationwp gotohere)
{
giveComport = true;
try
{
gotohere.id = (byte)MAV_CMD.WAYPOINT;
MAV_MISSION_RESULT ans = setWP(gotohere, 0, MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT, (byte)3);
if (ans != MAV_MISSION_RESULT.MAV_MISSION_ACCEPTED)
throw new Exception("Alt Change Failed");
}
catch (Exception ex) { giveComport = false; log.Error(ex); throw; }
giveComport = false;
}
public void setDigicamConfigure()
{
// not implmented
}
public void setDigicamControl(bool shot)
{
mavlink_digicam_control_t req = new mavlink_digicam_control_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.shot = (shot == true) ? (byte)1 : (byte)0;
generatePacket((byte)MAVLINK_MSG_ID.DIGICAM_CONTROL, req);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.DIGICAM_CONTROL, req);
}
public void setMountConfigure(MAV_MOUNT_MODE mountmode, bool stabroll, bool stabpitch, bool stabyaw)
{
mavlink_mount_configure_t req = new mavlink_mount_configure_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
req.mount_mode = (byte)mountmode;
req.stab_pitch = (stabpitch == true) ? (byte)1 : (byte)0;
req.stab_roll = (stabroll == true) ? (byte)1 : (byte)0;
req.stab_yaw = (stabyaw == true) ? (byte)1 : (byte)0;
generatePacket((byte)MAVLINK_MSG_ID.MOUNT_CONFIGURE, req);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.MOUNT_CONFIGURE, req);
}
public void setMountControl(double pa, double pb, double pc, bool islatlng)
{
mavlink_mount_control_t req = new mavlink_mount_control_t();
req.target_system = MAV.sysid;
req.target_component = MAV.compid;
if (!islatlng)
{
req.input_a = (int)pa;
req.input_b = (int)pb;
req.input_c = (int)pc;
}
else
{
req.input_a = (int)(pa * 10000000.0);
req.input_b = (int)(pb * 10000000.0);
req.input_c = (int)(pc * 100.0);
}
generatePacket((byte)MAVLINK_MSG_ID.MOUNT_CONTROL, req);
System.Threading.Thread.Sleep(20);
generatePacket((byte)MAVLINK_MSG_ID.MOUNT_CONTROL, req);
}
public void setMode(string modein)
{
try
{
MAVLink.mavlink_set_mode_t mode = new MAVLink.mavlink_set_mode_t();
if (translateMode(modein, ref mode))
{
setMode(mode);
}
}
catch { System.Windows.Forms.MessageBox.Show("Failed to change Modes"); }
}
public void setMode(mavlink_set_mode_t mode, MAV_MODE_FLAG base_mode = 0)
{
mode.base_mode |= (byte)base_mode;
generatePacket((byte)(byte)MAVLink.MAVLINK_MSG_ID.SET_MODE, mode);
System.Threading.Thread.Sleep(10);
generatePacket((byte)(byte)MAVLink.MAVLINK_MSG_ID.SET_MODE, mode);
}
/// <summary>
/// used for last bad serial characters
/// </summary>
byte[] lastbad = new byte[2];
private double t7 = 1.0e7;
/// <summary>
/// Serial Reader to read mavlink packets. POLL method
/// </summary>
/// <returns></returns>
public byte[] readPacket()
{
byte[] buffer = new byte[260];
int count = 0;
int length = 0;
int readcount = 0;
lastbad = new byte[2];
BaseStream.ReadTimeout = 1200; // 1200 ms between chars - the gps detection requires this.
DateTime start = DateTime.Now;
//Console.WriteLine(DateTime.Now.Millisecond + " SR0 " + BaseStream.BytesToRead);
lock (readlock)
{
//Console.WriteLine(DateTime.Now.Millisecond + " SR1 " + BaseStream.BytesToRead);
while (BaseStream.IsOpen || logreadmode)
{
try
{
if (readcount > 300)
{
log.Info("MAVLink readpacket No valid mavlink packets");
break;
}
readcount++;
if (logreadmode)
{
try
{
if (logplaybackfile.BaseStream.Position == 0)
{
if (logplaybackfile.PeekChar() == '-')
{
oldlogformat = true;
}
else
{
oldlogformat = false;
}
}
}
catch { oldlogformat = false; }
if (oldlogformat)
{
buffer = readlogPacket(); //old style log
}
else
{
buffer = readlogPacketMavlink();
}
}
else
{
MAV.cs.datetime = DateTime.Now;
DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);
// Console.WriteLine(DateTime.Now.Millisecond + " SR1a " + BaseStream.BytesToRead);
while (BaseStream.IsOpen && BaseStream.BytesToRead <= 0)
{
if (DateTime.Now > to)
{
log.InfoFormat("MAVLINK: 1 wait time out btr {0} len {1}", BaseStream.BytesToRead, length);
throw new Exception("Timeout");
}
System.Threading.Thread.Sleep(1);
//Console.WriteLine(DateTime.Now.Millisecond + " SR0b " + BaseStream.BytesToRead);
}
//Console.WriteLine(DateTime.Now.Millisecond + " SR1a " + BaseStream.BytesToRead);
if (BaseStream.IsOpen)
{
BaseStream.Read(buffer, count, 1);
if (rawlogfile != null && rawlogfile.CanWrite)
rawlogfile.WriteByte(buffer[count]);
}
//Console.WriteLine(DateTime.Now.Millisecond + " SR1b " + BaseStream.BytesToRead);
}
}
catch (Exception e) { log.Info("MAVLink readpacket read error: " + e.ToString()); break; }
// check if looks like a mavlink packet and check for exclusions and write to console
if (buffer[0] != 254)
{
if (buffer[0] >= 0x20 && buffer[0] <= 127 || buffer[0] == '\n' || buffer[0] == '\r')
{
// check for line termination
if (buffer[0] == '\r' || buffer[0] == '\n')
{
// check new line is valid
if (buildplaintxtline.Length > 3)
plaintxtline = buildplaintxtline;
// reset for next line
buildplaintxtline = "";
}
TCPConsole.Write(buffer[0]);
Console.Write((char)buffer[0]);
buildplaintxtline += (char)buffer[0];
}
_bytesReceivedSubj.OnNext(1);
count = 0;
lastbad[0] = lastbad[1];
lastbad[1] = buffer[0];
buffer[1] = 0;
continue;
}
// reset count on valid packet
readcount = 0;
//Console.WriteLine(DateTime.Now.Millisecond + " SR2 " + BaseStream.BytesToRead);
// check for a header
if (buffer[0] == 254)
{
// if we have the header, and no other chars, get the length and packet identifiers
if (count == 0 && !logreadmode)
{
DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);
while (BaseStream.IsOpen && BaseStream.BytesToRead < 5)
{
if (DateTime.Now > to)
{
log.InfoFormat("MAVLINK: 2 wait time out btr {0} len {1}", BaseStream.BytesToRead, length);
throw new Exception("Timeout");
}
System.Threading.Thread.Sleep(1);
//Console.WriteLine(DateTime.Now.Millisecond + " SR0b " + BaseStream.BytesToRead);
}
int read = BaseStream.Read(buffer, 1, 5);
count = read;
if (rawlogfile != null && rawlogfile.CanWrite)
rawlogfile.Write(buffer, 1, read);
}
// packet length
length = buffer[1] + 6 + 2 - 2; // data + header + checksum - U - length
if (count >= 5 || logreadmode)
{
if (MAV.sysid != 0)
{
if (MAV.sysid != buffer[3] || MAV.compid != buffer[4])
{
if (buffer[3] == '3' && buffer[4] == 'D')
{
// this is a 3dr radio rssi packet
}
else
{
log.InfoFormat("Mavlink Bad Packet (not addressed to this MAV) got {0} {1} vs {2} {3}", buffer[3], buffer[4], MAV.sysid, MAV.compid);
return new byte[0];
}
}
}
try
{
if (logreadmode)
{
}
else
{
DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);
while (BaseStream.IsOpen && BaseStream.BytesToRead < (length - 4))
{
if (DateTime.Now > to)
{
log.InfoFormat("MAVLINK: 3 wait time out btr {0} len {1}", BaseStream.BytesToRead, length);
break;
}
System.Threading.Thread.Sleep(1);
}
if (BaseStream.IsOpen)
{
int read = BaseStream.Read(buffer, 6, length - 4);
if (rawlogfile != null && rawlogfile.CanWrite)
{
// write only what we read, temp is the whole packet, so 6-end
rawlogfile.Write(buffer, 6, read);
}
}
}
count = length + 2;
}
catch { break; }
break;
}
}
count++;
if (count == 299)
break;
}
//Console.WriteLine(DateTime.Now.Millisecond + " SR3 " + BaseStream.BytesToRead);
}// end readlock
Array.Resize<byte>(ref buffer, count);
_bytesReceivedSubj.OnNext(buffer.Length);
if (!logreadmode && packetlosttimer.AddSeconds(5) < DateTime.Now)
{
packetlosttimer = DateTime.Now;
packetslost = (packetslost * 0.8f);
packetsnotlost = (packetsnotlost * 0.8f);
}
else if (logreadmode && packetlosttimer.AddSeconds(5) < lastlogread)
{
packetlosttimer = lastlogread;
packetslost = (packetslost * 0.8f);
packetsnotlost = (packetsnotlost * 0.8f);
}
//MAV.cs.linkqualitygcs = (ushort)((packetsnotlost / (packetsnotlost + packetslost)) * 100.0);
if (bpstime.Second != DateTime.Now.Second && !logreadmode && BaseStream.IsOpen)
{
Console.Write("bps {0} loss {1} left {2} mem {3} \n", bps1, synclost, BaseStream.BytesToRead, System.GC.GetTotalMemory(false) / 1024 / 1024.0);
bps2 = bps1; // prev sec
bps1 = 0; // current sec
bpstime = DateTime.Now;
}
bps1 += buffer.Length;
bps = (bps1 + bps2) / 2;
if (buffer.Length >= 5 && (buffer[3] == 255 || buffer[3] == 253) && logreadmode) // gcs packet
{
getWPsfromstream(ref buffer);
return buffer;// new byte[0];
}
ushort crc = MavlinkCRC.crc_calculate(buffer, buffer.Length - 2);
if (buffer.Length > 5 && buffer[0] == 254)
{
crc = MavlinkCRC.crc_accumulate(MAVLINK_MESSAGE_CRCS[buffer[5]], crc);
}
if (buffer.Length > 5 && buffer[1] != MAVLINK_MESSAGE_LENGTHS[buffer[5]])
{
if (MAVLINK_MESSAGE_LENGTHS[buffer[5]] == 0) // pass for unknown packets
{
}
else
{
log.InfoFormat("Mavlink Bad Packet (Len Fail) len {0} pkno {1}", buffer.Length, buffer[5]);
if (buffer.Length == 11 && buffer[0] == 'U' && buffer[5] == 0)
{
string message = "Mavlink 0.9 Heartbeat, Please upgrade your AP, This planner is for Mavlink 1.0\n\n";
CustomMessageBox.Show(message);
throw new Exception(message);
}
return new byte[0];
}
}
if (buffer.Length < 5 || buffer[buffer.Length - 1] != (crc >> 8) || buffer[buffer.Length - 2] != (crc & 0xff))
{
int packetno = -1;
if (buffer.Length > 5)
{
packetno = buffer[5];
}
if (packetno != -1 && buffer.Length > 5 && MAVLINK_MESSAGE_INFO[packetno] != null)
log.InfoFormat("Mavlink Bad Packet (crc fail) len {0} crc {1} vs {4} pkno {2} {3}", buffer.Length, crc, packetno, MAVLINK_MESSAGE_INFO[packetno].ToString(), BitConverter.ToUInt16(buffer, buffer.Length - 2));
if (logreadmode)
log.InfoFormat("bad packet pos {0} ", logplaybackfile.BaseStream.Position);
return new byte[0];
}
try
{
if ((buffer[0] == 'U' || buffer[0] == 254) && buffer.Length >= buffer[1])
{
if (buffer[3] == '3' && buffer[4] == 'D')
{
}
else
{
byte packetSeqNo = buffer[2];
int expectedPacketSeqNo = ((MAV.recvpacketcount + 1) % 0x100);
{
if (packetSeqNo != expectedPacketSeqNo)
{
synclost++; // actualy sync loss's
int numLost = 0;
if (packetSeqNo < ((MAV.recvpacketcount + 1))) // recvpacketcount = 255 then 10 < 256 = true if was % 0x100 this would fail
{
numLost = 0x100 - expectedPacketSeqNo + packetSeqNo;
}
else
{
numLost = packetSeqNo - MAV.recvpacketcount;
}
packetslost += numLost;
WhenPacketLost.OnNext(numLost);
log.InfoFormat("lost pkts new seqno {0} pkts lost {1}", packetSeqNo, numLost);
}
packetsnotlost++;
MAV.recvpacketcount = packetSeqNo;
}
WhenPacketReceived.OnNext(1);
// Console.WriteLine(DateTime.Now.Millisecond);
}
// Console.Write(temp[5] + " " + DateTime.Now.Millisecond + " " + packetspersecond[temp[5]] + " " + (DateTime.Now - packetspersecondbuild[temp[5]]).TotalMilliseconds + " \n");
if (double.IsInfinity(packetspersecond[buffer[5]]))
packetspersecond[buffer[5]] = 0;
packetspersecond[buffer[5]] = (((1000 / ((DateTime.Now - packetspersecondbuild[buffer[5]]).TotalMilliseconds) + packetspersecond[buffer[5]]) / 2));
packetspersecondbuild[buffer[5]] = DateTime.Now;
//Console.WriteLine("Packet {0}",temp[5]);
// store packet history
lock (objlock)
{
MAV.packets[buffer[5]] = buffer;
MAV.packetseencount[buffer[5]]++;
}
PacketReceived(buffer);
if (debugmavlink)
DebugPacket(buffer);
if (buffer[5] == (byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT) // status text
{
var msg = MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT].ByteArrayToStructure<MAVLink.mavlink_statustext_t>(6);
byte sev = msg.severity;
string logdata = Encoding.ASCII.GetString(msg.text);
int ind = logdata.IndexOf('\0');
if (ind != -1)
logdata = logdata.Substring(0, ind);
log.Info(DateTime.Now + " " + logdata);
MAV.cs.messages.Add(logdata);
if (sev >= 3)
{
MAV.cs.messageHigh = logdata;
MAV.cs.messageHighTime = DateTime.Now;
if (MainV2.speechEngine != null && MainV2.speechEngine.State == System.Speech.Synthesis.SynthesizerState.Ready && MainV2.config["speechenable"] != null && MainV2.config["speechenable"].ToString() == "True")
{
MainV2.speechEngine.SpeakAsync(logdata);
}
}
}
// set ap type
if (buffer[5] == (byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT)
{
mavlink_heartbeat_t hb = buffer.ByteArrayToStructure<mavlink_heartbeat_t>(6);
if (hb.type != (byte)MAVLink.MAV_TYPE.GCS)
{
mavlinkversion = hb.mavlink_version;
MAV.aptype = (MAV_TYPE)hb.type;
MAV.apname = (MAV_AUTOPILOT)hb.autopilot;
setAPType();
}
}
getWPsfromstream(ref buffer);
try
{
if (logfile != null && logfile.CanWrite && !logreadmode)
{
lock (logfile)
{
byte[] datearray = BitConverter.GetBytes((UInt64)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds * 1000));
Array.Reverse(datearray);
logfile.Write(datearray, 0, datearray.Length);
logfile.Write(buffer, 0, buffer.Length);
if (buffer[5] == 0)
{// flush on heartbeat - 1 seconds
logfile.Flush();
rawlogfile.Flush();
}
}
}
}
catch (Exception ex) { log.Error(ex); }
try
{
// full rw from mirror stream
if (MirrorStream != null && MirrorStream.IsOpen)
{
MirrorStream.Write(buffer, 0, buffer.Length);
while (MirrorStream.BytesToRead > 0)
{
byte[] buf = new byte[1024];
int len = MirrorStream.Read(buf, 0, buf.Length);
BaseStream.Write(buf, 0, len);
}
}
}
catch { }
}
}
catch { }
if (buffer[3] == '3' && buffer[4] == 'D')
{
// dont update last packet time for 3dr radio packets
}
else
{
lastvalidpacket = DateTime.Now;
}
// Console.Write((DateTime.Now - start).TotalMilliseconds.ToString("00.000") + "\t" + temp.Length + " \r");
// Console.WriteLine(DateTime.Now.Millisecond + " SR4 " + BaseStream.BytesToRead);
return buffer;
}
private void PacketReceived(byte[] buffer)
{
MAVLINK_MSG_ID type = (MAVLINK_MSG_ID)buffer[5];
lock (Subscriptions)
{
foreach (var item in Subscriptions)
{
if (item.Key == type)
{
try
{
item.Value(buffer);
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
}
}
List<KeyValuePair<MAVLINK_MSG_ID,Func<byte[],bool>>> Subscriptions = new List<KeyValuePair<MAVLINK_MSG_ID,Func<byte[],bool>>>();
public KeyValuePair<MAVLINK_MSG_ID, Func<byte[], bool>> SubscribeToPacketType(MAVLINK_MSG_ID type, Func<byte[], bool> function, bool exclusive = false)
{
var item = new KeyValuePair<MAVLINK_MSG_ID,Func<byte[],bool>>(type,function);
lock (Subscriptions)
{
if (exclusive) {
foreach (var subitem in Subscriptions)
{
if (subitem.Key == item.Key)
{
Subscriptions.Remove(subitem);
break;
}
}
}
log.Info("SubscribeToPacketType " + item.Key + " " + item.Value);
Subscriptions.Add(item);
}
return item;
}
public void UnSubscribeToPacketType(KeyValuePair<MAVLINK_MSG_ID, Func<byte[], bool>> item)
{
lock (Subscriptions)
{
log.Info("UnSubscribeToPacketType " + item.Key + " " + item.Value);
Subscriptions.Remove(item);
}
}
/// <summary>
/// Used to extract mission from log file - both sent or received
/// </summary>
/// <param name="buffer">packet</param>
void getWPsfromstream(ref byte[] buffer)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.MISSION_COUNT)
{
// clear old
MAV.wps.Clear();
}
if (buffer[5] == (byte)MAVLink.MAVLINK_MSG_ID.MISSION_ITEM)
{
mavlink_mission_item_t wp = buffer.ByteArrayToStructure<mavlink_mission_item_t>(6);
if (wp.current == 2)
{
// guide mode wp
MAV.GuidedMode = wp;
}
else
{
MAV.wps[wp.seq] = wp;
}
Console.WriteLine("WP # {7} cmd {8} p1 {0} p2 {1} p3 {2} p4 {3} x {4} y {5} z {6}", wp.param1, wp.param2, wp.param3, wp.param4, wp.x, wp.y, wp.z, wp.seq, wp.command);
}
if (buffer[5] == (byte)MAVLINK_MSG_ID.RALLY_POINT)
{
mavlink_rally_point_t rallypt = buffer.ByteArrayToStructure<mavlink_rally_point_t>(6);
MAV.rallypoints[rallypt.idx] = rallypt;
Console.WriteLine("RP # {0} {1} {2} {3} {4}", rallypt.idx, rallypt.lat,rallypt.lng,rallypt.alt, rallypt.break_alt);
}
if (buffer[5] == (byte)MAVLINK_MSG_ID.FENCE_POINT)
{
mavlink_fence_point_t fencept = buffer.ByteArrayToStructure<mavlink_fence_point_t>(6);
MAV.fencepoints[fencept.idx] = fencept;
}
}
public PointLatLngAlt getFencePoint(int no, ref int total)
{
byte[] buffer;
giveComport = true;
PointLatLngAlt plla = new PointLatLngAlt();
mavlink_fence_fetch_point_t req = new mavlink_fence_fetch_point_t();
req.idx = (byte)no;
req.target_component = MAV.compid;
req.target_system = MAV.sysid;
// request point
generatePacket((byte)MAVLINK_MSG_ID.FENCE_FETCH_POINT, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("getFencePoint Retry " + retrys + " - giv com " + giveComport);
generatePacket((byte)MAVLINK_MSG_ID.FENCE_FETCH_POINT, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - getFencePoint");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.FENCE_POINT)
{
giveComport = false;
mavlink_fence_point_t fp = buffer.ByteArrayToStructure<mavlink_fence_point_t>(6);
plla.Lat = fp.lat;
plla.Lng = fp.lng;
plla.Tag = fp.idx.ToString();
total = fp.count;
return plla;
}
}
}
}
public MemoryStream GetLog(ushort no)
{
MemoryStream ms = new MemoryStream();
Hashtable set = new Hashtable();
giveComport = true;
byte[] buffer;
if (Progress != null)
{
Progress((int)0, "");
}
uint totallength = 0;
uint ofs = 0;
uint bps = 0;
DateTime bpstimer = DateTime.Now;
mavlink_log_request_data_t req = new mavlink_log_request_data_t();
req.target_component = MAV.compid;
req.target_system = MAV.sysid;
req.id = no;
req.ofs = ofs;
// entire log
req.count = 0xFFFFFFFF;
// request point
generatePacket((byte)MAVLINK_MSG_ID.LOG_REQUEST_DATA, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(1000) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("GetLog Retry " + retrys + " - giv com " + giveComport);
generatePacket((byte)MAVLINK_MSG_ID.LOG_REQUEST_DATA, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - GetLog");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.LOG_DATA)
{
var data = buffer.ByteArrayToStructure<mavlink_log_data_t>();
if (data.id != no)
continue;
// reset retrys
retrys = 3;
start = DateTime.Now;
bps += data.count;
// record what we have received
set[(data.ofs / 90).ToString()] = 1;
ms.Seek((long)data.ofs, SeekOrigin.Begin);
ms.Write(data.data, 0, data.count);
// update new start point
req.ofs = data.ofs + data.count;
if (bpstimer.Second != DateTime.Now.Second)
{
if (Progress != null)
{
Progress((int)req.ofs, "");
}
//Console.WriteLine("log dl bps: " + bps.ToString());
bpstimer = DateTime.Now;
bps = 0;
}
// if data is less than max packet size or 0 > exit
if (data.count < 90 || data.count == 0)
{
totallength = data.ofs + data.count;
log.Info("start fillin len " + totallength + " count " + set.Count + " datalen " + data.count);
break;
}
}
}
}
log.Info("set count " + set.Count);
log.Info("count total " + ((totallength) / 90 + 1));
log.Info("totallength " + totallength);
log.Info("current length " + ms.Length);
while (true)
{
if (totallength == ms.Length && set.Count >= ((totallength) / 90 + 1))
{
giveComport = false;
return ms;
}
if (!(start.AddMilliseconds(200) > DateTime.Now))
{
for (int a = 0; a < ((totallength) / 90 + 1); a++)
{
if (!set.ContainsKey(a.ToString()))
{
// request large chunk if they are back to back
uint bytereq = 90;
int b = a + 1;
while (!set.ContainsKey(b.ToString()))
{
bytereq += 90;
b++;
}
req.ofs = (uint)(a * 90);
req.count = bytereq;
log.Info("req missing " + req.ofs + " " + req.count);
generatePacket((byte)MAVLINK_MSG_ID.LOG_REQUEST_DATA, req);
start = DateTime.Now;
break;
}
}
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.LOG_DATA)
{
var data = buffer.ByteArrayToStructure<mavlink_log_data_t>();
if (data.id != no)
continue;
// reset retrys
retrys = 3;
start = DateTime.Now;
bps += data.count;
// record what we have received
set[(data.ofs / 90).ToString()] = 1;
ms.Seek((long)data.ofs, SeekOrigin.Begin);
ms.Write(data.data, 0, data.count);
// update new start point
req.ofs = data.ofs + data.count;
if (bpstimer.Second != DateTime.Now.Second)
{
if (Progress != null)
{
Progress((int)req.ofs, "");
}
//Console.WriteLine("log dl bps: " + bps.ToString());
bpstimer = DateTime.Now;
bps = 0;
}
// check if we have next set and invalidate to request next packets
if (set.ContainsKey(((data.ofs / 90) + 1).ToString()))
{
start = DateTime.MinValue;
}
// if data is less than max packet size or 0 > exit
if (data.count < 90 || data.count == 0)
{
continue;
}
}
}
}
}
public List<mavlink_log_entry_t> GetLogList()
{
List<mavlink_log_entry_t> ans = new List<mavlink_log_entry_t>();
mavlink_log_entry_t entry1 = GetLogEntry(0, ushort.MaxValue);
log.Info("id "+entry1.id + " lln " + entry1.last_log_num + " logs " + entry1.num_logs + " size " + entry1.size);
//ans.Add(entry1);
for (ushort a = (ushort)(entry1.last_log_num - entry1.num_logs + 1); a <= entry1.last_log_num; a++)
{
mavlink_log_entry_t entry = GetLogEntry(a, a);
ans.Add(entry);
}
return ans;
}
public mavlink_log_entry_t GetLogEntry(ushort startno = 0, ushort endno = ushort.MaxValue)
{
giveComport = true;
byte[] buffer;
mavlink_log_request_list_t req = new mavlink_log_request_list_t();
req.target_component = MAV.compid;
req.target_system = MAV.sysid;
req.start = startno;
req.end = endno;
// request point
generatePacket((byte)MAVLINK_MSG_ID.LOG_REQUEST_LIST, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("GetLogList Retry " + retrys + " - giv com " + giveComport);
generatePacket((byte)MAVLINK_MSG_ID.LOG_REQUEST_LIST, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - GetLogList");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.LOG_ENTRY)
{
var ans = buffer.ByteArrayToStructure<mavlink_log_entry_t>();
if (ans.id >= startno && ans.id <= endno)
{
giveComport = false;
return ans;
}
}
}
}
}
public void EraseLog()
{
mavlink_log_erase_t req = new mavlink_log_erase_t();
req.target_component = MAV.compid;
req.target_system = MAV.sysid;
// send twice - we have no feedback on this
generatePacket((byte)MAVLINK_MSG_ID.LOG_ERASE, req);
generatePacket((byte)MAVLINK_MSG_ID.LOG_ERASE, req);
}
public List<PointLatLngAlt> getRallyPoints()
{
List<PointLatLngAlt> points = new List<PointLatLngAlt>();
if (!MAV.param.ContainsKey("RALLY_TOTAL"))
return points;
int count = int.Parse(MAV.param["RALLY_TOTAL"].ToString());
for (int a = 0; a < (count - 1); a++)
{
try
{
PointLatLngAlt plla = MainV2.comPort.getRallyPoint(a, ref count);
points.Add(plla);
}
catch { return points; }
}
return points;
}
public PointLatLngAlt getRallyPoint(int no, ref int total)
{
byte[] buffer;
giveComport = true;
PointLatLngAlt plla = new PointLatLngAlt();
mavlink_rally_fetch_point_t req = new mavlink_rally_fetch_point_t();
req.idx = (byte)no;
req.target_component = MAV.compid;
req.target_system = MAV.sysid;
// request point
generatePacket((byte)MAVLINK_MSG_ID.RALLY_FETCH_POINT, req);
DateTime start = DateTime.Now;
int retrys = 3;
while (true)
{
if (!(start.AddMilliseconds(700) > DateTime.Now))
{
if (retrys > 0)
{
log.Info("getRallyPoint Retry " + retrys + " - giv com " + giveComport);
generatePacket((byte)MAVLINK_MSG_ID.FENCE_FETCH_POINT, req);
start = DateTime.Now;
retrys--;
continue;
}
giveComport = false;
throw new Exception("Timeout on read - getRallyPoint");
}
buffer = readPacket();
if (buffer.Length > 5)
{
if (buffer[5] == (byte)MAVLINK_MSG_ID.RALLY_POINT)
{
giveComport = false;
mavlink_rally_point_t fp = buffer.ByteArrayToStructure<mavlink_rally_point_t>(6);
plla.Lat = fp.lat / t7;
plla.Lng = fp.lng / t7;
plla.Tag = fp.idx.ToString();
plla.Alt = fp.alt;
total = fp.count;
return plla;
}
}
}
}
public bool setFencePoint(byte index, PointLatLngAlt plla, byte fencepointcount)
{
mavlink_fence_point_t fp = new mavlink_fence_point_t();
fp.idx = index;
fp.count = fencepointcount;
fp.lat = (float)plla.Lat;
fp.lng = (float)plla.Lng;
fp.target_component = MAV.compid;
fp.target_system = MAV.sysid;
int retry = 3;
while (retry > 0)
{
generatePacket((byte)MAVLINK_MSG_ID.FENCE_POINT, fp);
int counttemp = 0;
PointLatLngAlt newfp = getFencePoint(fp.idx, ref counttemp);
if (newfp.Lat == plla.Lat && newfp.Lng == fp.lng)
return true;
retry--;
}
return false;
}
public bool setRallyPoint(byte index, PointLatLngAlt plla,short break_alt, UInt16 land_dir_cd, byte flags, byte rallypointcount)
{
mavlink_rally_point_t rp = new mavlink_rally_point_t();
rp.idx = index;
rp.count = rallypointcount;
rp.lat = (int)(plla.Lat * t7);
rp.lng = (int)(plla.Lng * t7);
rp.alt = (short)plla.Alt;
rp.break_alt = break_alt;
rp.land_dir = land_dir_cd;
rp.flags = (byte)flags;
rp.target_component = MAV.compid;
rp.target_system = MAV.sysid;
int retry = 3;
while (retry > 0)
{
generatePacket((byte)MAVLINK_MSG_ID.RALLY_POINT, rp);
int counttemp = 0;
PointLatLngAlt newfp = getRallyPoint(rp.idx, ref counttemp);
if (newfp.Lat == plla.Lat && newfp.Lng == rp.lng)
{
Console.WriteLine("Rally Set");
return true;
}
retry--;
}
return false;
}
byte[] readlogPacket()
{
byte[] temp = new byte[300];
MAV.sysid = 0;
int a = 0;
while (a < temp.Length && logplaybackfile.BaseStream.Position != logplaybackfile.BaseStream.Length)
{
temp[a] = (byte)logplaybackfile.BaseStream.ReadByte();
//Console.Write((char)temp[a]);
if (temp[a] == ':')
{
break;
}
a++;
if (temp[0] != '-')
{
a = 0;
}
}
//Console.Write('\n');
//Encoding.ASCII.GetString(temp, 0, a);
string datestring = Encoding.ASCII.GetString(temp, 0, a);
//Console.WriteLine(datestring);
long date = Int64.Parse(datestring);
DateTime date1 = DateTime.FromBinary(date);
lastlogread = date1;
int length = 5;
a = 0;
while (a < length)
{
temp[a] = (byte)logplaybackfile.BaseStream.ReadByte();
if (a == 1)
{
length = temp[1] + 6 + 2 + 1;
}
a++;
}
return temp;
}
byte[] readlogPacketMavlink()
{
byte[] temp = new byte[300];
MAV.sysid = 0;
//byte[] datearray = BitConverter.GetBytes((ulong)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
byte[] datearray = new byte[8];
int tem = logplaybackfile.BaseStream.Read(datearray, 0, datearray.Length);
Array.Reverse(datearray);
DateTime date1 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
UInt64 dateint = BitConverter.ToUInt64(datearray, 0);
try
{
// array is reversed above
if (datearray[7] == 254)
{
//rewind 8bytes
logplaybackfile.BaseStream.Seek(-8, SeekOrigin.Current);
}
else
{
date1 = date1.AddMilliseconds(dateint / 1000);
lastlogread = date1.ToLocalTime();
}
}
catch { }
MAV.cs.datetime = lastlogread;
int length = 5;
int a = 0;
while (a < length)
{
if (logplaybackfile.BaseStream.Position == logplaybackfile.BaseStream.Length)
break;
temp[a] = (byte)logplaybackfile.ReadByte();
if (temp[0] != 'U' && temp[0] != 254)
{
log.InfoFormat("logread - lost sync byte {0} pos {1}", temp[0], logplaybackfile.BaseStream.Position);
a = 0;
continue;
}
if (a == 1)
{
length = temp[1] + 6 + 2; // 6 header + 2 checksum
}
a++;
}
// set ap type for log file playback
if (temp[5] == 0 && a > 5)
{
mavlink_heartbeat_t hb = temp.ByteArrayToStructure<mavlink_heartbeat_t>(6);
if (hb.type != (byte)MAVLink.MAV_TYPE.GCS)
{
mavlinkversion = hb.mavlink_version;
MAV.aptype = (MAV_TYPE)hb.type;
MAV.apname = (MAV_AUTOPILOT)hb.autopilot;
setAPType();
}
}
return temp;
}
public bool translateMode(string modein, ref MAVLink.mavlink_set_mode_t mode)
{
mode.target_system = MAV.sysid;
if (modein == null || modein == "")
return false;
try
{
List<KeyValuePair<int, string>> modelist = Common.getModesList(MAV.cs);
foreach (KeyValuePair<int, string> pair in modelist)
{
if (pair.Value.ToLower() == modein.ToLower())
{
mode.base_mode = (byte)MAVLink.MAV_MODE_FLAG.CUSTOM_MODE_ENABLED;
mode.custom_mode = (uint)pair.Key;
}
}
if (mode.base_mode == 0)
{
MessageBox.Show("No Mode Changed " + modein);
return false;
}
}
catch { System.Windows.Forms.MessageBox.Show("Failed to find Mode"); return false; }
return true;
}
public void setAPType()
{
switch (MAV.apname)
{
case MAV_AUTOPILOT.ARDUPILOTMEGA:
switch (MAV.aptype)
{
case MAVLink.MAV_TYPE.FIXED_WING:
MAV.cs.firmware = MainV2.Firmwares.ArduPlane;
break;
case MAVLink.MAV_TYPE.QUADROTOR:
MAV.cs.firmware = MainV2.Firmwares.ArduCopter2;
break;
case MAVLink.MAV_TYPE.TRICOPTER:
MAV.cs.firmware = MainV2.Firmwares.ArduCopter2;
break;
case MAVLink.MAV_TYPE.HEXAROTOR:
MAV.cs.firmware = MainV2.Firmwares.ArduCopter2;
break;
case MAVLink.MAV_TYPE.OCTOROTOR:
MAV.cs.firmware = MainV2.Firmwares.ArduCopter2;
break;
case MAVLink.MAV_TYPE.HELICOPTER:
MAV.cs.firmware = MainV2.Firmwares.ArduCopter2;
break;
case MAVLink.MAV_TYPE.GROUND_ROVER:
MAV.cs.firmware = MainV2.Firmwares.ArduRover;
break;
default:
break;
}
break;
case MAV_AUTOPILOT.UDB:
switch (MAV.aptype)
{
case MAVLink.MAV_TYPE.FIXED_WING:
MAV.cs.firmware = MainV2.Firmwares.ArduPlane;
break;
}
break;
case MAV_AUTOPILOT.GENERIC:
switch (MAV.aptype)
{
case MAVLink.MAV_TYPE.FIXED_WING:
MAV.cs.firmware = MainV2.Firmwares.Ateryx;
break;
}
break;
}
}
public override string ToString()
{
return "MAV " + MAV.sysid + " on " + BaseStream.PortName;
}
public void Dispose()
{
if (_bytesReceivedSubj != null)
_bytesReceivedSubj.Dispose();
if (_bytesSentSubj != null)
_bytesSentSubj.Dispose();
this.Close();
}
}
} | gpl-3.0 |
rikardfalkeborn/mandelbulber2 | mandelbulber2/src/opencl_engine_render_fractal.cpp | 39455 | /**
* Mandelbulber v2, a 3D fractal generator ,=#MKNmMMKmmßMNWy,
* ,B" ]L,,p%%%,,,§;, "K
* Copyright (C) 2017-18 Mandelbulber Team §R-==%w["'~5]m%=L.=~5N
* ,=mm=§M ]=4 yJKA"/-Nsaj "Bw,==,,
* This file is part of Mandelbulber. §R.r= jw",M Km .mM FW ",§=ß., ,TN
* ,4R =%["w[N=7]J '"5=],""]]M,w,-; T=]M
* Mandelbulber is free software: §R.ß~-Q/M=,=5"v"]=Qf,'§"M= =,M.§ Rz]M"Kw
* you can redistribute it and/or §w "xDY.J ' -"m=====WeC=\ ""%""y=%"]"" §
* modify it under the terms of the "§M=M =D=4"N #"%==A%p M§ M6 R' #"=~.4M
* GNU General Public License as §W =, ][T"]C § § '§ e===~ U !§[Z ]N
* published by the 4M",,Jm=,"=e~ § § j]]""N BmM"py=ßM
* Free Software Foundation, ]§ T,M=& 'YmMMpM9MMM%=w=,,=MT]M m§;'§,
* either version 3 of the License, TWw [.j"5=~N[=§%=%W,T ]R,"=="Y[LFT ]N
* or (at your option) TW=,-#"%=;[ =Q:["V"" ],,M.m == ]N
* any later version. J§"mr"] ,=,," =="""J]= M"M"]==ß"
* §= "=C=4 §"eM "=B:m|4"]#F,§~
* Mandelbulber is distributed in "9w=,,]w em%wJ '"~" ,=,,ß"
* the hope that it will be useful, . "K= ,=RMMMßM"""
* 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 Mandelbulber. If not, see <http://www.gnu.org/licenses/>.
*
* ###########################################################################
*
* Authors: Krzysztof Marczak ([email protected]), Robert Pancoast ([email protected]),
* Sebastian Jennen ([email protected])
*
* cOpenClEngineRenderFractal - prepares and executes fractal rendering on opencl
*/
#include "opencl_engine_render_fractal.h"
#include <functional>
#include <QtAlgorithms>
#include "camera_target.hpp"
#include "cimage.hpp"
#include "common_math.h"
#include "files.h"
#include "fractal.h"
#include "fractal_formulas.hpp"
#include "fractal_list.hpp"
#include "fractparams.hpp"
#include "global_data.hpp"
#include "material.h"
#include "nine_fractals.hpp"
#include "opencl_dynamic_data.hpp"
#include "opencl_hardware.h"
#include "parameters.hpp"
#include "progress_text.hpp"
#include "rectangle.hpp"
#include "render_data.hpp"
#include "render_worker.hpp"
#include "texture.hpp"
// custom includes
#ifdef USE_OPENCL
#include "opencl/fractal_cl.h"
#include "opencl/fractparams_cl.hpp"
#endif
cOpenClEngineRenderFractal::cOpenClEngineRenderFractal(cOpenClHardware *_hardware)
: cOpenClEngine(_hardware)
{
#ifdef USE_OPENCL
constantInBuffer = nullptr;
inCLConstBuffer = nullptr;
backgroungImageBuffer = nullptr;
backgroundImage2D = nullptr;
inCLBuffer = nullptr;
dynamicData = new cOpenClDynamicData;
optimalJob.sizeOfPixel = sizeof(sClPixel);
autoRefreshMode = false;
monteCarlo = false;
renderEngineMode = clRenderEngineTypeNone;
#endif
}
cOpenClEngineRenderFractal::~cOpenClEngineRenderFractal()
{
#ifdef USE_OPENCL
ReleaseMemory();
#endif
}
#ifdef USE_OPENCL
void cOpenClEngineRenderFractal::ReleaseMemory()
{
if (constantInBuffer) delete constantInBuffer;
constantInBuffer = nullptr;
if (inCLConstBuffer) delete inCLConstBuffer;
inCLConstBuffer = nullptr;
if (inCLBuffer) delete inCLBuffer;
inCLBuffer = nullptr;
if (backgroungImageBuffer) delete backgroungImageBuffer;
backgroungImageBuffer = nullptr;
dynamicData->Clear();
}
QString cOpenClEngineRenderFractal::GetKernelName()
{
return QString("fractal3D");
}
bool cOpenClEngineRenderFractal::LoadSourcesAndCompile(const cParameterContainer *params)
{
programsLoaded = false;
readyForRendering = false;
emit updateProgressAndStatus(tr("OpenCl - initializing"), tr("Compiling OpenCL programs"), 0.0);
QByteArray programEngine;
try
{
QString openclPath = systemData.sharedDir + "opencl" + QDir::separator();
QString openclEnginePath = openclPath + "engines" + QDir::separator();
QStringList clHeaderFiles;
clHeaderFiles.append("defines_cl.h");
clHeaderFiles.append("opencl_typedefs.h");
clHeaderFiles.append("opencl_algebra.h");
clHeaderFiles.append("common_params_cl.hpp");
clHeaderFiles.append("image_adjustments_cl.h");
clHeaderFiles.append("fractal_cl.h");
clHeaderFiles.append("fractal_coloring_cl.hpp");
clHeaderFiles.append("fractparams_cl.hpp");
clHeaderFiles.append("fractal_sequence_cl.h");
clHeaderFiles.append("material_cl.h");
clHeaderFiles.append("object_type_cl.h");
clHeaderFiles.append("object_data_cl.h");
clHeaderFiles.append("primitives_cl.h");
clHeaderFiles.append("input_data_structures.h");
clHeaderFiles.append("render_data_cl.h");
// pass through define constants
programEngine.append("#define USE_OPENCL 1\n");
if (params->Get<bool>("opencl_precision"))
programEngine.append("#define DOUBLE_PRECISION " + QString::number(1) + "\n");
#ifdef _WIN32
QString openclPathSlash = openclPath.replace("/", "\\"); // replace single slash with backslash
#else
QString openclPathSlash = openclPath;
#endif
for (int i = 0; i < clHeaderFiles.size(); i++)
{
programEngine.append("#include \"" + openclPathSlash + clHeaderFiles.at(i) + "\"\n");
}
if (params->Get<bool>("box_folding") || params->Get<bool>("spherical_folding"))
{
programEngine.append("#include \"" + openclEnginePath + "basic_foldings.cl\"\n");
}
// fractal formulas - only actually used
for (int i = 0; i < listOfUsedFormulas.size(); i++)
{
QString formulaName = listOfUsedFormulas.at(i);
if (formulaName != "")
{
programEngine.append("#include \"" + systemData.sharedDir + "formula" + QDir::separator()
+ "opencl" + QDir::separator() + formulaName + ".cl\"\n");
}
}
if (renderEngineMode != clRenderEngineTypeFast)
{
// fractal coloring
programEngine.append("#include \"" + openclEnginePath + "fractal_coloring.cl\"\n");
}
// compute fractal
programEngine.append("#include \"" + openclEnginePath + "compute_fractal.cl\"\n");
// compute fractal
programEngine.append("#include \"" + openclEnginePath + "primitives.cl\"\n");
// calculate distance
programEngine.append("#include \"" + openclEnginePath + "calculate_distance.cl\"\n");
// normal vector calculation
programEngine.append("#include \"" + openclEnginePath + "normal_vector.cl\"\n");
// 3D projections (3point, equirectagular, fisheye)
programEngine.append("#include \"" + openclEnginePath + "projection_3d.cl\"\n");
if (renderEngineMode != clRenderEngineTypeFast)
{
// shaders
programEngine.append("#include \"" + openclEnginePath + "shaders.cl\"\n");
}
if (renderEngineMode == clRenderEngineTypeFull)
{
// ray recursion
programEngine.append("#include \"" + openclEnginePath + "ray_recursion.cl\"\n");
}
if (renderEngineMode != clRenderEngineTypeFast)
{
// Monte Carlo DOF
programEngine.append("#include \"" + openclEnginePath + "monte_carlo_dof.cl\"\n");
}
// main engine
QString engineFileName;
switch (renderEngineMode)
{
case clRenderEngineTypeFast: engineFileName = "fast_engine.cl"; break;
case clRenderEngineTypeLimited: engineFileName = "limited_engine.cl"; break;
case clRenderEngineTypeFull: engineFileName = "full_engine.cl"; break;
case clRenderEngineTypeNone: break;
}
QString engineFullFileName = openclEnginePath + engineFileName;
programEngine.append(LoadUtf8TextFromFile(engineFullFileName));
}
catch (const QString &ex)
{
qCritical() << "OpenCl program error: " << ex;
return false;
}
SetUseBuildCache(!params->Get<bool>("opencl_disable_build_cache"));
SetUseFastRelaxedMath(params->Get<bool>("opencl_use_fast_relaxed_math"));
// building OpenCl kernel
QString errorString;
QElapsedTimer timer;
timer.start();
if (Build(programEngine, &errorString))
{
programsLoaded = true;
}
else
{
programsLoaded = false;
WriteLog(errorString, 0);
}
WriteLogDouble(
"cOpenClEngineRenderFractal: Opencl DOF build time [s]", timer.nsecsElapsed() / 1.0e9, 2);
return programsLoaded;
}
void cOpenClEngineRenderFractal::SetParameters(const cParameterContainer *paramContainer,
const cFractalContainer *fractalContainer, sParamRender *paramRender, cNineFractals *fractals,
sRenderData *renderData)
{
Q_UNUSED(fractalContainer);
if (constantInBuffer) delete constantInBuffer;
constantInBuffer = new sClInConstants;
definesCollector.clear();
renderEngineMode = enumClRenderEngineMode(paramContainer->Get<int>("opencl_mode"));
// update camera rotation data (needed for simplified calculation in opencl kernel)
cCameraTarget cameraTarget(paramRender->camera, paramRender->target, paramRender->topVector);
paramRender->viewAngle = cameraTarget.GetRotation() * 180.0 / M_PI;
paramRender->resolution = 1.0 / paramRender->imageHeight;
if (renderEngineMode == clRenderEngineTypeFull) definesCollector += " -DFULL_ENGINE";
// define distance estimation method
fractal::enumDEType deType = fractals->GetDEType(0);
fractal::enumDEFunctionType deFunctionType = fractals->GetDEFunctionType(0);
if (fractals->IsHybrid()) definesCollector += " -DIS_HYBRID";
bool useAnalyticDEType = false;
bool useDeltaDEType = false;
bool useLinearDEFunction = false;
bool useLogarithmicDEFunction = false;
bool usePseudoKleinianDEFunction = false;
if (fractals->IsHybrid())
{
if (deType == fractal::analyticDEType)
{
useAnalyticDEType = true;
switch (deFunctionType)
{
case fractal::linearDEFunction: definesCollector += " -DANALYTIC_LINEAR_DE"; break;
case fractal::logarithmicDEFunction: definesCollector += " -DANALYTIC_LOG_DE"; break;
case fractal::pseudoKleinianDEFunction:
definesCollector += " -DANALYTIC_PSEUDO_KLEINIAN_DE";
break;
case fractal::josKleinianDEFunction:
definesCollector += " -DANALYTIC_JOS_KLEINIAN_DE";
break;
default: break;
}
}
if (deType == fractal::deltaDEType)
{
useDeltaDEType = true;
switch (fractals->GetDEFunctionType(0))
{
case fractal::linearDEFunction: useLinearDEFunction = true; break;
case fractal::logarithmicDEFunction: useLogarithmicDEFunction = true; break;
case fractal::pseudoKleinianDEFunction: usePseudoKleinianDEFunction = true; break;
default: break;
}
}
}
else // is not Hybrid
{
for (int i = 0; i < NUMBER_OF_FRACTALS; i++)
{
if (!paramRender->booleanOperatorsEnabled && i == 1) break;
if (fractals->GetDEType(i) == fractal::analyticDEType)
{
useAnalyticDEType = true;
}
else if (fractals->GetDEType(i) == fractal::deltaDEType)
{
useDeltaDEType = true;
switch (fractals->GetDEFunctionType(i))
{
case fractal::linearDEFunction: useLinearDEFunction = true; break;
case fractal::logarithmicDEFunction: useLogarithmicDEFunction = true; break;
case fractal::pseudoKleinianDEFunction: usePseudoKleinianDEFunction = true; break;
default: break;
}
}
}
}
if (useAnalyticDEType) definesCollector += " -DANALYTIC_DE";
if (useDeltaDEType) definesCollector += " -DDELTA_DE";
if (useLinearDEFunction) definesCollector += " -DDELTA_LINEAR_DE";
if (useLogarithmicDEFunction) definesCollector += " -DDELTA_LOG_DE";
if (usePseudoKleinianDEFunction) definesCollector += " -DDELTA_PSEUDO_KLEINIAN_DE";
if (paramRender->limitsEnabled) definesCollector += " -DLIMITS_ENABLED";
listOfUsedFormulas.clear();
// creating list of used formulas
for (int i = 0; i < NUMBER_OF_FRACTALS; i++)
{
fractal::enumFractalFormula fractalFormula = fractals->GetFractal(i)->formula;
int listIndex = cNineFractals::GetIndexOnFractalList(fractalFormula);
QString formulaName = fractalList.at(listIndex).internalName;
listOfUsedFormulas.append(formulaName);
}
// adding #defines to the list
for (int i = 0; i < listOfUsedFormulas.size(); i++)
{
QString internalID = toCamelCase(listOfUsedFormulas.at(i));
if (internalID != "")
{
QString functionName = internalID.left(1).toUpper() + internalID.mid(1) + "Iteration";
definesCollector += " -DFORMULA_ITER_" + QString::number(i) + "=" + functionName;
}
}
if (paramRender->common.foldings.boxEnable) definesCollector += " -DBOX_FOLDING";
if (paramRender->common.foldings.sphericalEnable) definesCollector += " -DSPHERICAL_FOLDING";
bool weightUsed = false;
for (int i = 0; i < NUMBER_OF_FRACTALS; i++)
{
if (fractals->GetWeight(i) != 1.0)
{
weightUsed = true;
}
}
if (weightUsed) definesCollector += " -DITERATION_WEIGHT";
// ---- perspective projections ------
switch (paramRender->perspectiveType)
{
case params::perspThreePoint: definesCollector += " -DPERSP_THREE_POINT"; break;
case params::perspEquirectangular: definesCollector += " -DPERSP_EQUIRECTANGULAR"; break;
case params::perspFishEye: definesCollector += " -DPERSP_FISH_EYE"; break;
case params::perspFishEyeCut: definesCollector += " -DPERSP_FISH_EYE_CUT"; break;
}
// ------------ enabling shaders ----------
bool anyVolumetricShaderUsed = false;
if (paramRender->shadow) definesCollector += " -DSHADOWS";
if (paramRender->ambientOcclusionEnabled)
{
if (paramRender->ambientOcclusionMode == params::AOModeFast)
definesCollector += " -DAO_MODE_FAST";
else if (paramRender->ambientOcclusionMode == params::AOModeMultipleRays)
definesCollector += " -DAO_MODE_MULTIPLE_RAYS";
}
if (paramRender->slowShading) definesCollector += " -DSLOW_SHADING";
if (renderData->lights.IsAnyLightEnabled())
{
definesCollector += " -DAUX_LIGHTS";
if (paramRender->auxLightVisibility > 0.0)
{
definesCollector += " -DVISIBLE_AUX_LIGHTS";
anyVolumetricShaderUsed = true;
}
}
if (paramRender->interiorMode) definesCollector += " -DINTERIOR_MODE";
if (paramRender->booleanOperatorsEnabled) definesCollector += " -DBOOLEAN_OPERATORS";
bool isVolumetricLight = false;
for (int i = 0; i < 5; i++)
{
if (paramRender->volumetricLightEnabled[i]) isVolumetricLight = true;
}
if (isVolumetricLight)
{
definesCollector += " -DVOLUMETRIC_LIGHTS";
anyVolumetricShaderUsed = true;
}
if (paramRender->glowEnabled) definesCollector += " -DGLOW";
if (paramRender->fogEnabled)
{
definesCollector += " -DBASIC_FOG";
anyVolumetricShaderUsed = true;
}
if (paramRender->volFogEnabled && paramRender->volFogDensity > 0)
{
definesCollector += " -DVOLUMETRIC_FOG";
anyVolumetricShaderUsed = true;
}
if (paramRender->iterFogEnabled == true)
{
definesCollector += " -DITER_FOG";
anyVolumetricShaderUsed = true;
}
if (paramRender->fakeLightsEnabled == true)
{
definesCollector += " -DFAKE_LIGHTS";
anyVolumetricShaderUsed = true;
}
if (!anyVolumetricShaderUsed) definesCollector += " -DSIMPLE_GLOW";
if (paramRender->DOFMonteCarlo && paramRender->DOFEnabled)
definesCollector += " -DMONTE_CARLO_DOF";
if (paramRender->texturedBackground)
{
definesCollector += " -DTEXTURED_BACKGROUND";
switch (paramRender->texturedBackgroundMapType)
{
case params::mapEquirectangular: definesCollector += " -DBACKGROUND_EQUIRECTANGULAR"; break;
case params::mapDoubleHemisphere:
definesCollector += " -DBACKGROUND_DOUBLE_HEMISPHERE";
break;
case params::mapFlat: definesCollector += " -DBACKGROUND_FLAT"; break;
}
}
listOfUsedFormulas = listOfUsedFormulas.toSet().toList(); // eliminate duplicates
WriteLogDouble("Constant buffer size [KB]", sizeof(sClInConstants) / 1024.0, 3);
//----------- create dynamic data -----------
dynamicData->Clear();
dynamicData->ReserveHeader();
// materials
QMap<int, cMaterial> materials;
CreateMaterialsMap(paramContainer, &materials, true);
int materialsArraySize = dynamicData->BuildMaterialsData(materials);
definesCollector += " -DMAT_ARRAY_SIZE=" + QString::number(materialsArraySize);
bool anyMaterialIsReflective = false;
bool anyMaterialIsRefractive = false;
bool anyMaterialHasSpecialColoring = false;
bool anyMaterialHasIridescence = false;
bool anyMaterialHasColoringEnabled = false;
bool anyMaterialHasExtraColoringEnabled = false;
foreach (cMaterial material, materials)
{
if (material.reflectance > 0.0) anyMaterialIsReflective = true;
if (material.transparencyOfSurface > 0.0) anyMaterialIsRefractive = true;
if (material.fractalColoring.coloringAlgorithm != fractalColoring_Standard)
anyMaterialHasSpecialColoring = true;
if (material.iridescenceEnabled) anyMaterialHasIridescence = true;
if (material.useColorsFromPalette) anyMaterialHasColoringEnabled = true;
if (material.fractalColoring.extraColorEnabledFalse) anyMaterialHasExtraColoringEnabled = true;
}
if (anyMaterialIsReflective) definesCollector += " -DUSE_REFLECTANCE";
if (anyMaterialIsRefractive) definesCollector += " -DUSE_REFRACTION";
if (anyMaterialHasSpecialColoring) definesCollector += " -DUSE_COLORING_MODES";
if (anyMaterialHasIridescence) definesCollector += " -DUSE_IRIDESCENCE";
if (renderEngineMode != clRenderEngineTypeFast && anyMaterialHasColoringEnabled)
definesCollector += " -DUSE_FRACTAL_COLORING";
if (anyMaterialHasExtraColoringEnabled) definesCollector += " -DUSE_EXTRA_COLORING";
if ((anyMaterialIsReflective || anyMaterialIsRefractive) && paramRender->raytracedReflections)
{
definesCollector += " -DREFLECTIONS_MAX=" + QString::number(paramRender->reflectionsMax + 1);
}
else
{
paramRender->reflectionsMax = 0;
definesCollector += " -DREFLECTIONS_MAX=1";
}
// AO colored vectors
cRenderWorker *tempRenderWorker =
new cRenderWorker(paramRender, fractals, nullptr, renderData, nullptr);
tempRenderWorker->PrepareAOVectors();
sVectorsAround *AOVectors = tempRenderWorker->getAOVectorsAround();
int numberOfVectors = tempRenderWorker->getAoVectorsCount();
dynamicData->BuildAOVectorsData(AOVectors, numberOfVectors);
dynamicData->BuildLightsData(&renderData->lights);
dynamicData->BuildPrimitivesData(¶mRender->primitives);
if (paramRender->primitives.GetListOfPrimitives()->size() > 0)
definesCollector += " -DUSE_PRIMITIVES";
dynamicData->BuildObjectsData(&renderData->objectData);
// definesCollector += " -DOBJ_ARRAY_SIZE=" + QString::number(renderData->objectData.size());
dynamicData->FillHeader();
inBuffer = dynamicData->GetData();
//---------------- another parameters -------------
autoRefreshMode = paramContainer->Get<bool>("auto_refresh");
monteCarlo = paramRender->DOFMonteCarlo && paramRender->DOFEnabled
&& renderEngineMode != clRenderEngineTypeFast;
// copy all cl parameters to constant buffer
constantInBuffer->params = clCopySParamRenderCl(*paramRender);
constantInBuffer->params.viewAngle = toClFloat3(paramRender->viewAngle * M_PI / 180.0);
for (int i = 0; i < NUMBER_OF_FRACTALS; i++)
{
constantInBuffer->fractal[i] = clCopySFractalCl(*fractals->GetFractal(i));
}
fractals->CopyToOpenclData(&constantInBuffer->sequence);
delete tempRenderWorker;
}
void cOpenClEngineRenderFractal::RegisterInputOutputBuffers(const cParameterContainer *params)
{
Q_UNUSED(params);
outputBuffers << sClInputOutputBuffer(sizeof(sClPixel), optimalJob.stepSize, "output-buffer");
}
bool cOpenClEngineRenderFractal::PreAllocateBuffers(const cParameterContainer *params)
{
cOpenClEngine::PreAllocateBuffers(params);
Q_UNUSED(params);
cl_int err;
if (hardware->ContextCreated())
{
if (inCLConstBuffer) delete inCLConstBuffer;
inCLConstBuffer = new cl::Buffer(*hardware->getContext(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(sClInConstants), constantInBuffer, &err);
if (!checkErr(err,
"cl::Buffer(*hardware->getContext(), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, "
"sizeof(sClInConstants), constantInBuffer, &err)"))
{
emit showErrorMessage(
QObject::tr("OpenCL %1 cannot be created!").arg(QObject::tr("buffer for constants")),
cErrorMessage::errorMessage, nullptr);
return false;
}
// this buffer will be used for color palettes, lights, etc...
if (inCLBuffer) delete inCLBuffer;
inCLBuffer = new cl::Buffer(*hardware->getContext(), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
size_t(inBuffer.size()), inBuffer.data(), &err);
if (!checkErr(err,
"Buffer::Buffer(*hardware->getContext(), CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, "
"sizeof(sClInBuff), inBuffer, &err)"))
{
emit showErrorMessage(
QObject::tr("OpenCL %1 cannot be created!").arg(QObject::tr("buffer for variable data")),
cErrorMessage::errorMessage, nullptr);
return false;
}
}
else
{
emit showErrorMessage(
QObject::tr("OpenCL context is not ready"), cErrorMessage::errorMessage, nullptr);
return false;
}
return true;
}
// TODO:
// This is the hot spot for heterogeneous execution
// requires opencl for all compute resources
bool cOpenClEngineRenderFractal::Render(cImage *image, bool *stopRequest, sRenderData *renderData)
{
if (programsLoaded)
{
// The image resolution determines the total amount of work
int width = image->GetWidth();
int height = image->GetHeight();
cProgressText progressText;
progressText.ResetTimer();
emit updateProgressAndStatus(tr("OpenCl - rendering image"), progressText.getText(0.0), 0.0);
QElapsedTimer timer;
timer.start();
QElapsedTimer progressRefreshTimer;
progressRefreshTimer.start();
QElapsedTimer timerImageRefresh;
timerImageRefresh.start();
int lastRefreshTime = 1;
qint64 numberOfPixels = qint64(width) * qint64(height);
qint64 gridWidth = width / optimalJob.stepSizeX;
qint64 gridHeight = height / optimalJob.stepSizeY;
const qint64 noiseTableSize = (gridWidth + 1) * (gridHeight + 1);
double *noiseTable = new double[noiseTableSize];
for (qint64 i = 0; i < noiseTableSize; i++)
{
noiseTable[i] = 0.0;
}
int numberOfSamples = 1;
if (monteCarlo)
{
numberOfSamples = constantInBuffer->params.DOFSamples;
}
QList<QRect> lastRenderedRects;
double doneMC = 0.0f;
QList<QPoint> tileSequence = calculateOptimalTileSequence(gridWidth + 1, gridHeight + 1);
// writing data to queue
if (!WriteBuffersToQueue()) throw;
if (renderEngineMode != clRenderEngineTypeFast)
{
if (!PrepareBufferForBackground(renderData)) throw;
}
try
{
for (int monteCarloLoop = 1; monteCarloLoop <= numberOfSamples; monteCarloLoop++)
{
// TODO:
// insert device for loop here
// requires initialization for all opencl devices
// requires optimalJob for all opencl devices
lastRenderedRects.clear();
qint64 pixelsRendered = 0;
qint64 pixelsRenderedMC = 0;
int gridStep = 0;
while (pixelsRendered < numberOfPixels)
{
int gridX = tileSequence.at(gridStep).x();
int gridY = tileSequence.at(gridStep).y();
gridStep++;
const qint64 jobX = gridX * optimalJob.stepSizeX;
const qint64 jobY = gridY * optimalJob.stepSizeY;
// check if noise is still too high
bool bigNoise = true;
if (monteCarlo)
{
if (noiseTable[gridX + gridY * (gridWidth + 1)]
< constantInBuffer->params.DOFMaxNoise / 100.0
&& monteCarloLoop > constantInBuffer->params.DOFMinSamples)
bigNoise = false;
}
if (jobX >= 0 && jobX < width && jobY >= 0 && jobY < height)
{
qint64 pixelsLeftX = width - jobX;
qint64 pixelsLeftY = height - jobY;
qint64 jobWidth2 = min(optimalJob.stepSizeX, pixelsLeftX);
qint64 jobHeight2 = min(optimalJob.stepSizeY, pixelsLeftY);
if (monteCarloLoop == 1)
renderData->statistics.numberOfRenderedPixels += jobHeight2 * jobWidth2;
if (bigNoise)
{
// assign parameters to kernel
if (!AssignParametersToKernel()) throw;
// if (!autoRefreshMode && !monteCarlo && progressRefreshTimer.elapsed()
//> 1000)
// {
// const QRect currentCorners = SizedRectangle(jobX, jobY, jobWidth2,
// jobHeight2);
// MarkCurrentPendingTile(image, currentCorners);
// }
// processing queue
if (!ProcessQueue(jobX, jobY, pixelsLeftX, pixelsLeftY)) throw;
// update image when OpenCl kernel is working
if (lastRenderedRects.size() > 0
&& timerImageRefresh.nsecsElapsed() > lastRefreshTime * 1000)
{
timerImageRefresh.restart();
image->NullPostEffect(&lastRenderedRects);
image->CompileImage(&lastRenderedRects);
if (image->IsPreview())
{
image->ConvertTo8bit(&lastRenderedRects);
image->UpdatePreview(&lastRenderedRects);
emit updateImage();
}
lastRefreshTime = timerImageRefresh.nsecsElapsed() / lastRenderedRects.size();
lastRenderedRects.clear();
timerImageRefresh.restart();
}
if (!ReadBuffersFromQueue()) throw;
// Collect Pixel information from the rgbBuffer
// Populate the data into image->Put
pixelsRenderedMC += jobWidth2 * jobHeight2;
double monteCarloNoiseSum = 0.0;
double maxNoise = 0.0;
for (int x = 0; x < jobWidth2; x++)
{
for (int y = 0; y < jobHeight2; y++)
{
sClPixel pixelCl =
((sClPixel *)outputBuffers[outputIndex].ptr)[x + y * jobWidth2];
sRGBFloat pixel = {pixelCl.R, pixelCl.G, pixelCl.B};
sRGB8 color = {pixelCl.colR, pixelCl.colG, pixelCl.colB};
unsigned short opacity = pixelCl.opacity;
unsigned short alpha = pixelCl.alpha;
size_t xx = x + jobX;
size_t yy = y + jobY;
if (monteCarlo)
{
sRGBFloat oldPixel = image->GetPixelImage(xx, yy);
sRGBFloat newPixel;
newPixel.R =
oldPixel.R * (1.0 - 1.0 / monteCarloLoop) + pixel.R * (1.0 / monteCarloLoop);
newPixel.G =
oldPixel.G * (1.0 - 1.0 / monteCarloLoop) + pixel.G * (1.0 / monteCarloLoop);
newPixel.B =
oldPixel.B * (1.0 - 1.0 / monteCarloLoop) + pixel.B * (1.0 / monteCarloLoop);
image->PutPixelImage(xx, yy, newPixel);
image->PutPixelZBuffer(xx, yy, pixelCl.zBuffer);
unsigned short oldAlpha = image->GetPixelAlpha(xx, yy);
unsigned short newAlpha = (double)oldAlpha * (1.0 - 1.0 / monteCarloLoop)
+ alpha * (1.0 / monteCarloLoop);
image->PutPixelAlpha(xx, yy, newAlpha);
image->PutPixelColor(xx, yy, color);
image->PutPixelOpacity(xx, yy, opacity);
// noise estimation
double noise = (newPixel.R - oldPixel.R) * (newPixel.R - oldPixel.R)
+ (newPixel.G - oldPixel.G) * (newPixel.G - oldPixel.G)
+ (newPixel.B - oldPixel.B) * (newPixel.B - oldPixel.B);
noise *= 0.3333;
monteCarloNoiseSum += noise;
if (noise > maxNoise) maxNoise = noise;
}
else
{
image->PutPixelImage(xx, yy, pixel);
image->PutPixelZBuffer(xx, yy, pixelCl.zBuffer);
image->PutPixelColor(xx, yy, color);
image->PutPixelOpacity(xx, yy, opacity);
image->PutPixelAlpha(xx, yy, alpha);
}
}
}
renderData->statistics.totalNumberOfDOFRepeats += jobWidth2 * jobHeight2;
// total noise in last rectangle
if (monteCarlo)
{
double weight = 0.2;
double totalNoiseRect = sqrt(
(1.0 - weight) * monteCarloNoiseSum / jobWidth2 / jobHeight2 + weight * maxNoise);
noiseTable[gridX + gridY * (gridWidth + 1)] = totalNoiseRect;
}
lastRenderedRects.append(SizedRectangle(jobX, jobY, jobWidth2, jobHeight2));
} // bigNoise
pixelsRendered += jobWidth2 * jobHeight2;
if (progressRefreshTimer.elapsed() > 100)
{
double percentDone;
if (!monteCarlo)
{
percentDone = double(pixelsRendered) / numberOfPixels;
}
else
{
percentDone = double(monteCarloLoop - 1) / numberOfSamples
+ double(pixelsRendered) / numberOfPixels / numberOfSamples;
percentDone = percentDone * (1.0 - doneMC) + doneMC;
}
emit updateProgressAndStatus(
tr("OpenCl - rendering image"), progressText.getText(percentDone), percentDone);
emit updateStatistics(renderData->statistics);
gApplication->processEvents();
progressRefreshTimer.restart();
}
if (*stopRequest)
{
image->NullPostEffect(&lastRenderedRects);
image->CompileImage(&lastRenderedRects);
if (image->IsPreview())
{
image->ConvertTo8bit(&lastRenderedRects);
image->UpdatePreview(&lastRenderedRects);
emit updateImage();
}
lastRenderedRects.clear();
delete[] noiseTable;
return false;
}
}
}
// update last rectangle
if (monteCarlo)
{
if (lastRenderedRects.size() > 0)
{
QElapsedTimer timerImageRefresh;
timerImageRefresh.start();
image->NullPostEffect(&lastRenderedRects);
image->CompileImage(&lastRenderedRects);
if (image->IsPreview())
{
image->ConvertTo8bit(&lastRenderedRects);
image->UpdatePreview(&lastRenderedRects);
emit updateImage();
}
lastRenderedRects.clear();
}
if (pixelsRendered > 0)
doneMC = 1.0 - double(pixelsRenderedMC) / pixelsRendered;
else
doneMC = 0.0;
gApplication->processEvents();
}
double totalNoise = 0.0;
for (qint64 i = 0; i < noiseTableSize; i++)
{
totalNoise += noiseTable[i];
}
totalNoise /= noiseTableSize;
renderData->statistics.totalNoise = totalNoise * width * height;
emit updateStatistics(renderData->statistics);
} // monte carlo loop
}
catch (...)
{
delete[] noiseTable;
emit updateProgressAndStatus(tr("OpenCl - rendering failed"), progressText.getText(1.0), 1.0);
return false;
}
delete[] noiseTable;
WriteLogDouble(
"cOpenClEngineRenderFractal: OpenCL Rendering time [s]", timer.nsecsElapsed() / 1.0e9, 2);
// refresh image at end
image->NullPostEffect(&lastRenderedRects);
WriteLog("image->CompileImage()", 2);
image->CompileImage(&lastRenderedRects);
if (image->IsPreview())
{
WriteLog("image->ConvertTo8bit()", 2);
image->ConvertTo8bit(&lastRenderedRects);
// WriteLog("image->UpdatePreview()", 2);
// image->UpdatePreview(&lastRenderedRects);
// WriteLog("image->GetImageWidget()->update()", 2);
// emit updateImage();
}
emit updateProgressAndStatus(tr("OpenCl - rendering finished"), progressText.getText(1.0), 1.0);
return true;
}
else
{
return false;
}
}
QList<QPoint> cOpenClEngineRenderFractal::calculateOptimalTileSequence(
int gridWidth, int gridHeight)
{
QList<QPoint> tiles;
for (int i = 0; i < gridWidth * gridHeight; i++)
{
tiles.append(QPoint(i % gridWidth, i / gridWidth));
}
qSort(tiles.begin(), tiles.end(),
std::bind(cOpenClEngineRenderFractal::sortByCenterDistanceAsc, std::placeholders::_1,
std::placeholders::_2, gridWidth, gridHeight));
return tiles;
}
bool cOpenClEngineRenderFractal::sortByCenterDistanceAsc(
const QPoint &v1, const QPoint &v2, int gridWidth, int gridHeight)
{
// choose the tile with the lower distance to the center
QPoint center;
center.setX((gridWidth - 1) / 2);
center.setY((gridHeight - 1) / 2);
QPointF cV1 = center - v1;
cV1.setX(cV1.x() * gridHeight / gridWidth);
QPointF cV2 = center - v2;
cV2.setX(cV2.x() * gridHeight / gridWidth);
double dist2V1 = cV1.x() * cV1.x() + cV1.y() * cV1.y();
double dist2V2 = cV2.x() * cV2.x() + cV2.y() * cV2.y();
if (dist2V1 != dist2V2) return dist2V1 < dist2V2;
// order tiles with same distsance clockwise
int quartV1 = cV1.x() > 0 ? (cV1.y() > 0 ? 1 : 0) : (cV1.y() > 0 ? 2 : 3);
int quartV2 = cV2.x() > 0 ? (cV2.y() > 0 ? 1 : 0) : (cV2.y() > 0 ? 2 : 3);
if (quartV1 != quartV2) return quartV1 < quartV2;
return quartV1 < 2 ? v1.y() >= v2.y() : v1.y() < v2.y();
}
void cOpenClEngineRenderFractal::MarkCurrentPendingTile(cImage *image, QRect corners)
{
int edgeWidth = max(1, min(corners.width(), corners.height()) / 10);
int edgeLength = max(1, min(corners.width(), corners.height()) / 4);
for (int _xx = 0; _xx < corners.width(); _xx++)
{
int xx = _xx + corners.x();
for (int _yy = 0; _yy < corners.height(); _yy++)
{
int yy = _yy + corners.y();
bool border = false;
if (_xx < edgeWidth || _xx > corners.width() - edgeWidth)
{
border = _yy < edgeLength || _yy > corners.height() - edgeLength;
}
if (!border && (_yy < edgeWidth || _yy > corners.height() - edgeWidth))
{
border = _xx < edgeLength || _xx > corners.width() - edgeLength;
}
image->PutPixelImage(xx, yy, border ? sRGBFloat(1, 1, 1) : sRGBFloat(0, 0, 0));
image->PutPixelColor(xx, yy, sRGB8(255, 255, 255));
image->PutPixelOpacity(xx, yy, 65535);
image->PutPixelAlpha(xx, yy, 1);
}
}
QList<QRect> currentRenderededLines;
currentRenderededLines << corners;
image->NullPostEffect(¤tRenderededLines);
image->CompileImage(¤tRenderededLines);
if (image->IsPreview())
{
image->ConvertTo8bit(¤tRenderededLines);
image->UpdatePreview(¤tRenderededLines);
emit updateImage();
}
}
QString cOpenClEngineRenderFractal::toCamelCase(const QString &s)
{
QStringList upperCaseLookup({"Vs", "Kifs", "De", "Xyz", "Cxyz", "Vcl", "Chs"});
QStringList parts = s.split('_', QString::SkipEmptyParts);
for (int i = 1; i < parts.size(); ++i)
{
parts[i].replace(0, 1, parts[i][0].toUpper());
// rewrite to known capital names in iteration function names
if (upperCaseLookup.contains(parts[i]))
{
parts[i] = parts[i].toUpper();
}
}
return parts.join("");
}
bool cOpenClEngineRenderFractal::AssignParametersToKernelAdditional(int argIterator)
{
int err = kernel->setArg(argIterator++, *inCLBuffer); // input data in global memory
if (!checkErr(err, "kernel->setArg(1, *inCLBuffer)"))
{
emit showErrorMessage(
QObject::tr("Cannot set OpenCL argument for %1").arg(QObject::tr("input data")),
cErrorMessage::errorMessage, nullptr);
return false;
}
err = kernel->setArg(
argIterator++, *inCLConstBuffer); // input data in constant memory (faster than global)
if (!checkErr(err, "kernel->setArg(2, *inCLConstBuffer)"))
{
emit showErrorMessage(
QObject::tr("Cannot set OpenCL argument for %2").arg(QObject::tr("constant data")),
cErrorMessage::errorMessage, nullptr);
return false;
}
if (renderEngineMode != clRenderEngineTypeFast)
{
err = kernel->setArg(
argIterator++, *backgroundImage2D); // input data in constant memory (faster than global)
if (!checkErr(err, "kernel->setArg(3, *backgroundImage2D)"))
{
emit showErrorMessage(
QObject::tr("Cannot set OpenCL argument for %2").arg(QObject::tr("background image")),
cErrorMessage::errorMessage, nullptr);
return false;
}
}
err = kernel->setArg(argIterator++, Random(1000000)); // random seed
if (!checkErr(err, "kernel->setArg(4, *inCLConstBuffer)"))
{
emit showErrorMessage(
QObject::tr("Cannot set OpenCL argument for %3").arg(QObject::tr("random seed")),
cErrorMessage::errorMessage, nullptr);
return false;
}
return true;
}
bool cOpenClEngineRenderFractal::WriteBuffersToQueue()
{
cOpenClEngine::WriteBuffersToQueue();
cl_int err = queue->enqueueWriteBuffer(*inCLBuffer, CL_TRUE, 0, inBuffer.size(), inBuffer.data());
if (!checkErr(err, "CommandQueue::enqueueWriteBuffer(inCLBuffer)"))
{
emit showErrorMessage(
QObject::tr("Cannot enqueue writing OpenCL %1").arg(QObject::tr("input buffers")),
cErrorMessage::errorMessage, nullptr);
return false;
}
err = queue->finish();
if (!checkErr(err, "CommandQueue::finish() - inCLBuffer"))
{
emit showErrorMessage(
QObject::tr("Cannot finish writing OpenCL %1").arg(QObject::tr("input buffers")),
cErrorMessage::errorMessage, nullptr);
return false;
}
err = queue->enqueueWriteBuffer(
*inCLConstBuffer, CL_TRUE, 0, sizeof(sClInConstants), constantInBuffer);
if (!checkErr(err, "CommandQueue::enqueueWriteBuffer(inCLConstBuffer)"))
{
emit showErrorMessage(
QObject::tr("Cannot enqueue writing OpenCL %1").arg(QObject::tr("constant buffers")),
cErrorMessage::errorMessage, nullptr);
return false;
}
err = queue->finish();
if (!checkErr(err, "CommandQueue::finish() - inCLConstBuffer"))
{
emit showErrorMessage(
QObject::tr("Cannot finish writing OpenCL %1").arg(QObject::tr("constant buffers")),
cErrorMessage::errorMessage, nullptr);
return false;
}
return true;
}
bool cOpenClEngineRenderFractal::ProcessQueue(
size_t jobX, size_t jobY, size_t pixelsLeftX, size_t pixelsLeftY)
{
// size_t limitedWorkgroupSize = optimalJob.workGroupSize;
// int stepSize = optimalJob.stepSize;
//
// if (optimalJob.stepSize > pixelsLeft)
// {
// int mul = pixelsLeft / optimalJob.workGroupSize;
// if (mul > 0)
// {
// stepSize = mul * optimalJob.workGroupSize;
// }
// else
// {
// // in this case will be limited workGroupSize
// stepSize = pixelsLeft;
// limitedWorkgroupSize = pixelsLeft;
// }
// }
size_t stepSizeX = optimalJob.stepSizeX;
if (pixelsLeftX < stepSizeX) stepSizeX = pixelsLeftX;
size_t stepSizeY = optimalJob.stepSizeY;
if (pixelsLeftY < stepSizeY) stepSizeY = pixelsLeftY;
// optimalJob.stepSize = stepSize;
cl_int err = queue->enqueueNDRangeKernel(
*kernel, cl::NDRange(jobX, jobY), cl::NDRange(stepSizeX, stepSizeY), cl::NullRange);
if (!checkErr(err, "CommandQueue::enqueueNDRangeKernel()"))
{
emit showErrorMessage(
QObject::tr("Cannot enqueue OpenCL rendering jobs"), cErrorMessage::errorMessage, nullptr);
return false;
}
return true;
}
bool cOpenClEngineRenderFractal::ReadBuffersFromQueue()
{
return cOpenClEngine::ReadBuffersFromQueue();
}
size_t cOpenClEngineRenderFractal::CalcNeededMemory()
{
size_t mem1 = optimalJob.sizeOfPixel * optimalJob.stepSize;
size_t mem2 = dynamicData->GetData().size();
return max(mem1, mem2);
}
bool cOpenClEngineRenderFractal::PrepareBufferForBackground(sRenderData *renderData)
{
// buffer for background image
int texWidth = renderData->textures.backgroundTexture.Width();
int texHeight = renderData->textures.backgroundTexture.Height();
if (backgroungImageBuffer) delete[] backgroungImageBuffer;
backgroungImageBuffer = new cl_uchar4[texWidth * texHeight];
size_t backgroundImage2DWidth = texWidth;
size_t backgroundImage2DHeight = texHeight;
for (int y = 0; y < texHeight; y++)
{
for (int x = 0; x < texWidth; x++)
{
sRGBA16 pixel = renderData->textures.backgroundTexture.FastPixel(x, y);
backgroungImageBuffer[x + y * texWidth].s[0] = pixel.R / 256;
backgroungImageBuffer[x + y * texWidth].s[1] = pixel.G / 256;
backgroungImageBuffer[x + y * texWidth].s[2] = pixel.B / 256;
backgroungImageBuffer[x + y * texWidth].s[3] = CL_UCHAR_MAX;
}
}
cl_int err;
if (backgroundImage2D) delete backgroundImage2D;
backgroundImage2D =
new cl::Image2D(*hardware->getContext(), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
cl::ImageFormat(CL_RGBA, CL_UNORM_INT8), backgroundImage2DWidth, backgroundImage2DHeight,
backgroundImage2DWidth * sizeof(cl_uchar4), backgroungImageBuffer, &err);
if (!checkErr(err, "cl::Image2D(...backgroundImage...)")) return false;
return true;
}
#endif
| gpl-3.0 |
Litss/PlotSquared | src/main/java/com/plotsquared/listener/ProcessedWEExtent.java | 9449 | package com.plotsquared.listener;
import java.lang.reflect.Field;
import java.util.HashSet;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.SetBlockQueue;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.Vector2D;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class ProcessedWEExtent extends AbstractDelegateExtent {
private final HashSet<RegionWrapper> mask;
int BScount = 0;
int Ecount = 0;
boolean BSblocked = false;
boolean Eblocked = false;
private final String world;
private final int max;
private int count;
private Extent parent;
public ProcessedWEExtent(final String world, final HashSet<RegionWrapper> mask, int max, final Extent child, final Extent parent) {
super(child);
this.mask = mask;
this.world = world;
if (max == -1) {
max = Integer.MAX_VALUE;
}
this.max = max;
count = 0;
this.parent = parent;
}
@Override
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException {
final int id = block.getType();
switch (id) {
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178: {
if (BSblocked) {
return false;
}
BScount++;
if (BScount > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
BSblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
} catch (final Exception e) {
e.printStackTrace();
}
parent = null;
}
return false;
}
return super.setBlock(location, block);
}
break;
}
default: {
final int x = location.getBlockX();
final int y = location.getBlockY();
final int z = location.getBlockZ();
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
} catch (final Exception e) {
e.printStackTrace();
}
parent = null;
}
return false;
}
switch (id) {
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 25:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 52:
case 54:
case 55:
case 56:
case 57:
case 58:
case 60:
case 61:
case 62:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 75:
case 76:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 117:
case 121:
case 122:
case 123:
case 124:
case 129:
case 133:
case 138:
case 137:
case 140:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 176:
case 177:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
SetBlockQueue.setBlock(world, x, y, z, id);
} else {
super.setBlock(location, block);
}
break;
}
default: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
SetBlockQueue.setBlock(world, x, y, z, new PlotBlock((short) id, (byte) block.getData()));
} else {
super.setBlock(location, block);
}
break;
}
}
return true;
// BlockManager.manager.functionSetBlock(world, x, y, z, id, data);
// return super.setBlock(location, block);
}
}
}
return false;
}
@Override
public Entity createEntity(final Location location, final BaseEntity entity) {
if (Eblocked) {
return null;
}
Ecount++;
if (Ecount > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
Eblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.createEntity(location, entity);
}
return null;
}
@Override
public boolean setBiome(final Vector2D position, final BaseBiome biome) {
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) {
return super.setBiome(position, biome);
}
return false;
}
}
| gpl-3.0 |
matalangilbert/stromohab-2008 | Software and Solutions/Visual Studio Solutions/Deprecated Solutions and Code/TightropeDiagnostics/TightropeDiagnostics/ALSoundEnvironment.cs | 1475 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ALManagedStaticClass;
using System.Windows.Forms;
using System.Threading;
namespace StromoLight_Diagnostics
{
public class ALSoundEnvironment
{
TestSubject person;
Foot left;
Foot right;
Thread update;
Thread monitor;
public ALSoundEnvironment(TestSubject person)
{
this.person = person;
left = person.Left;
right = person.Right;
ALsetup.SLsetenvironment();
//if (!ALsetup.SLsetenvironment())
//{
// MessageBox.Show("Sound is not fully functioning!");
//}
StartSound();
}
private void StartSound()
{
float pitch;
ALsetup.SLplayTone();
while (ALsetup.SLtoneupdate())
{
pitch = (float)Foot.Frontfoot.CurrentMarker.xCoordinate / 100;
ALsetup.SLchangepitch(pitch);
}
//update = new Thread(new ThreadStart(KeepPlaying));
//monitor = new Thread(new ThreadStart(Monitor));
}
private void KeepPlaying()
{
while(ALsetup.SLtoneupdate());
}
private void Monitor()
{
float pitch = (float)Foot.Frontfoot.CurrentMarker.xCoordinate/100;
ALsetup.SLchangepitch(pitch);
}
}
}
| gpl-3.0 |
GroundhogLighting/glare | premakescripts/gendaylit.lua | 495 | --add_executable(gendaylit gendaylit.c sun.c)
--target_link_libraries(gendaylit rtrad ${LIB_M})
project "gendaylit"
kind "ConsoleApp"
language "C"
defines {
"lint"
}
files {
rad_gen.."/gendaylit.c",
rad_gen.."/sun.c",
}
targetdir "../bin/%{cfg.buildcfg}"
includedirs{
third_party_dir.."/Radiance/src/**",
third_party_dir
}
links{
"rtrad",
} | gpl-3.0 |
iDigBio/idb-backend | scripts/rss-feed-dump-for-humans.py | 2451 | from __future__ import print_function
import feedparser
from pyquery import PyQuery as pq
import argparse
argparser = argparse.ArgumentParser(description='Script to quickly dump dataset information out of an RSS feed in human-readable format.')
argparser.add_argument("-f", "--feed", required=True, help="The filename or URL of the RSS feed to parse.")
args = argparser.parse_args()
feed_to_parse = args.feed
if not feed_to_parse.startswith('http'):
print ()
print ("* non-HTTP feed supplied, assuming local file. *")
feed = feedparser.parse(feed_to_parse)
def get_title(entry):
if "title" in entry:
return(entry["title"])
else:
return("NO TITLE FOUND")
def get_pubDate(entry):
if "published" in entry:
return (entry["published"])
else:
return ("NO PUBLISHED DATE FOUND")
def get_id(entry):
if "id" in entry:
return (entry["id"])
else:
return ("NO ID FOUND")
def get_dataset_link(entry):
if "ipt_dwca" in entry:
return (entry["ipt_dwca"])
elif "link" in entry:
return (entry["link"])
else:
return ("NO DATASET LINK FOUND")
def get_eml_link(entry):
if "ipt_eml" in entry:
return (entry["ipt_eml"])
elif "emllink" in entry:
return (entry["emllink"])
else:
return ("NO EML LINK FOUND")
hr = "=============================================================================================="
print ()
print (hr)
print (feed_to_parse)
if "title" in feed['feed']:
print (feed['feed']['title'])
else:
print ("Feed has no TITLE.")
print (hr)
for entry in feed.entries:
entry_title = ""
entry_pubDate = ""
entry_id = ""
entry_dataset_link = ""
entry_eml_link = ""
# feedparser converts many common fields into normalized names. Examples:
# guid --> id
# pubDate --> published
#
# Fields that contain colons such as ipt:dwca and ipt:eml get underscored to ipt_dwca and ipt_eml
#
# The actual IPT guid field is not visible as a normalized field since another id field is used.
# However, the id is embedded in the middle of the id url so human can pluck it out if needed.
print ("title: ", get_title(entry))
print ("published: ", get_pubDate(entry))
print ("id: ", get_id(entry))
print ("dataset link: ", get_dataset_link(entry))
print ("eml link: ", get_eml_link(entry))
print (hr)
| gpl-3.0 |
dicebox/minetest-france | minetest/src/nodemetadata.cpp | 4654 | /*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <[email protected]>
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 2.1 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.
*/
#include "nodemetadata.h"
#include "exceptions.h"
#include "gamedef.h"
#include "inventory.h"
#include "log.h"
#include "util/serialize.h"
#include "constants.h" // MAP_BLOCKSIZE
#include <sstream>
/*
NodeMetadata
*/
NodeMetadata::NodeMetadata(IItemDefManager *item_def_mgr):
m_inventory(new Inventory(item_def_mgr))
{}
NodeMetadata::~NodeMetadata()
{
delete m_inventory;
}
void NodeMetadata::serialize(std::ostream &os) const
{
int num_vars = m_stringvars.size();
writeU32(os, num_vars);
for (StringMap::const_iterator
it = m_stringvars.begin();
it != m_stringvars.end(); ++it) {
os << serializeString(it->first);
os << serializeLongString(it->second);
}
m_inventory->serialize(os);
}
void NodeMetadata::deSerialize(std::istream &is)
{
m_stringvars.clear();
int num_vars = readU32(is);
for(int i=0; i<num_vars; i++){
std::string name = deSerializeString(is);
std::string var = deSerializeLongString(is);
m_stringvars[name] = var;
}
m_inventory->deSerialize(is);
}
void NodeMetadata::clear()
{
Metadata::clear();
m_inventory->clear();
}
bool NodeMetadata::empty() const
{
return Metadata::empty() && m_inventory->getLists().size() == 0;
}
/*
NodeMetadataList
*/
void NodeMetadataList::serialize(std::ostream &os) const
{
/*
Version 0 is a placeholder for "nothing to see here; go away."
*/
u16 count = countNonEmpty();
if (count == 0) {
writeU8(os, 0); // version
return;
}
writeU8(os, 1); // version
writeU16(os, count);
for(std::map<v3s16, NodeMetadata*>::const_iterator
i = m_data.begin();
i != m_data.end(); ++i)
{
v3s16 p = i->first;
NodeMetadata *data = i->second;
if (data->empty())
continue;
u16 p16 = p.Z * MAP_BLOCKSIZE * MAP_BLOCKSIZE + p.Y * MAP_BLOCKSIZE + p.X;
writeU16(os, p16);
data->serialize(os);
}
}
void NodeMetadataList::deSerialize(std::istream &is, IItemDefManager *item_def_mgr)
{
clear();
u8 version = readU8(is);
if (version == 0) {
// Nothing
return;
}
if (version != 1) {
std::string err_str = std::string(FUNCTION_NAME)
+ ": version " + itos(version) + " not supported";
infostream << err_str << std::endl;
throw SerializationError(err_str);
}
u16 count = readU16(is);
for (u16 i=0; i < count; i++) {
u16 p16 = readU16(is);
v3s16 p;
p.Z = p16 / MAP_BLOCKSIZE / MAP_BLOCKSIZE;
p16 &= MAP_BLOCKSIZE * MAP_BLOCKSIZE - 1;
p.Y = p16 / MAP_BLOCKSIZE;
p16 &= MAP_BLOCKSIZE - 1;
p.X = p16;
if (m_data.find(p) != m_data.end()) {
warningstream<<"NodeMetadataList::deSerialize(): "
<<"already set data at position"
<<"("<<p.X<<","<<p.Y<<","<<p.Z<<"): Ignoring."
<<std::endl;
continue;
}
NodeMetadata *data = new NodeMetadata(item_def_mgr);
data->deSerialize(is);
m_data[p] = data;
}
}
NodeMetadataList::~NodeMetadataList()
{
clear();
}
std::vector<v3s16> NodeMetadataList::getAllKeys()
{
std::vector<v3s16> keys;
std::map<v3s16, NodeMetadata *>::const_iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it)
keys.push_back(it->first);
return keys;
}
NodeMetadata *NodeMetadataList::get(v3s16 p)
{
std::map<v3s16, NodeMetadata *>::const_iterator n = m_data.find(p);
if (n == m_data.end())
return NULL;
return n->second;
}
void NodeMetadataList::remove(v3s16 p)
{
NodeMetadata *olddata = get(p);
if (olddata) {
delete olddata;
m_data.erase(p);
}
}
void NodeMetadataList::set(v3s16 p, NodeMetadata *d)
{
remove(p);
m_data.insert(std::make_pair(p, d));
}
void NodeMetadataList::clear()
{
std::map<v3s16, NodeMetadata*>::iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it) {
delete it->second;
}
m_data.clear();
}
int NodeMetadataList::countNonEmpty() const
{
int n = 0;
std::map<v3s16, NodeMetadata*>::const_iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it) {
if (!it->second->empty())
n++;
}
return n;
}
| gpl-3.0 |
CroceRossaItaliana/jorvik | ufficio_soci/migrations/0010_issue_194_pregresso.py | 1722 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, date
from django.db import migrations, models
from django.db.models import Q
def forward_func(apps, schema_editor):
Appartenenza = apps.get_model("anagrafica", "Appartenenza")
inizio = fine = datetime.now()
# Trova tutte le appartenenze doppie
apps = Appartenenza.objects.filter(
Q(inizio__lte=inizio),
Q(Q(fine__isnull=True) | Q(fine__gt=fine)),
confermata=True,
membro='OR',
persona_id__in=Appartenenza.objects.filter(
Q(inizio__lte=inizio),
Q(Q(fine__isnull=True) | Q(fine__gt=fine)),
confermata=True,
membro__in=('VO', 'SO', 'DI'),
).values_list('persona_id', flat=True)
)
problemi = 0
for app in apps: # Per ogni appartenenza ordinaria ancora attiva
# Trova la nuova appartenenza (reclamata)
app_nuova = Appartenenza.objects.filter(
Q(inizio__lte=inizio),
Q(Q(fine__isnull=True) | Q(fine__gt=fine)),
confermata=True,
persona=app.persona,
membro__in=('VO', 'SO', 'DI'),
).order_by('-inizio').first()
if app_nuova.inizio < app.inizio: # Data sballata.
app_nuova.inizio = datetime(2015, 1, 1)
app_nuova.save()
app.fine = app_nuova.inizio
app.save()
else: # Solo da chiudere la vecchia.
app.fine = app_nuova.inizio
app.save()
class Migration(migrations.Migration):
dependencies = [
('ufficio_soci', '0009_auto_20160224_1447'),
]
operations = [
migrations.RunPython(forward_func)
]
| gpl-3.0 |
wisend/ti.mba | app/forms/quotes/ItemForm.php | 4773 | <?php
namespace App\Forms\Quotes;
// Use form elements
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Numeric;
use Phalcon\Forms\Element\Select;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Submit;
// Use Models relating to items
use App\Models\Grade;
use App\Models\Treatment;
use App\Models\Finish;
use App\Models\Dryness;
use App\Models\PricingUnit;
use App\Models\QuoteCodes;
class ItemForm extends Form
{
// Initialize the form
public function initialize()
{
// Hidden ID to be used when editing items
$id = new Hidden("id");
$this->add($id);
$quoteId = new Hidden("quoteId");
$this->add($quoteId);
$grade = new Select(
'grade[]',
Grade::find(array('conditions' => 'active = 1', 'order' => 'name ASC')),
array(
'using' => array('shortCode', 'name'),
'useEmpty' => true,
'emptyText' => 'Grade',
'class' => 'data grade no-selectize data',
'data-live-search' => 'true',
'data-container' => 'body',
)
);
$this->add($grade);
// Numeric value for width
$width = new Numeric('width[]');
$width->setLabel('Width');
$width->setAttributes(array(
"class" => "form-control",
"step" => "1",
"placeholder" => "Width",
));
$this->add($width);
// Numeric value for thickness
$thickness = new Numeric('thickness[]');
$thickness->setLabel("Thickness");
$thickness->setAttributes(array(
"class" => "data",
"step" => "1",
"placeholder" => "Thickness",
));
$this->add($thickness);
// Numeric value for quantity
$qty = new Numeric('qty[]');
$qty->setLabel("Qty");
$qty->setAttributes(array(
"class" => "form-control",
"step" => "1",
"placeholder" => "Qty",
));
$this->add($qty);
// Select list containing all usable treatments
$treatment = new Select(
'treatment[]',
Treatment::find(),
array(
'using' => array('shortCode', 'shortCode'),
'useEmpty' => true,
'class' => 'data treatment no-selectize data',
'data-container' => 'body',
'emptyText' => 'Treat...',
'data-live-search' => 'true',
)
);
$treatment->setLabel("Treatment");
$this->add($treatment);
// Select list containing all usable drynesses
$dryness = new Select(
'dryness[]',
Dryness::find(),
array(
'using' => array('shortCode', 'shortCode'),
'useEmpty' => true,
'class' => 'data dryness no-selectize data',
'data-container' => 'body',
'emptyText' => 'Dry...',
'data-live-search' => 'true',
)
);
$dryness->setLabel("Dryness");
$this->add($dryness);
// Select list containing all usable finishes
$finish = new Select(
'finish[]',
Finish::find(),
array(
'using' => array('id', 'name'),
'useEmpty' => true,
'class' => 'form-control no-selectize data',
'data-container' => 'body',
'emptyText' => 'Finish',
'data-live-search' => 'true',
'data-show-subtext' => 'true',
)
);
$finish->setLabel("Finish");
$this->add($finish);
// Simple numeric value for price
$price = new Numeric('price[]');
$price ->setLabel("Price")
->setAttributes(
array(
"class" => "form-control",
"step" => "any",
"placeholder" => "Price",
)
);
$this->add($price);
$priceMethod = new Select(
'priceMethod[]',
PricingUnit::find(),
array(
'using' => array('id', 'name'),
'useEmpty' => false,
'class' => 'form-control no-selectize data',
)
);
$this->add($priceMethod);
$priceMethod = new Select('priceMethod');
$notes = new Text('lengths[]');
$notes->setAttributes(
array(
'class' => 'form-control no-selectize data',
'placeholder' => 'Notes',
)
);
$this->add($notes);
}
}
| gpl-3.0 |
rays/PopCurrent | app/controllers/permission_controller.rb | 2381 | #***************************************************************
# Filename: permission_controller.rb
# Authors: Sean Jackson, Ray Slakinski
# Created: April 2006
#
# Actions to manage Users
#
# Copyright 2006 PopCurrent.com. All rights reserved.
#***************************************************************
class PermissionController < ApplicationController
layout "standard_adside"
# We shouldn't accept GET requests that modify data.
verify :method => :post, :only => %w(destroy)
def index
redirect_to :action => "list"
end
def list
@content_columns = Permission.content_columns
@permission_pages, @permissions = paginate :permission, :order => 'id', :per_page => 15
end
def show
if (@permission = find_permission(params[:id]))
@content_columns = Permission.content_columns
else
redirect_back_or_default :action => 'list'
end
end
def new
case request.method
when :get
@permission = Permission.new
when :post
@permission = Permission.new(@params[:permission])
if @permission.save
flash[:notice] = 'Permission was successfully created.'
redirect_to :action => 'list'
else
render_action 'new'
end
end
end
def edit
case request.method
when :get
if (@permission = find_permission(params[:id])).nil?
redirect_back_or_default :action => 'list'
end
when :post
if (@permission = find_permission(params[:id]))
if @permission.update_attributes(@params[:permission])
flash[:notice] = 'Permission was successfully updated.'
redirect_to :action => 'show', :id => @permission
else
render_action 'edit'
end
else
redirect_back_or_default :action => 'list'
end
end
end
def destroy
if (@permission = find_permission(params[:id]))
@permission.destroy
flash[:notice] = "Permission '#{@permission.path}' deleted."
redirect_to :action => 'list'
else
redirect_back_or_default :action => 'list'
end
end
protected
def find_permission(id)
begin
Permission.find(id)
rescue
flash[:message] = "There is no permission with ID ##{id}"
nil
end
end
end
| gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.