repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
mach0/polystrip | poly_strip_dialog.py | 2465 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
PolyStripDialog
A QGIS plugin
Polygons along lines
-------------------
begin : 2017-07-29
git sha : $Format:%H$
copyright : (C) 2017 by Werner Macho
email : werner.macho@gmail.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
from qgis.PyQt import (
uic
)
from qgis.PyQt.QtWidgets import (
QDialog
)
from qgis.gui import (
QgsProjectionSelectionTreeWidget
)
from .poly_strip_alg import get_all_pages
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'poly_strip_dialog_base.ui'))
class PolyStripDialog(QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(PolyStripDialog, self).__init__(parent)
self.setupUi(self)
def polystrip(self, layer):
if self.crsBoxSelect.isChecked():
srid = PolyStripDialog().crsselectauto(layer)
else:
srid = PolyStripDialog().crsselect
width = self.widthSpinBox.value()
height = self.heightSpinBox.value()
coverage = self.coverSpinBox.value()
covstart = self.coverSpinBoxStart.value()
get_all_pages(layer, width, height, srid, coverage, covstart)
def labelwriter(self, unitstr):
unit = unitstr
self.label_unit.setText(unit)
@staticmethod
def crsselect():
proj_selector = QgsProjectionSelectionTreeWidget()
proj_selector.exec_()
srid = proj_selector.crs()
return srid
@staticmethod
def crsselectauto(layer):
srid = layer.crs().authid()
return srid
| gpl-3.0 |
wangwl/SOAPgaeaDevelopment4.0 | src/main/java/org/bgi/flexlab/gaea/data/mapreduce/input/bam/GaeaAnySAMInputFormat.java | 6701 | /*******************************************************************************
* Copyright (c) 2017, BGI-Shenzhen
*
* 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/>
*
* This file incorporates work covered by the following copyright and
* Permission notices:
*
* Copyright (c) 2010 Aalto University
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package org.bgi.flexlab.gaea.data.mapreduce.input.bam;
import hbparquet.hadoop.util.ContextUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.bgi.flexlab.gaea.data.mapreduce.input.sam.GaeaSamInputFormat;
import org.bgi.flexlab.gaea.data.mapreduce.writable.SamRecordWritable;
import org.seqdoop.hadoop_bam.FileVirtualSplit;
import org.seqdoop.hadoop_bam.SAMFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GaeaAnySAMInputFormat extends
FileInputFormat<LongWritable, SamRecordWritable> {
public static final String TRUST_EXTS_PROPERTY = "hadoopbam.anysam.trust-exts";
public static final String SAM_FORMAT_FOR_ALL_PATH = "samformat.allpath";
private final GaeaBamInputFormat bamIF = new GaeaBamInputFormat();
private final GaeaSamInputFormat samIF = new GaeaSamInputFormat();
private final Map<Path, SAMFormat> formatMap;
private Configuration conf;
private boolean trustExts;
public GaeaAnySAMInputFormat() {
this.formatMap = new HashMap<Path, SAMFormat>();
this.conf = null;
}
public GaeaAnySAMInputFormat(Configuration conf) {
this.formatMap = new HashMap<Path, SAMFormat>();
this.conf = conf;
this.trustExts = conf.getBoolean(TRUST_EXTS_PROPERTY, true);
}
public SAMFormat getFormat(final Path path) {
SAMFormat fmt = formatMap.get(path);
if (fmt != null || formatMap.containsKey(path))
return fmt;
if (this.conf == null)
throw new IllegalStateException("Don't have a Configuration yet");
if(conf.get(SAM_FORMAT_FOR_ALL_PATH) != null){
String format = conf.get(SAM_FORMAT_FOR_ALL_PATH);
if(format.equals("BAM") || format.equals("bam"))
fmt = SAMFormat.BAM;
else
fmt = SAMFormat.SAM;
formatMap.put(path, fmt);
return fmt;
}
if (trustExts) {
final SAMFormat f = SAMFormat.inferFromFilePath(path);
if (f != null) {
formatMap.put(path, f);
return f;
}
}
try {
fmt = SAMFormat.inferFromData(path.getFileSystem(conf).open(path));
} catch (IOException e) {
}
formatMap.put(path, fmt);
return fmt;
}
@Override
public RecordReader<LongWritable, SamRecordWritable> createRecordReader(
InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException {
final Path path;
if (split instanceof FileSplit)
path = ((FileSplit) split).getPath();
else if (split instanceof FileVirtualSplit)
path = ((FileVirtualSplit) split).getPath();
else
throw new IllegalArgumentException("split '" + split
+ "' has unknown type: cannot extract path");
if (this.conf == null)
this.conf = ContextUtil.getConfiguration(ctx);
final SAMFormat fmt = getFormat(path);
if (fmt == null)
throw new IllegalArgumentException(
"unknown SAM format, cannot create RecordReader: " + path);
switch (fmt) {
case SAM:
return samIF.createRecordReader(split, ctx);
case BAM:
return bamIF.createRecordReader(split, ctx);
default:
assert false;
return null;
}
}
@Override
public boolean isSplitable(JobContext job, Path path) {
if (this.conf == null)
this.conf = ContextUtil.getConfiguration(job);
final SAMFormat fmt = getFormat(path);
if (fmt == null)
return super.isSplitable(job, path);
switch (fmt) {
case SAM:
return samIF.isSplitable(job, path);
case BAM:
return bamIF.isSplitable(job, path);
default:
assert false;
return false;
}
}
@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
if (this.conf == null)
this.conf = ContextUtil.getConfiguration(job);
final List<InputSplit> origSplits = super.getSplits(job);
final List<InputSplit> bamOrigSplits = new ArrayList<InputSplit>(
origSplits.size()), newSplits = new ArrayList<InputSplit>(
origSplits.size());
for (final InputSplit iSplit : origSplits) {
final FileSplit split = (FileSplit) iSplit;
if (SAMFormat.BAM.equals(getFormat(split.getPath())))
bamOrigSplits.add(split);
else
newSplits.add(split);
}
newSplits.addAll(bamIF.getSplits(bamOrigSplits,
ContextUtil.getConfiguration(job)));
return newSplits;
}
}
| gpl-3.0 |
probedock/probedock | client/initializers/gravatar.js | 241 | angular.module('probedock').config(function(gravatarServiceProvider) {
gravatarServiceProvider.defaults = {
// Use auto-generated identicons (based on the e-mail) for users not registered on gravatar
default: 'identicon'
};
});
| gpl-3.0 |
haxelion/ObjectIdentifier | mainwindow.cpp | 3379 | /*
This file is part of ObjectIdentifier.
ObjectIdentifier 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.
Nagen 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/>.
Copyright 2014 Charles Hubain <charles.hubain@haxelion.eu>
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->actionOpen,&QAction::triggered, this, &MainWindow::open);
connect(ui->actionSave, &QAction::triggered, this, &MainWindow::save);
connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
connect(&processing_thread, &ProcessingThread::finished, this, &MainWindow::refreshDisplay);
connect(ui->stage_selector, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), &processing_thread, &ProcessingThread::setOutputState);
connect(ui->hmin_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setHMin);
connect(ui->hmax_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setHMax);
connect(ui->smin_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setSMin);
connect(ui->smax_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setSMax);
connect(ui->threshold1_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setThreshold1);
connect(ui->threshold2_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setThreshold2);
connect(ui->minarea_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setMinArea);
connect(ui->epsilon_input, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), &processing_thread, &ProcessingThread::setEpsilon);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::open()
{
if(processing_thread.isRunning() == false)
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "", tr("Image Files (*.png *.jpg *jpeg *.bmp)"));
processing_thread.setInput(&fileName);
processing_thread.start();
}
}
void MainWindow::save()
{
}
void MainWindow::refreshDisplay()
{
QImage *output = processing_thread.getOutput();
if(output != NULL)
{
QPixmap pixmap = QPixmap::fromImage(output->scaled(ui->display->size(), Qt::KeepAspectRatio));
ui->display->setPixmap(pixmap);
}
}
void MainWindow::paintEvent(QPaintEvent *e)
{
if(previous_size != ui->display->size())
{
previous_size = ui->display->size();
refreshDisplay();
}
QMainWindow::paintEvent(e);
}
| gpl-3.0 |
howshea/Gank.io | app/src/main/java/com/howshea/gankio/net/ApiService.java | 655 | package com.howshea.gankio.net;
import com.howshea.gankio.entity.GankList;
import com.howshea.gankio.entity.History;
import com.howshea.gankio.entity.MeiziList;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
/**
* Created by haipo on 2016/10/13.
*/
public interface ApiService {
@GET("data/福利/{count}/{page}")
Observable<MeiziList> getMeizi(@Path("count") int count, @Path("page") int page);
@GET("data/{type}/{count}/{page}")
Observable<GankList> getGank(@Path("type") String type, @Path("count") int count, @Path("page") int page);
@GET("day/history")
Observable<History> getDate();
}
| gpl-3.0 |
oslocyclotronlab/Qkinz | src/kinematics/src/BetheBlockComp.cpp | 3419 | #include "BetheBlockComp.h"
#include "BetheBlock.h"
#include "Particle.h"
#include "Material.h"
#ifndef BETHEBLOCKCONST
#define BETHEBLOCKCONST 0.1535 // MeVcm^2/g
#endif
#ifndef MASSELECTRON
#define MASSELECTRON 0.511 // MeV/c^2
#endif
BetheBlockComp::BetheBlockComp(){}
BetheBlockComp::BetheBlockComp(Material *material, double *weights, const int &n_mat, Particle *beam)
{
elements.reset(new BetheBlock[n_mat]);
weight.reset(new double[n_mat]);
projectile.reset(new Particle(*beam));
nbr_el = n_mat;
Zeff = 0;
Aeff = 0;
Ieff = 0;
for (int i = 0 ; i < n_mat ; ++i){
Zeff += material[i].GetZ()*weights[i];
Aeff += material[i].GetA()*weights[i];
Ieff += log(material[i].GetMeanEx())*weights[i]*material[i].GetZ();
weight[i] = weights[i];
elements[i] = BetheBlock(new Material(*(material+i)), new Particle(*beam));
}
Ieff /= Zeff;
Ieff = exp(Ieff);
densCorrSet = false;
}
BetheBlockComp::~BetheBlockComp()
{
if (elements)
elements.reset();
if (weight)
weight.reset();
if (projectile)
projectile.reset();
}
BetheBlockComp &BetheBlockComp::operator=(const BetheBlockComp &bbc)
{
this->elements.reset(new BetheBlock[bbc.nbr_el]);
this->weight.reset(new double[bbc.nbr_el]);
this->nbr_el = bbc.nbr_el;
this->projectile.reset(new Particle(*(bbc.projectile)));
for (int i = 0 ; i < this->nbr_el ; ++i){
this->elements[i] = bbc.elements[i];
this->weight[i] = bbc.weight[i];
}
return *this;
}
double BetheBlockComp::Evaluate(const double &E) const
{
double Erel = E + projectile->GetM_MeV();
double prel = sqrt(pow(Erel, 2) - pow(projectile->GetM_MeV(), 2));
double beta = prel/Erel;
double gamma = 1./sqrt(1 - beta*beta);
double result = 2*log(2*MASSELECTRON*pow(beta*gamma, 2)/Ieff);
result -= log(pow(MASSELECTRON/projectile->GetM_MeV(), 2) + 2*gamma*MASSELECTRON/projectile->GetM_MeV() + 1);
result -= 2*beta*beta;
if (densCorrSet)
result -= CalcDensCorr(log10(beta*gamma));
result *= BETHEBLOCKCONST*Zeff*pow(projectile->GetZ(),2)/(Aeff*pow(beta,2));
return -result;
}
/*
double BetheBlockComp::Evaluate(const double &E) const
{
double result = 0;
for (int i = 0 ; i < nbr_el ; ++i){
result += weight[i]*elements[i](E);
}
return result;
}
*/
double BetheBlockComp::Loss(const double &E, const double &width, const int &points)
{
double dx = width/(points - 1);
double e = E;
double R1, R2, R3, R4;
for (int i = 0 ; i < points ; ++i){
R1 = dx*Evaluate(e);
R2 = dx*Evaluate(e + 0.5*R1);
R3 = dx*Evaluate(e + 0.5*R2);
R4 = dx*Evaluate(e + R3);
e += (R1 + 2*(R2*R3) + R4)/6.;
if (e < 0) return 0;
}
return e;
}
void BetheBlockComp::setDensityCorrections(BetheBlock::DensityCorr densCor){ densCorr = densCor; densCorrSet = true; }
double BetheBlockComp::CalcDensCorr(double X) const
{
if (!densCorrSet)
return 0;
else if (X < densCorr.X0)
return 0;
else if (X < densCorr.X1)
return 4.6052*X + densCorr.C0 + densCorr.a*pow(densCorr.X1 - X, densCorr.m);
else
return 4.6052*X + densCorr.C0;
}
/*
void BetheBlockComp::setDensityCorrections(BetheBlock::DensityCorr *densCorr)
{
BetheBlock::DensityCorr tmp;
for (int i = 0 ; i < nbr_el ; ++i){
tmp = densCorr[i];
elements[i].setDensityCorr(tmp);
}
}
*/
| gpl-3.0 |
asine/exchangecalendar | addressbook/content/exchangeContactSettings.js | 4792 | /* ***** BEGIN LICENSE BLOCK *****
* Version: GPL 3.0
*
* The contents of this file are subject to the General Public License
* 3.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* -- Exchange 2007/2010 Contacts.
* -- For Thunderbird.
*
* Author: Michel Verbraak (info@1st-setup.nl)
* Website: http://www.1st-setup.nl/wordpress/?page_id=xx
* email: exchangecontacts@extensions.1st-setup.nl
*
*
* ***** BEGIN LICENSE BLOCK *****/
"use strict";
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
function exchExchangeContactSettings(aDocument, aWindow) {
this._document = aDocument;
this._window = aWindow;
this.globalFunctions = Cc["@1st-setup.nl/global/functions;1"]
.getService(Ci.mivFunctions);
}
exchExchangeContactSettings.prototype = {
isNewDirectory: true,
dirUUID: "",
checkRequired: function _checkRequired() {
let canAdvance = true;
let vbox = this._document.getElementById('exchWebService-exchange-settings');
if (vbox) {
let eList = vbox.getElementsByAttribute('required', 'true');
for (let i = 0; i < eList.length && canAdvance; ++i) {
canAdvance = (eList[i].value != "");
}
if (canAdvance) {
this._document.getElementById("exchWebService_ContactSettings_dialog").buttons = "accept,cancel";
}
else {
this._document.getElementById("exchWebService_ContactSettings_dialog").buttons = "cancel";
}
}
},
onLoad: function _onLoad() {
var directory = this._window.arguments[0].selectedDirectory;
if (!directory) {
// New directory to create
this.isNewDirectory = true;
this.dirUUID = "";
this._document.getElementById("exchWebService_folderbase").selectedIndex = 7;
tmpSettingsOverlay.exchWebServicesgFolderBase = "contacts";
this._document.getElementById("exchangeWebService_preference_contacts_pollinterval").value = 300;
this._document.getElementById("exchWebService-add-globaladdresslist").checked = false;
}
else {
this.isNewDirectory = false;
this.dirUUID = directory.uuid;
this.prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch("extensions.exchangecontacts@extensions.1st-setup.nl.account." + this.dirUUID + ".");
this._document.getElementById("exchangeWebService_preference_contacts_pollinterval").value = this.globalFunctions.safeGetIntPref(this.prefs, "pollinterval", 300, true);
this._document.getElementById("exchWebService-add-globaladdresslist").checked = this.globalFunctions.safeGetBoolPref(this.prefs, "globalAddressList", false, true);
// load preferences of current directory.
tmpSettingsOverlay.exchWebServicesLoadExchangeSettingsByContactUUID(directory.uuid);
}
},
onSave: function _onSave() {
this._window.arguments[0].newAccountObject = tmpSettingsOverlay.exchWebServicesSaveExchangeSettingsByContactUUID(this.isNewDirectory, this.dirUUID);
this._window.arguments[0].newAccountObject.pollinterval = this._document.getElementById("exchangeWebService_preference_contacts_pollinterval").value;
this._window.arguments[0].newAccountObject.addGlobalAddressList = this._document.getElementById("exchWebService-add-globaladdresslist").checked;
this._window.arguments[0].answer = "saved";
if (!this.isNewDirectory) {
this.prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch("extensions.exchangecontacts@extensions.1st-setup.nl.account." + this.dirUUID + ".");
this.prefs.setIntPref("pollinterval", this._window.arguments[0].newAccountObject.pollinterval);
this.prefs.setBoolPref("globalAddressList", this._window.arguments[0].newAccountObject.addGlobalAddressList);
var observerService = Cc["@mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.notifyObservers(this, "onContactReset", this.dirUUID);
}
return true;
},
}
var tmpExchangeContactSettings = new exchExchangeContactSettings(document, window);
| gpl-3.0 |
roma/roma-java-client | java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/MapcountCommandID.java | 518 | package jp.co.rakuten.rit.roma.client.util.commands;
import jp.co.rakuten.rit.roma.client.commands.CommandID;
/**
*
*/
public interface MapcountCommandID extends CommandID {
// storage command
int MAPCOUNT_GET = 150;
int MAPCOUNT_COUNTUP = 151;
int MAPCOUNT_UPDATE = 152;
String STR_MAPCOUNT_GET = "mapcount_get";
String STR_MAPCOUNT_COUNTUP = "mapcount_countup";
String STR_MAPCOUNT_UPDATE = "mapcount_update";
String STR_MAPCOUNT_FLAG = "0";
}
| gpl-3.0 |
CCIP-App/CCIP-Puzzle-Bueno | src/modal/util.js | 780 | import crypto from 'crypto'
export default {
parseQueryParams (query) {
return query.split('?').pop().split('&')
.map((query) => {
var keyValue = query.split('=')
return {
key: keyValue.shift(),
value: keyValue.pop()
}
})
.reduce((collection, param) => {
collection[param.key] = param.value
return collection
}, {})
},
sha1Gen (raw) {
var hashGen = crypto.createHash('sha1')
hashGen.update(raw)
return hashGen.digest('hex')
},
StringFormat () {
let formatString = arguments[0]
let args = Array.prototype.slice.call(arguments).slice(1)
return args.reduce(
(formatString, arg, i) => formatString.replace('${' + (i + 1) + '}', arg), formatString)
}
}
| gpl-3.0 |
egovernments/egov-playground | eGov/egov/egov-pgr/src/main/java/org/egov/pgr/repository/ComplaintTypeRepository.java | 2890 | /*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) <2015> eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* 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/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org.
*/
package org.egov.pgr.repository;
import org.egov.infra.admin.master.entity.Department;
import org.egov.pgr.entity.ComplaintType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ComplaintTypeRepository extends JpaRepository<ComplaintType, Long> {
ComplaintType findByName(String name);
List<ComplaintType> findByIsActiveTrueAndNameContainingIgnoreCase(String name);
List<ComplaintType> findByIsActiveTrueAndCategoryIdOrderByNameAsc(Long categoryId);
ComplaintType findByCode(String code);
@Query("select distinct ct.department from ComplaintType ct order by ct.department.name asc")
List<Department> findAllComplaintTypeDepartments();
List<ComplaintType> findByIsActiveTrueOrderByNameAsc();
List<ComplaintType> findByNameContainingIgnoreCase(String name);
}
| gpl-3.0 |
erikacamilleri/bumsccavefinal2016-ppnp | PPNP 1.0.0/src/utils/Logger.cpp | 847 | #include <utils/Logger.h>
#include <QtCore/QString>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <ctime>
Logger* Logger::s_instance = nullptr;
std::string Logger::s_filename = "";
Logger* Logger::instance()
{
if(s_instance == nullptr)
{
s_instance = new Logger;
std::time_t result = std::time(nullptr);
std::string timestamp = std::asctime(std::localtime(&result));
Logger::s_filename = "debug_log/log_" + timestamp + ".txt";
}
return s_instance;
}
void Logger::log(const std::string &_logMessage)
{
QString outputFilename = QString::fromUtf8(Logger::s_filename.c_str());
QFile outputFile(outputFilename);
outputFile.open(QIODevice::Append);
if(outputFile.isOpen())
{
QTextStream outStream(&outputFile);
outStream << QString::fromStdString(_logMessage);
}
outputFile.close();
}
| gpl-3.0 |
Akogen/Module | Controller/Adminhtml/Akogenlist/Index.php | 1937 | <?php
/**
* AKogen
*
* NOTICE OF LICENSE
*
* This source file is subject to the AKogen.com license that is
* available through the world-wide-web at this URL:
* http://www.AKogen.com/license-agreement.html
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category AKogen
* @package Akogen_Module
* @copyright Copyright (c) 2017 AKogen (http://www.AKogen.com/)
* @license http://www.AKogen.com/license-agreement.html
*/
namespace Akogen\Module\Controller\Adminhtml\Akogenlist;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action as BackendAction;
/**
* Module Index action.
* @category AKogen
* @package Akogen_Module
* @module Module
* @author AKogen Developer
*/
class Index extends BackendAction
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
/**
* Check the permission to run it
*
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(
'Akogen_Module::akogenlist');
}
/**
* Index action
*
* @return \Magento\Backend\Model\View\Result\Page
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('Akogen_Module::akogenlist');
$resultPage->addBreadcrumb(__('CMS'), __('CMS'));
$resultPage->addBreadcrumb(__('AKogen List'), __('Aogen List'));
$resultPage->getConfig()->getTitle()->prepend(__('Akogen List'));
return $resultPage;
}
}
| gpl-3.0 |
lyssym/access | schedule/producer/produce.py | 1465 | # _*_ coding: utf-8 _*_
import time
from apscheduler.schedulers.background import BackgroundScheduler
from control.mysql import KeyWordsClient
from control.msg_queue import CommonServer
from control.rabbit_producer import ProduceService
from util.config import USR_BASE, KW_TABLE, BACKUP_TABLE, GOOGLE, BAIDU, BING, PUBMED
from util.info import UserData, BaiDuData, BingData, PubMedData
def get_db(database, table):
keyword_db = KeyWordsClient(database, table)
ret = keyword_db.fetch_valid_data()
if not ret:
keywords = []
for r in ret:
keywords.append(r[2].strip())
return keywords
return None
def schedule(database, table):
keywords = get_db(database, table)
if keywords:
for key in keywords:
data = UserData([key])
producer = ProduceService(GOOGLE)
producer.produce(data.set_request())
producer = CommonServer(USR_BASE, BACKUP_TABLE)
producer.produce(key)
data = BaiDuData([key])
producer = ProduceService(BAIDU)
producer.produce(data.set_request())
data = BingData([key])
producer = ProduceService(BING)
producer.produce(data.set_request())
time.sleep(20)
if __name__ == '__main__':
schedule = BackgroundScheduler()
schedule.add_job(func=schedule, args=(USR_BASE, KW_TABLE, ), trigger='interval', hours=12)
schedule.start()
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimation.java | 989 | package com.badlogic.gdx.graphics.g3d.keyframed;
import com.badlogic.gdx.graphics.g3d.Animation;
public class KeyframeAnimation extends Animation
{
public Keyframe[] keyframes;
public float length;
public String name;
public int refs;
public float sampleRate;
public KeyframeAnimation(String paramString, int paramInt, float paramFloat1, float paramFloat2)
{
this.name = paramString;
this.keyframes = new Keyframe[paramInt];
this.length = paramFloat1;
this.sampleRate = paramFloat2;
this.refs = 1;
}
public void addRef()
{
this.refs = (1 + this.refs);
}
public float getLength()
{
return this.length;
}
public int getNumFrames()
{
return this.keyframes.length;
}
public int removeRef()
{
int i = -1 + this.refs;
this.refs = i;
return i;
}
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.badlogic.gdx.graphics.g3d.keyframed.KeyframeAnimation
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
jhacks/viox | src/gdk/syslinux.gdk.cpp | 441 | //syslinux.gdk.cpp
/*VIOX64
Virtual Bios Hypervisor 4 AMD64 Fam10+ (&ia64) 2 free & happy GPL3 hacking.
Author: jhacks hack hersteller jhackher@gmail.com
This program is released under the GNU GPL license v3 or later version, WHITHOUT ANY WARRANTY.
A copy of the license should be found in jhacks.LICENSE.txt and/or COPYING.txt file.
In any case latest version is in http://www.gnu.org/licenses/gpl.html
*/
#include syslinux.gdk.hpp
//TODO
| gpl-3.0 |
pholda/MalpompaAligxilo | core/shared/src/main/scala/pl/pholda/malpompaaligxilo/form/field/CheckboxField.scala | 476 | package pl.pholda.malpompaaligxilo.form.field
import pl.pholda.malpompaaligxilo.form.FieldType
case class CheckboxField(default: Boolean = false) extends FieldType[Boolean] {
override def parse(values: Seq[String]): Option[Boolean] = {
Some(values.nonEmpty)
}
override val arrayValue: Boolean = false
override def separatedValues(value: Option[Boolean]): List[(String, String)] = value match {
case Some(true) => "" -> "x" :: Nil
case _ => Nil
}
}
| gpl-3.0 |
moxaj/mobsoft-lab3 | app/src/main/java/mobsoftlab/MobSoftApplicationComponent.java | 1140 | package mobsoftlab;
import javax.inject.Singleton;
import dagger.Component;
import mobsoftlab.interactor.InteractorModule;
import mobsoftlab.interactor.chat.ChatInteractor;
import mobsoftlab.mock.MockNetworkModule;
import mobsoftlab.repository.RepositoryModule;
import mobsoftlab.ui.UIModule;
import mobsoftlab.ui.login.LoginActivity;
import mobsoftlab.ui.login.LoginPresenter;
import mobsoftlab.ui.messages.MessagesActivity;
import mobsoftlab.ui.messages.MessagesPresenter;
import mobsoftlab.ui.rooms.RoomsActivity;
import mobsoftlab.ui.rooms.RoomsPresenter;
@Singleton
@Component(modules = {UIModule.class, RepositoryModule.class, InteractorModule.class, MockNetworkModule.class})
public interface MobSoftApplicationComponent {
void inject(MobSoftApplication mobSoftApplication);
void inject(ChatInteractor chatInteractor);
void inject(LoginActivity loginActivity);
void inject(LoginPresenter loginPresenter);
void inject(RoomsActivity roomsActivity);
void inject(RoomsPresenter roomsPresenter);
void inject(MessagesActivity messagesActivity);
void inject(MessagesPresenter messagesPresenter);
}
| gpl-3.0 |
adamkruger/psiphon-tunnel-core | vendor/github.com/refraction-networking/gotapdance/tapdance/conn_raw.go | 17862 | package tapdance
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto"
pb "github.com/refraction-networking/gotapdance/protobuf"
"github.com/refraction-networking/utls"
)
// Simply establishes TLS and TapDance connection.
// Both reader and writer flows shall have this underlying raw connection.
// Knows about but doesn't keep track of timeout and upload limit
type tdRawConn struct {
tcpConn closeWriterConn // underlying TCP connection with CloseWrite() function that sends FIN
tlsConn *tls.UConn // TLS connection to decoy (and station)
covert string // hostname that tapdance station will connect client to
TcpDialer func(context.Context, string, string) (net.Conn, error)
decoySpec pb.TLSDecoySpec
pinDecoySpec bool // don't ever change decoy (still changeable from outside)
initialMsg pb.StationToClient
defaultStationPubkey []byte // this pubkey is used if the per-decoy key (tdRaw.decoySpec.Pubkey.Key) is not set
tagType tdTagType
remoteConnId []byte // 32 byte ID of the connection to station, used for reconnection
establishedAt time.Time // right after TLS connection to decoy is established, but not to station
UploadLimit int // used only in POST-based tags
closed chan struct{}
closeOnce sync.Once
// stats to report
sessionStats pb.SessionStats
failedDecoys []string
// purely for logging and stats reporting purposes:
flowId CounterUint64 // id of the flow within the session (=how many times reconnected)
sessionId uint64 // id of the local session
strIdSuffix string // suffix for every log string (e.g. to mark upload-only flows)
}
func makeTdRaw(handshakeType tdTagType, stationPubkey []byte) *tdRawConn {
tdRaw := &tdRawConn{tagType: handshakeType,
defaultStationPubkey: stationPubkey,
}
tdRaw.closed = make(chan struct{})
return tdRaw
}
func (tdRaw *tdRawConn) DialContext(ctx context.Context) error {
return tdRaw.dial(ctx, false)
}
func (tdRaw *tdRawConn) RedialContext(ctx context.Context) error {
tdRaw.flowId.Inc()
return tdRaw.dial(ctx, true)
}
func (tdRaw *tdRawConn) dial(ctx context.Context, reconnect bool) error {
var maxConnectionAttempts int
var err error
dialStartTs := time.Now()
var expectedTransition pb.S2C_Transition
if reconnect {
maxConnectionAttempts = 5
expectedTransition = pb.S2C_Transition_S2C_CONFIRM_RECONNECT
tdRaw.tlsConn.Close()
} else {
maxConnectionAttempts = 20
expectedTransition = pb.S2C_Transition_S2C_SESSION_INIT
if len(tdRaw.covert) > 0 {
expectedTransition = pb.S2C_Transition_S2C_SESSION_COVERT_INIT
}
}
for i := 0; i < maxConnectionAttempts; i++ {
if tdRaw.IsClosed() {
return errors.New("Closed")
}
// sleep to prevent overwhelming decoy servers
if waitTime := sleepBeforeConnect(i); waitTime != nil {
select {
case <-waitTime:
case <-ctx.Done():
return context.Canceled
case <-tdRaw.closed:
return errors.New("Closed")
}
}
if tdRaw.pinDecoySpec {
if tdRaw.decoySpec.Ipv4Addr == nil {
return errors.New("decoySpec is pinned, but empty!")
}
} else {
if !reconnect {
tdRaw.decoySpec = Assets().GetDecoy()
if tdRaw.decoySpec.GetIpAddrStr() == "" {
return errors.New("tdConn.decoyAddr is empty!")
}
}
}
if !reconnect {
// generate a new remove conn ID for each attempt to dial
// keep same remote conn ID for reconnect, since that's what it is for
tdRaw.remoteConnId = make([]byte, 16)
rand.Read(tdRaw.remoteConnId[:])
}
err = tdRaw.tryDialOnce(ctx, expectedTransition)
if err == nil {
tdRaw.sessionStats.TotalTimeToConnect = durationToU32ptrMs(time.Since(dialStartTs))
return nil
}
tdRaw.failedDecoys = append(tdRaw.failedDecoys,
tdRaw.decoySpec.GetHostname()+" "+tdRaw.decoySpec.GetIpAddrStr())
if tdRaw.sessionStats.FailedDecoysAmount == nil {
tdRaw.sessionStats.FailedDecoysAmount = new(uint32)
}
*tdRaw.sessionStats.FailedDecoysAmount += uint32(1)
}
return err
}
func (tdRaw *tdRawConn) tryDialOnce(ctx context.Context, expectedTransition pb.S2C_Transition) (err error) {
Logger().Infoln(tdRaw.idStr() + " Attempting to connect to decoy " +
tdRaw.decoySpec.GetHostname() + " (" + tdRaw.decoySpec.GetIpAddrStr() + ")")
tlsToDecoyStartTs := time.Now()
err = tdRaw.establishTLStoDecoy(ctx)
tlsToDecoyTotalTs := time.Since(tlsToDecoyStartTs)
if err != nil {
Logger().Errorf(tdRaw.idStr() + " establishTLStoDecoy(" +
tdRaw.decoySpec.GetHostname() + "," + tdRaw.decoySpec.GetIpAddrStr() +
") failed with " + err.Error())
return err
}
tdRaw.sessionStats.TlsToDecoy = durationToU32ptrMs(tlsToDecoyTotalTs)
Logger().Infof("%s Connected to decoy %s(%s) in %s", tdRaw.idStr(), tdRaw.decoySpec.GetHostname(),
tdRaw.decoySpec.GetIpAddrStr(), tlsToDecoyTotalTs.String())
if tdRaw.IsClosed() {
// if connection was closed externally while in establishTLStoDecoy()
tdRaw.tlsConn.Close()
return errors.New("Closed")
}
// Check if cipher is supported
cipherIsSupported := func(id uint16) bool {
for _, c := range tapDanceSupportedCiphers {
if c == id {
return true
}
}
return false
}
if !cipherIsSupported(tdRaw.tlsConn.ConnectionState().CipherSuite) {
Logger().Errorf("%s decoy %s offered unsupported cipher %d\n Client ciphers: %#v\n",
tdRaw.idStr(), tdRaw.decoySpec.GetHostname(),
tdRaw.tlsConn.ConnectionState().CipherSuite,
tdRaw.tlsConn.HandshakeState.Hello.CipherSuites)
err = errors.New("Unsupported cipher.")
tdRaw.tlsConn.Close()
return err
}
var tdRequest string
tdRequest, err = tdRaw.prepareTDRequest(tdRaw.tagType)
if err != nil {
Logger().Errorf(tdRaw.idStr() +
" Preparation of initial TD request failed with " + err.Error())
tdRaw.tlsConn.Close()
return
}
tdRaw.establishedAt = time.Now() // TODO: recheck how ClientConf's timeout is calculated and move, if needed
Logger().Infoln(tdRaw.idStr() + " Attempting to connect to TapDance Station" +
" with connection ID: " + hex.EncodeToString(tdRaw.remoteConnId[:]) + ", method: " +
tdRaw.tagType.Str())
rttToStationStartTs := time.Now()
_, err = tdRaw.tlsConn.Write([]byte(tdRequest))
if err != nil {
Logger().Errorf(tdRaw.idStr() +
" Could not send initial TD request, error: " + err.Error())
tdRaw.tlsConn.Close()
return
}
// Give up waiting for the station pretty quickly (2x handshake time == ~4RTT)
tdRaw.tlsConn.SetDeadline(time.Now().Add(tlsToDecoyTotalTs * 2))
switch tdRaw.tagType {
case tagHttpGetIncomplete:
tdRaw.initialMsg, err = tdRaw.readProto()
rttToStationTotalTs := time.Since(rttToStationStartTs)
tdRaw.sessionStats.RttToStation = durationToU32ptrMs(rttToStationTotalTs)
if err != nil {
if errIsTimeout(err) {
Logger().Errorf("%s %s: %v", tdRaw.idStr(),
"TapDance station didn't pick up the request", err)
// lame fix for issue #38 with abrupt drop of not picked up flows
tdRaw.tlsConn.SetDeadline(time.Now().Add(
getRandomDuration(deadlineTCPtoDecoyMin,
deadlineTCPtoDecoyMax)))
tdRaw.tlsConn.Write([]byte(getRandPadding(456, 789, 5) + "\r\n" +
"Connection: close\r\n\r\n"))
go readAndClose(tdRaw.tlsConn,
getRandomDuration(deadlineTCPtoDecoyMin,
deadlineTCPtoDecoyMax))
} else {
// any other error will be fatal
Logger().Errorf(tdRaw.idStr() +
" fatal error reading from TapDance station: " +
err.Error())
tdRaw.tlsConn.Close()
return
}
return
}
if tdRaw.initialMsg.GetStateTransition() != expectedTransition {
err = errors.New("Init error: state transition mismatch!" +
" Received: " + tdRaw.initialMsg.GetStateTransition().String() +
" Expected: " + expectedTransition.String())
Logger().Infof("%s Failed to connect to TapDance Station [%s]: %s",
tdRaw.idStr(), tdRaw.initialMsg.GetStationId(), err.Error())
// this exceptional error implies that station has lost state, thus is fatal
return err
}
Logger().Infoln(tdRaw.idStr() + " Successfully connected to TapDance Station [" + tdRaw.initialMsg.GetStationId() + "]")
case tagHttpPostIncomplete:
// don't wait for response
default:
panic("Unsupported td handshake type:" + tdRaw.tagType.Str())
}
// TapDance should NOT have a timeout, timeouts have to be handled by client and server
tdRaw.tlsConn.SetDeadline(time.Time{}) // unsets timeout
return nil
}
func (tdRaw *tdRawConn) establishTLStoDecoy(ctx context.Context) error {
deadline, deadlineAlreadySet := ctx.Deadline()
if !deadlineAlreadySet {
deadline = time.Now().Add(getRandomDuration(deadlineTCPtoDecoyMin, deadlineTCPtoDecoyMax))
}
childCtx, childCancelFunc := context.WithDeadline(ctx, deadline)
defer childCancelFunc()
tcpDialer := tdRaw.TcpDialer
if tcpDialer == nil {
// custom dialer is not set, use default
d := net.Dialer{}
tcpDialer = d.DialContext
}
tcpToDecoyStartTs := time.Now()
dialConn, err := tcpDialer(childCtx, "tcp", tdRaw.decoySpec.GetIpAddrStr())
tcpToDecoyTotalTs := time.Since(tcpToDecoyStartTs)
if err != nil {
return err
}
tdRaw.sessionStats.TcpToDecoy = durationToU32ptrMs(tcpToDecoyTotalTs)
config := tls.Config{ServerName: tdRaw.decoySpec.GetHostname()}
if config.ServerName == "" {
// if SNI is unset -- try IP
config.ServerName, _, err = net.SplitHostPort(tdRaw.decoySpec.GetIpAddrStr())
if err != nil {
dialConn.Close()
return err
}
Logger().Infoln(tdRaw.idStr() + ": SNI was nil. Setting it to" +
config.ServerName)
}
// parrot Chrome 62 ClientHello
tdRaw.tlsConn = tls.UClient(dialConn, &config, tls.HelloChrome_62)
err = tdRaw.tlsConn.BuildHandshakeState()
if err != nil {
dialConn.Close()
return err
}
err = tdRaw.tlsConn.MarshalClientHello()
if err != nil {
dialConn.Close()
return err
}
tdRaw.tlsConn.SetDeadline(deadline)
err = tdRaw.tlsConn.Handshake()
if err != nil {
dialConn.Close()
return err
}
closeWriter, ok := dialConn.(closeWriterConn)
if !ok {
return errors.New("dialConn is not a closeWriter")
}
tdRaw.tcpConn = closeWriter
return nil
}
func (tdRaw *tdRawConn) Close() error {
var err error
tdRaw.closeOnce.Do(func() {
close(tdRaw.closed)
if tdRaw.tlsConn != nil {
err = tdRaw.tlsConn.Close()
}
})
return err
}
type closeWriterConn interface {
net.Conn
CloseWrite() error
}
func (tdRaw *tdRawConn) closeWrite() error {
return tdRaw.tcpConn.CloseWrite()
}
func (tdRaw *tdRawConn) prepareTDRequest(handshakeType tdTagType) (string, error) {
// Generate tag for the initial TapDance request
buf := new(bytes.Buffer) // What we have to encrypt with the shared secret using AES
masterKey := tdRaw.tlsConn.HandshakeState.MasterSecret
// write flags
flags := default_flags
if tdRaw.tagType == tagHttpPostIncomplete {
flags |= tdFlagUploadOnly
}
if err := binary.Write(buf, binary.BigEndian, flags); err != nil {
return "", err
}
buf.Write([]byte{0}) // Unassigned byte
negotiatedCipher := tdRaw.tlsConn.HandshakeState.State12.Suite.Id
if tdRaw.tlsConn.HandshakeState.ServerHello.Vers == tls.VersionTLS13 {
negotiatedCipher = tdRaw.tlsConn.HandshakeState.State13.Suite.Id
}
buf.Write([]byte{byte(negotiatedCipher >> 8),
byte(negotiatedCipher & 0xff)})
buf.Write(masterKey[:])
buf.Write(tdRaw.tlsConn.HandshakeState.ServerHello.Random)
buf.Write(tdRaw.tlsConn.HandshakeState.Hello.Random)
buf.Write(tdRaw.remoteConnId[:]) // connection id for persistence
err := WriteTlsLog(tdRaw.tlsConn.HandshakeState.Hello.Random,
tdRaw.tlsConn.HandshakeState.MasterSecret)
if err != nil {
Logger().Warningf("Failed to write TLS secret log: %s", err)
}
// Generate and marshal protobuf
transition := pb.C2S_Transition_C2S_SESSION_INIT
var covert *string
if len(tdRaw.covert) > 0 {
transition = pb.C2S_Transition_C2S_SESSION_COVERT_INIT
covert = &tdRaw.covert
}
currGen := Assets().GetGeneration()
initProto := &pb.ClientToStation{
CovertAddress: covert,
StateTransition: &transition,
DecoyListGeneration: &currGen,
}
initProtoBytes, err := proto.Marshal(initProto)
if err != nil {
return "", err
}
Logger().Debugln(tdRaw.idStr()+" Initial protobuf", initProto)
// Choose the station pubkey
pubkey := tdRaw.defaultStationPubkey
if perDecoyKey := tdRaw.decoySpec.GetPubkey().GetKey(); perDecoyKey != nil {
pubkey = perDecoyKey // per-decoy key takes preference over default global pubkey
}
// Obfuscate/encrypt tag and protobuf
tag, encryptedProtoMsg, err := obfuscateTagAndProtobuf(buf.Bytes(), initProtoBytes, pubkey)
if err != nil {
return "", err
}
return tdRaw.genHTTP1Tag(tag, encryptedProtoMsg)
}
// mutates tdRaw: sets tdRaw.UploadLimit
func (tdRaw *tdRawConn) genHTTP1Tag(tag, encryptedProtoMsg []byte) (string, error) {
sharedHeaders := `Host: ` + tdRaw.decoySpec.GetHostname() +
"\nUser-Agent: TapDance/1.2 (+https://refraction.network/info)"
if len(encryptedProtoMsg) > 0 {
sharedHeaders += "\nX-Proto: " + base64.StdEncoding.EncodeToString(encryptedProtoMsg)
}
var httpTag string
switch tdRaw.tagType {
// for complete copy http generator of golang
case tagHttpGetComplete:
fallthrough
case tagHttpGetIncomplete:
tdRaw.UploadLimit = int(tdRaw.decoySpec.GetTcpwin()) - getRandInt(1, 1045)
httpTag = fmt.Sprintf(`GET / HTTP/1.1
%s
X-Ignore: %s`, sharedHeaders, getRandPadding(7, maxInt(612-len(sharedHeaders), 7), 10))
httpTag = strings.Replace(httpTag, "\n", "\r\n", -1)
case tagHttpPostIncomplete:
ContentLength := getRandInt(900000, 1045000)
tdRaw.UploadLimit = ContentLength - 1
httpTag = fmt.Sprintf(`POST / HTTP/1.1
%s
Accept-Encoding: None
X-Padding: %s
Content-Type: application/zip; boundary=----WebKitFormBoundaryaym16ehT29q60rUx
Content-Length: %s
----WebKitFormBoundaryaym16ehT29q60rUx
Content-Disposition: form-data; name=\"td.zip\"
`, sharedHeaders, getRandPadding(1, maxInt(461-len(sharedHeaders), 1), 10), strconv.Itoa(ContentLength))
httpTag = strings.Replace(httpTag, "\n", "\r\n", -1)
}
keystreamOffset := len(httpTag)
keystreamSize := (len(tag)/3+1)*4 + keystreamOffset // we can't use first 2 bits of every byte
wholeKeystream, err := tdRaw.tlsConn.GetOutKeystream(keystreamSize)
if err != nil {
return httpTag, err
}
keystreamAtTag := wholeKeystream[keystreamOffset:]
httpTag += reverseEncrypt(tag, keystreamAtTag)
if tdRaw.tagType == tagHttpGetComplete {
httpTag += "\r\n\r\n"
}
Logger().Debugf("Generated HTTP TAG:\n%s\n", httpTag)
return httpTag, nil
}
func (tdRaw *tdRawConn) idStr() string {
return "[Session " + strconv.FormatUint(tdRaw.sessionId, 10) + ", " +
"Flow " + strconv.FormatUint(tdRaw.flowId.Get(), 10) + tdRaw.strIdSuffix + "]"
}
// Simply reads and returns protobuf
// Returns error if it's not a protobuf
// TODO: redesign it pb, data, err
func (tdRaw *tdRawConn) readProto() (msg pb.StationToClient, err error) {
var readBuffer bytes.Buffer
var outerProtoMsgType msgType
var msgLen int64 // just the body (e.g. raw data or protobuf)
// Get TIL
_, err = io.CopyN(&readBuffer, tdRaw.tlsConn, 2)
if err != nil {
return
}
typeLen := uint16toInt16(binary.BigEndian.Uint16(readBuffer.Next(2)))
if typeLen < 0 {
outerProtoMsgType = msgRawData
msgLen = int64(-typeLen)
} else if typeLen > 0 {
outerProtoMsgType = msgProtobuf
msgLen = int64(typeLen)
} else {
// protobuf with size over 32KB, not fitting into 2-byte TL
outerProtoMsgType = msgProtobuf
_, err = io.CopyN(&readBuffer, tdRaw.tlsConn, 4)
if err != nil {
return
}
msgLen = int64(binary.BigEndian.Uint32(readBuffer.Next(4)))
}
if outerProtoMsgType == msgRawData {
err = errors.New("Received data message in uninitialized flow")
return
}
// Get the message itself
_, err = io.CopyN(&readBuffer, tdRaw.tlsConn, msgLen)
if err != nil {
return
}
err = proto.Unmarshal(readBuffer.Bytes(), &msg)
if err != nil {
return
}
Logger().Debugln(tdRaw.idStr() + " INIT: received protobuf: " + msg.String())
return
}
// Generates padding and stuff
// Currently guaranteed to be less than 1024 bytes long
func (tdRaw *tdRawConn) writeTransition(transition pb.C2S_Transition) (n int, err error) {
const paddingMinSize = 250
const paddingMaxSize = 800
const paddingSmoothness = 5
paddingDecrement := 0 // reduce potential padding size by this value
currGen := Assets().GetGeneration()
msg := pb.ClientToStation{
DecoyListGeneration: &currGen,
StateTransition: &transition,
UploadSync: new(uint64)} // TODO: remove
if tdRaw.flowId.Get() == 0 {
// we have stats for each reconnect, but only send stats for the initial connection
msg.Stats = &tdRaw.sessionStats
}
if len(tdRaw.failedDecoys) > 0 {
failedDecoysIdx := 0 // how many failed decoys to report now
for failedDecoysIdx < len(tdRaw.failedDecoys) {
if paddingMinSize < proto.Size(&pb.ClientToStation{
FailedDecoys: tdRaw.failedDecoys[:failedDecoysIdx+1]}) {
// if failedDecoys list is too big to fit in place of min padding
// then send the rest on the next reconnect
break
}
failedDecoysIdx += 1
}
paddingDecrement = proto.Size(&pb.ClientToStation{
FailedDecoys: tdRaw.failedDecoys[:failedDecoysIdx]})
msg.FailedDecoys = tdRaw.failedDecoys[:failedDecoysIdx]
tdRaw.failedDecoys = tdRaw.failedDecoys[failedDecoysIdx:]
}
msg.Padding = []byte(getRandPadding(paddingMinSize-paddingDecrement,
paddingMaxSize-paddingDecrement, paddingSmoothness))
msgBytes, err := proto.Marshal(&msg)
if err != nil {
return
}
Logger().Infoln(tdRaw.idStr()+" sending transition: ", msg.String())
b := getMsgWithHeader(msgProtobuf, msgBytes)
n, err = tdRaw.tlsConn.Write(b)
return
}
func (tdRaw *tdRawConn) IsClosed() bool {
select {
case <-tdRaw.closed:
return true
default:
return false
}
}
| gpl-3.0 |
olivettikatz/libincandescence | audio/SoundExtern.cpp | 765 | #include "SoundExtern.h"
namespace incandescence
{
void SoundExtern::load()
{
argv[0] = "afplay";
argv[1] = "-v";
stringstream ss;
ss << volume;
argv[2] = (char *)ss.str().c_str();
argv[3] = (char *)path.c_str();
argv[4] = "-q";
argv[5] = "1";
argv[6] = "-t";
argv[7] = "0.1";
argv[8] = NULL;
}
void SoundExtern::play()
{
pid_t pid = fork();
if (pid == 0)
{
if (execvp(argv[0], argv) != 0)
{
INCD_ERROR("error while executing SoundExtern::play.");
return ;
}
}
else if (pid < 0)
{
INCD_ERROR("unable to fork thread for SoundExtern::play.");
}
else
{
int r = 0;
waitpid(pid, &r, 0);
if (r != 0)
{
INCD_ERROR("error while playing sound '" << path << "' (" << r << ").");
}
}
}
} | gpl-3.0 |
Rouletus/fsm_gillot | src/utils/Transition.java | 1132 | package utils;
/**
* Classe représentant une transition entre états
* @author ThomasGillot
*/
public class Transition {
private State departure;
private State arrival;
private String input_event;
private String output_event;
public Transition(State departure, State arrival,String input_event, String output_event) {
this.departure = departure;
this.arrival = arrival;
this.input_event = input_event;
this.output_event = output_event;
}
public State getDeparture() {
return departure;
}
public State getArrival() {
return arrival;
}
public String getOutput_event() {
return output_event;
}
public String getInput_event() {
return input_event;
}
public String toNewObject(){
return "\t\tt = new Transition("+this.departure.getId()+","+this.arrival.getId()+",\""+this.input_event+"\",\""+ this.output_event+"\");\n" +
"\t\ttransitions.add(t);\n";
}
@Override
public String toString() {
return departure + "->" + arrival + "/" + output_event;
}
}
| gpl-3.0 |
pchote/OpenRA | mods/ra/maps/soviet-09/soviet09.lua | 3867 | --[[
Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
TruckStops = { TruckStop1, TruckStop2, TruckStop3, TruckStop4, TruckStop5, TruckStop6, TruckStop7, TruckStop8 }
MissionStartAttackUnits = { StartAttack1tnk1, StartAttack1tnk2, StartAttackArty1, StartAttackArty2, StartAttackArty3 }
TruckEscape = { TruckEscape1, TruckEscape2, TruckEscape3, TruckEscape4, TruckEscape5, TruckEscapeWest }
BackupRoute = { TruckEscape2, TruckEscape1, TruckEscapeEast }
MissionStart = function()
Utils.Do(TruckStops, function(waypoint)
StolenTruck.Move(waypoint.Location)
end)
Trigger.AfterDelay(DateTime.Seconds(5), function()
Utils.Do(MissionStartAttackUnits, function(actor)
actor.AttackMove(DefaultCameraPosition.Location)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(45), function()
Media.DisplayMessage("Commander, the truck has stopped at a nearby allied base.\nAllied radio intercepts say the truck has orders to flee the battlefield\nif any Soviet units approach the base.")
end)
Trigger.OnKilled(StolenTruck, function()
USSR.MarkCompletedObjective(DestroyTruck)
USSR.MarkCompletedObjective(DefendCommand)
end)
Trigger.OnKilled(CommandCenter, function()
USSR.MarkFailedObjective(DefendCommand)
end)
end
Trigger.OnEnteredProximityTrigger(TruckAlarm.CenterPosition, WDist.FromCells(11), function(actor, triggerflee)
if actor.Owner == USSR and actor.Type ~= "badr" and actor.Type ~= "u2" and actor.Type ~= "camera.spyplane" then
Trigger.RemoveProximityTrigger(triggerflee)
Media.DisplayMessage("The convoy truck is attempting to escape!")
EscapeCamera = Actor.Create("camera", true, { Owner = USSR, Location = TruckAlarm.Location })
Media.PlaySoundNotification(USSR, "AlertBleep")
Utils.Do(TruckEscape, function(waypoint)
StolenTruck.Move(waypoint.Location)
end)
Trigger.AfterDelay(DateTime.Seconds(5), function()
EscapeCamera.Destroy()
end)
Trigger.OnIdle(StolenTruck, function()
Utils.Do(BackupRoute, function(waypoint)
StolenTruck.Move(waypoint.Location)
end)
end)
end
end)
Trigger.OnEnteredFootprint(({ TruckEscapeWest.Location } or { TruckEscapeEast.Location }), function(actor, triggerlose)
if actor.Owner == Greece and actor.Type == "truk" then
Trigger.RemoveFootprintTrigger(triggerlose)
actor.Destroy()
USSR.MarkFailedObjective(DestroyTruck)
end
end)
Tick = function()
Greece.Cash = 50000
Germany.Cash = 50000
end
WorldLoaded = function()
USSR = Player.GetPlayer("USSR")
Germany = Player.GetPlayer("Germany")
Greece = Player.GetPlayer("Greece")
Trigger.OnObjectiveAdded(USSR, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
DestroyTruck = USSR.AddObjective("Destroy the stolen convoy truck.\nDo not let it escape.")
DefendCommand = USSR.AddObjective("Defend our forward command center.")
Trigger.OnObjectiveCompleted(USSR, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(USSR, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(USSR, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(USSR, "MissionFailed")
end)
end)
Trigger.OnPlayerWon(USSR, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(USSR, "MissionAccomplished")
end)
end)
Camera.Position = DefaultCameraPosition.CenterPosition
MissionStart()
ActivateAI()
end
| gpl-3.0 |
alexrudnick/hackerschool-demos | ngrams/doitlive.py | 3495 | #!/usr/bin/env python3
import math
import sys
import random
import readline
from collections import defaultdict
from collections import Counter
LOW_NUMBER = 0.00001
## counts dictionary maps from contexts to dictionaries (Counters) that map from
## words to their counts.
def build_counts(sentences):
"""Return a counts dictionary, given a list of sentences."""
out = defaultdict(Counter)
for sent in sentences:
sent = [None] + sent + [None]
for (prev, cur) in zip(sent, sent[1:]):
out[prev][cur] += 1
return out
def counts_to_probs(counts_dict):
"""Take a counts dictionary and return the appropriate probs dictionary."""
out = defaultdict(lambda: defaultdict(lambda: LOW_NUMBER))
for prev in counts_dict:
for cur in counts_dict[prev]:
out[prev][cur] = (counts_dict[prev][cur] /
sum(counts_dict[prev].values()))
return out
def unigram_probs(sentences):
counts = Counter()
out = defaultdict(lambda: LOW_NUMBER)
for sent in sentences:
for cur in sent:
counts[cur] += 1
total_words = sum(counts.values())
for word,count in counts.items():
out[word] = count / total_words
return out
def get_sentences(fn):
with open(fn) as infile:
out = infile.readlines()
out = [line.strip().split() for line in out]
return out
def sample_word(word_dist):
"""Given a little distribution dictionary, sample one word."""
score = random.random()
for word,prob in word_dist.items():
if score < prob:
return word
score -= prob
assert False, "this should also never happen"
def sample_sentence(probs_dict):
"""Generate a sentence!!"""
prev = None
out = []
while True:
cur = sample_word(probs_dict[prev])
if cur is None:
return out
out.append(cur)
prev = cur
assert False, "this should never happen!"
def score_sentence(sent, bigram_probs, unigram_probs):
"""Return the surprisal value of this sentence in bits."""
total_surprise = 0
sent = [None] + sent + [None]
for (prev, cur) in zip(sent, sent[1:]):
if prev in bigram_probs and cur in bigram_probs[prev]:
surprise = -math.log(bigram_probs[prev][cur], 2)
else:
## STUPID BACKOFF (Brants et al 2010)
prob = 0.4 * unigram_probs[cur]
surprise = -math.log(prob, 2)
total_surprise += surprise
return total_surprise
def main():
sentences = get_sentences(sys.argv[1])
counts = build_counts(sentences)
bigram = counts_to_probs(counts)
unigram = unigram_probs(sentences)
##print(sentence)
##print(" ".join(sentence))
sent = "`` What ho , Angela , old girl . ''".split()
print(sent)
score = score_sentence(sent, bigram, unigram)
print(score)
sent = "`` What airplane , Angela , old girl . ''".split()
print(sent)
score = score_sentence(sent, bigram, unigram)
print(score)
print("GIVE ME SENTENCES.")
while True:
line = input("> ")
if not line: break
sent = line.split()
score = score_sentence(sent, bigram, unigram)
print("I give it a:", score)
generated = sample_sentence(bigram)
print("Let me try: ", " ".join(generated))
score = score_sentence(generated, bigram, unigram)
print("I got a:", score)
if __name__ == "__main__": main()
| gpl-3.0 |
BerntA/DeadBread | DeadBread/Controls/ConVarList.cs | 9221 | //========= Copyright © Reperio Studios 2013-2016 @ Bernt Andreas Eide! ============//
//
// Purpose: ConVar List : Parses a given .txt which is passed in from the ServerForm, we display custom convars + tooltips for'em.
//
//=============================================================================================//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DeadBread.Base;
namespace DeadBread.Controls
{
public partial class ConVarList : UserControl
{
public bool m_bCanOpen;
private string szCFGPath;
public ConVarList(string game, string cfgPath)
{
InitializeComponent();
this.SetStyle(
System.Windows.Forms.ControlStyles.UserPaint |
System.Windows.Forms.ControlStyles.AllPaintingInWmPaint |
System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer,
true);
DoubleBuffered = true;
BackColor = Color.Transparent;
ForeColor = Color.Transparent;
if (!DesignMode)
BackgroundImage = Globals.GetTextureImage("controls\\LoginBG.png");
m_bCanOpen = false;
szCFGPath = cfgPath;
ParseConVarFile(game);
}
public void WriteConVarsToConfig()
{
if (!m_bCanOpen)
return;
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is CheckBoxNew)
WriteToConfig(string.Format("{0} {1}", ((CheckBoxNew)Controls[i]).GetConVar(), ((CheckBoxNew)Controls[i]).IsChecked() ? 1 : 0));
else
{
switch (((NumericVar)Controls[i]).ValueType)
{
case 0:
WriteToConfig(string.Format("{0} {1}", ((NumericVar)Controls[i]).GetConVar(), ((NumericVar)Controls[i]).GetValueInt()));
break;
case 1:
WriteToConfig(string.Format("{0} {1}", ((NumericVar)Controls[i]).GetConVar(), ((NumericVar)Controls[i]).GetValueFloat()));
break;
case 2:
WriteToConfig(string.Format("{0} \"{1}\"", ((NumericVar)Controls[i]).GetConVar(), ((NumericVar)Controls[i]).GetValueString()));
break;
}
}
}
}
/// <summary>
/// Write to the server.cfg file...
/// </summary>
/// <param name="text"></param>
private void WriteToConfig(string text)
{
using (StreamWriter writer = new StreamWriter(szCFGPath, true))
{
writer.Write(text + Environment.NewLine);
}
}
private void ParseConVarFile(string game)
{
try
{
using (StreamReader reader = new StreamReader(string.Format("{0}\\BaseLauncher\\config\\{1}_convars.txt", Globals.GetAppPath(), game)))
{
m_bCanOpen = true;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (string.IsNullOrEmpty(line))
continue;
int iValue = 0;
string szValue = null;
float flValue = 0.0F;
int iYPos = 0;
for (int i = 0; i < Controls.Count; i++)
{
if (iYPos < (Controls[i].Height + Controls[i].Bounds.Y))
iYPos = (Controls[i].Height + Controls[i].Bounds.Y);
}
if (line.Contains("BOOL"))
{
line = line.Replace("BOOL ", "");
iValue = int.Parse(line.Substring(0, line.IndexOf(" ")));
line = line.Replace(line.Substring(0, line.IndexOf(" ") + 1), "");
int indexToNextSpace = line.IndexOf(" ");
string szConVar = line.Substring(0, indexToNextSpace);
line = line.Replace(line.Substring(0, indexToNextSpace + 1), "");
int indexToBracket1 = line.IndexOf(">");
CheckBoxNew checkBox = new CheckBoxNew(line.Substring(1, indexToBracket1 - 1), szConVar, (iValue > 0) ? true : false);
checkBox.Parent = this;
checkBox.Bounds = new Rectangle(20, iYPos + 5, 150, 24);
checkBox.BringToFront();
line = line.Replace(line.Substring(0, indexToBracket1 + 2), "");
line = line.Replace(">", "");
line = line.Replace("<", "");
infoTip.SetToolTip(checkBox, line);
}
else if (line.Contains("INT"))
{
line = line.Replace("INT ", "");
iValue = int.Parse(line.Substring(0, line.IndexOf(" ")));
line = line.Replace(line.Substring(0, line.IndexOf(" ") + 1), "");
int indexToNextSpace = line.IndexOf(" ");
string szConVar = line.Substring(0, indexToNextSpace);
line = line.Replace(line.Substring(0, indexToNextSpace + 1), "");
int indexToBracket1 = line.IndexOf(">");
NumericVar numericBox = new NumericVar(line.Substring(1, indexToBracket1 - 1), szConVar, iValue);
numericBox.Parent = this;
numericBox.Bounds = new Rectangle(20, iYPos + 5, 300, 40);
numericBox.BringToFront();
line = line.Replace(line.Substring(0, indexToBracket1 + 2), "");
line = line.Replace(">", "");
line = line.Replace("<", "");
infoTip.SetToolTip(numericBox, line);
}
else if (line.Contains("FLOAT"))
{
line = line.Replace("FLOAT ", "");
flValue = float.Parse(line.Substring(0, line.IndexOf(" ")));
line = line.Replace(line.Substring(0, line.IndexOf(" ") + 1), "");
int indexToNextSpace = line.IndexOf(" ");
string szConVar = line.Substring(0, indexToNextSpace);
line = line.Replace(line.Substring(0, indexToNextSpace + 1), "");
int indexToBracket1 = line.IndexOf(">");
NumericVar numericBox = new NumericVar(line.Substring(1, indexToBracket1 - 1), szConVar, flValue);
numericBox.Parent = this;
numericBox.Bounds = new Rectangle(20, iYPos + 5, 300, 40);
numericBox.BringToFront();
line = line.Replace(line.Substring(0, indexToBracket1 + 2), "");
line = line.Replace(">", "");
line = line.Replace("<", "");
infoTip.SetToolTip(numericBox, line);
}
else if (line.Contains("STRING"))
{
line = line.Replace("STRING ", "");
szValue = line.Substring(0, line.IndexOf(" "));
line = line.Replace(line.Substring(0, line.IndexOf(" ") + 1), "");
int indexToNextSpace = line.IndexOf(" ");
string szConVar = line.Substring(0, indexToNextSpace);
line = line.Replace(line.Substring(0, indexToNextSpace + 1), "");
int indexToBracket1 = line.IndexOf(">");
NumericVar numericBox = new NumericVar(line.Substring(1, indexToBracket1 - 1), szConVar, szValue);
numericBox.Parent = this;
numericBox.Bounds = new Rectangle(20, iYPos + 5, 300, 40);
numericBox.BringToFront();
line = line.Replace(line.Substring(0, indexToBracket1 + 2), "");
line = line.Replace(">", "");
line = line.Replace("<", "");
infoTip.SetToolTip(numericBox, line);
}
}
}
}
catch
{
m_bCanOpen = false;
Visible = false;
}
}
}
}
| gpl-3.0 |
votkapower/m-cs | 21232f297a/admin_switch/plugins/index.php | 3600 |
<div id='panel-top'>Адним панел - Добавки [ Plug-ins ]</div>
<div id='panel-bottom'>
<?php
$pln = htmlspecialchars(trim($_GET['pln']));
if(!$pln){ $pln = "list";}
switch ($pln)
{
case "list":
$dir = "../plugins";
$handle = opendir($dir);
$i=0;
while (($plugin_f = readdir($handle))!== false)
{
if( strlen($plugin_f) > 3 && $plugin_f != "Thumb.db")
{
$i++;
$pl_info_file = $dir."/".$plugin_f."/info.txt";
$fo = fopen($pl_info_file, "r");
$plugin_info = fread($fo, filesize($pl_info_file));
fclose($fo);
$finded_rs = mysqli_query($_db,"SELECT * FROM `plugins` WHERE `plugin_name`='$plugin_f'");
$count = mysqli_num_rows($finded_rs);
$time = time();
preg_match("/Автор: (.*)/", $plugin_info, $p_autor_matches);
preg_match("/Версия: ([0-9\.]+){0,10}/", $plugin_info, $p_vers_matches);
preg_match("/Име: (.+){0,".strlen($plugin_info)."}/", $plugin_info, $plugin_title);
preg_match("/Инфо: (.+){0,}/", $plugin_info, $pl_info);
$p_author = $p_autor_matches[1];
$p_version = $p_vers_matches[1];
$plugin_title = $plugin_title[1];
if(@file_exists("../switch/plugin-".$plugin_f."/index.php") OR @file_exists("../plugins/".$plugin_f."/install.php"))
{
if($count == 0) // `plugins` >>>>> `plugin_name`,`plugin_version`,`plugin_author`,`timestamp`,`installed`
{
mysqli_query($_db,"INSERT INTO `plugins` (`plugin_name`,`title`,`plugin_version`,`plugin_author`,`timestamp`,`installed`)VALUES('".$plugin_f."','$plugin_title','$p_version','$p_author','$time','false')")or die(mysqli_error($_db));
}
}
$plugin_info = $pl_info[1];
?>
<div onmouseover="$(this).next().css('background','#121212')" onmouseout="$(this).next().css('background','#333333')" style='background:#262424;padding:5px;color:#b5190e;font-family:Arial;border-bottom:1px solid #666;'>
<b style='font-size:18px;'><?php echo $i.".".$plugin_title;?></b>
<span style='float:right;color:#666;'>[
<?php
$q = mysqli_fetch_array(mysqli_query($_db,"SELECT `installed` FROM `plugins` WHERE `plugin_name`='".$plugin_f."'"));
//echo $q['installed'];
if( $q['installed'] == 'false')
{
?>
<a href='./?p=plugins&pln=install&pnm=<?php echo $plugin_f;?>' style='color:green;'>Инсталирай</a>
<?php
}
else
{
?>
<a href='./?p=plugins&pln=deinstall&pnm=<?php echo $plugin_f;?>'>Де-инсталирай</a>
<?php
}
?>
]</span>
</div>
<div onmouseover="this.style.background='#121212'" onmouseout="this.style.background='#333333'" style='background:#333;padding:5px;color:#ccc;font-size:11px;font-family:arial;border-bottom:0px solid #666;'>
<i><?php echo nl2br($plugin_info);?></i>
<div style='padding:0px 5px;margin-top:5px;'>
<span>автор: <b style='font-size:9px;'><?php echo $p_author; ?></b></span>
<span style='float:right;'>версия: <b style='font-size:9px;'><?php echo $p_version;?></b></span>
</div>
</div>
<br>
<?php
}
}
closedir($handle);
break;
case "install":
$title = trim(htmlspecialchars($_GET['pnm']));
include "../plugins/".$title."/install.php";
break;
case "deinstall":
$title = trim(htmlspecialchars($_GET['pnm']));
include "../plugins/".$title."/deinstall.php";
break;
}
?>
</div> | gpl-3.0 |
Henrik-Peters/ActivFlex-Media | ActivFlex Media/ViewModels/LibraryVideoViewModel.cs | 7050 | #region License
// ActivFlex Media - Manage your media libraries
// Copyright(C) 2017 Henrik Peters
//
// 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/>.
#endregion
using System.Windows;
using System.Windows.Media.Imaging;
using ActivFlex.Libraries;
namespace ActivFlex.ViewModels
{
/// <summary>
/// ViewModel implementation for library video thumbnail controls.
/// </summary>
public class LibraryVideoViewModel : ViewModel, ILibraryItemViewModel
{
private LibraryVideo _proxy;
/// <summary>
/// The represented library item.
/// </summary>
public ILibraryItem Proxy {
get => _proxy;
set {
if (_proxy != value && value is LibraryVideo) {
_proxy = (LibraryVideo)value;
//Video indicator for cached thumbnails
if (_proxy.Thumbnail != null) {
IndicatorVisibility = Visibility.Visible;
}
NotifyPropertyChanged();
}
}
}
/// <summary>
/// The thumbnail image of the represented video.
/// Will be null when the thumbnail is not loaded.
/// </summary>
public BitmapSource ThumbImage {
get => _proxy.Thumbnail;
set {
//Video indicator
if (value != null) {
IndicatorVisibility = Visibility.Visible;
}
_proxy.Thumbnail = value;
NotifyPropertyChanged();
}
}
private Visibility _indicatorVisibility = Visibility.Collapsed;
public Visibility IndicatorVisibility {
get => _indicatorVisibility;
set => SetProperty(ref _indicatorVisibility, value);
}
/// <summary>
/// Media container that stores the item.
/// </summary>
public MediaContainer Container => _proxy.Container;
/// <summary>
/// Unique global identifier of the item.
/// </summary>
public int ItemID => _proxy.ItemID;
/// <summary>
/// Short text to describe the item.
/// </summary>
public string Name {
get => _proxy.Name;
set {
if (_proxy.Name != value) {
_proxy.Name = value;
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Absolute filesystem path of the item.
/// </summary>
public string Path => _proxy.Path;
/// <summary>
/// True when the item is selected in a view.
/// </summary>
public bool IsSelected {
get => _proxy.IsSelected;
set {
if (_proxy.IsSelected != value) {
_proxy.IsSelected = value;
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for one star.
/// </summary>
public bool RatingOneStar {
get => _proxy.Rating == StarRating.OneStar;
set {
if (value && _proxy.Rating != StarRating.OneStar) {
_proxy.Rating = StarRating.OneStar;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.OneStar);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for two stars.
/// </summary>
public bool RatingTwoStars {
get => _proxy.Rating == StarRating.TwoStars;
set {
if (value && _proxy.Rating != StarRating.TwoStars) {
_proxy.Rating = StarRating.TwoStars;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.TwoStars);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for three stars.
/// </summary>
public bool RatingThreeStars {
get => _proxy.Rating == StarRating.ThreeStars;
set {
if (value && _proxy.Rating != StarRating.ThreeStars) {
_proxy.Rating = StarRating.ThreeStars;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.ThreeStars);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for four stars.
/// </summary>
public bool RatingFourStars {
get => _proxy.Rating == StarRating.FourStars;
set {
if (value && _proxy.Rating != StarRating.FourStars) {
_proxy.Rating = StarRating.FourStars;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.FourStars);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for five stars.
/// </summary>
public bool RatingFiveStars {
get => _proxy.Rating == StarRating.FiveStars;
set {
if (value && _proxy.Rating != StarRating.FiveStars) {
_proxy.Rating = StarRating.FiveStars;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.FiveStars);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Checks or sets the rating for no rating.
/// </summary>
public bool RatingNotRated {
get => _proxy.Rating == StarRating.NoRating;
set {
if (value && _proxy.Rating != StarRating.NoRating) {
_proxy.Rating = StarRating.NoRating;
MainViewModel.StorageEngine.UpdateLibraryItemRating(ItemID, StarRating.NoRating);
NotifyPropertyChanged();
}
}
}
/// <summary>
/// Create a new view model for a library video item.
/// </summary>
/// <param name="proxy">The represented video music</param>
public LibraryVideoViewModel(LibraryVideo proxy)
{
this.Proxy = proxy;
}
}
} | gpl-3.0 |
Platonymous/Stardew-Valley-Mods | HarpOfYobaRedux/Magic/SeedMagic.cs | 1871 | using System.Collections.Generic;
using StardewValley;
using Microsoft.Xna.Framework;
using StardewValley.TerrainFeatures;
namespace HarpOfYobaRedux
{
class SeedMagic : IMagic
{
public SeedMagic()
{
}
public void doMagic(bool playedToday)
{
if (!playedToday)
{
List<Vector2> tiles = Utility.getAdjacentTileLocations(Game1.player.getTileLocation());
Vector2 playerTile = Game1.player.getTileLocation();
tiles.Add(playerTile);
tiles.Add(playerTile + new Vector2(1f, 1f));
tiles.Add(playerTile + new Vector2(-1f, -1f));
tiles.Add(playerTile + new Vector2(1f, -1f));
tiles.Add(playerTile + new Vector2(-1f, 1f));
foreach (Vector2 tile in tiles)
{
if(Game1.currentLocation.terrainFeatures.ContainsKey(tile) && Game1.currentLocation.terrainFeatures[tile] is HoeDirt)
{
HoeDirt hd = (HoeDirt) Game1.currentLocation.terrainFeatures[tile];
if (hd.crop == null)
{
int seeds = 770;
if (Game1.IsWinter)
seeds = 498;
hd.plant(seeds,(int)tile.X, (int)tile.Y,Game1.player, false, Game1.currentLocation);
if(hd.crop != null)
{
hd.crop.newDay(1, 0, (int)tile.X, (int)tile.Y, Game1.currentLocation);
Game1.playSound("leafrustle");
}
}
}
}
}
}
}
}
| gpl-3.0 |
ypcd/gstunnel | gstunnellib/gspackoper/compresser.go | 1320 | package gspackoper
import (
"bytes"
"compress/flate"
"io"
"log"
)
var logger *log.Logger
func init() {
logger = log.Default()
}
type compresser struct {
fewriter *flate.Writer
fereader io.ReadCloser
}
func NewCompresser() *compresser {
return &compresser{}
}
func (ap *compresser) compress2(data []byte) []byte { return data }
func (ap *compresser) uncompress2(data []byte) []byte { return data }
func (ap *compresser) compress(data []byte) []byte {
var b bytes.Buffer
if ap.fewriter == nil {
zw, err := flate.NewWriter(&b, 1)
ap.fewriter = zw
if err != nil {
logger.Fatalln(err)
}
} else {
ap.fewriter.Reset(&b)
}
zw := ap.fewriter
if _, err := io.Copy(zw, bytes.NewReader(data)); err != nil {
logger.Fatalln(err)
}
if err := zw.Close(); err != nil {
logger.Fatalln(err)
}
return b.Bytes()
}
func (ap *compresser) uncompress(data []byte) []byte {
var b bytes.Buffer
if ap.fereader == nil {
zr := flate.NewReader(bytes.NewReader(data))
ap.fereader = zr
} else {
zr := ap.fereader
if err := zr.(flate.Resetter).Reset(bytes.NewReader(data), nil); err != nil {
logger.Fatalln(err)
}
}
zr := ap.fereader
if _, err := io.Copy(&b, zr); err != nil {
logger.Fatalln(err)
}
if err := zr.Close(); err != nil {
logger.Fatalln(err)
}
return b.Bytes()
}
| gpl-3.0 |
ilixi/ilixi | apps/monitor/Monitor.cpp | 7049 | /*
Copyright 2010, 2011 Tarik Sekmen.
All Rights Reserved.
Written by Tarik Sekmen <tarik@ilixi.org>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Monitor.h"
#include <ui/VBoxLayout.h>
#include <ui/HBoxLayout.h>
#include <ui/GridLayout.h>
#include <ui/GroupBox.h>
#include <ui/TabPanel.h>
#include <ui/Icon.h>
#include <ui/ScrollArea.h>
#include <ui/Spacer.h>
#include <sstream>
#include "ilixiConfig.h"
template<class T>
inline std::string
toString(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
Monitor::Monitor(int argc, char* argv[])
: Application(&argc, &argv)
{
setMargin(15);
setBackgroundImage(ILIXI_DATADIR"images/ilixi_bg.jpg");
_cpuMon = new CPUMonitor();
_cpuMon->refresh();
_fsMon = new FSMonitor();
_fsMon->refresh();
_memMon = new MEMMonitor();
_memMon->refresh();
_netMon = new NETMonitor();
_netMon->refresh();
_osMon = new OSMonitor();
_osMon->refresh();
setLayout(new VBoxLayout());
TabPanel* tabPanel = new TabPanel();
addWidget(tabPanel);
//**************************************
VBoxLayout* overviewLayout = new VBoxLayout();
tabPanel->addTab(overviewLayout, "Overview");
_uptime = new Label("Uptime: " + _osMon->getUptime());
overviewLayout->addWidget(_uptime);
overviewLayout->addWidget(new Label("System: " + _osMon->getSysName()));
overviewLayout->addWidget(new Label("Node: " + _osMon->getNodeName()));
overviewLayout->addWidget(new Label("Release: " + _osMon->getRelease()));
overviewLayout->addWidget(new Label("Version: " + _osMon->getVersion()));
overviewLayout->addWidget(new Label("Machine: " + _osMon->getMachine()));
overviewLayout->addWidget(new Label("CPU Vendor: " + _cpuMon->getVendor()));
overviewLayout->addWidget(new Label("CPU Model: " + _cpuMon->getModel()));
overviewLayout->addWidget(new Label("CPU Cores: " + toString(_cpuMon->getCpuCores())));
overviewLayout->addWidget(new Label("CPU Cache: " + toString(_cpuMon->getCacheSize()) + " KB"));
overviewLayout->addWidget(new Label("Processes: " + _cpuMon->getProcesses()));
overviewLayout->addWidget(new Spacer(Vertical));
//****************************************************************************
GridLayout* fm = new GridLayout(3, 2);
tabPanel->addTab(fm, "Resources");
GroupBox* memGroup = new GroupBox("Memory");
memGroup->setTitleIcon(StyleHint::RAM);
// memGroup->setYConstraint(FixedConstraint);
memGroup->setLayout(new VBoxLayout());
fm->addWidget(memGroup);
memGroup->addWidget(new Label("Total: " + toString(_memMon->getTotal()) + " MB"));
memGroup->addWidget(new Label("Cached: " + toString(_memMon->getCached()) + " MB"));
memGroup->addWidget(new Label("Free: " + toString(_memMon->getFree()) + " MB"));
memGroup->addWidget(new Label("Buffers: " + toString(_memMon->getBuffers()) + " MB"));
memGroup->addWidget(new Spacer(Vertical));
memGroup->addWidget(new Label("Usage:"));
_memUsage = new ProgressBar();
memGroup->addWidget(_memUsage);
//**************************************
GroupBox* fsGroup = new GroupBox("File System");
fsGroup->setTitleIcon(StyleHint::File);
// fsGroup->setYConstraint(FixedConstraint);
fsGroup->setLayout(new VBoxLayout());
fm->addWidget(fsGroup);
fsGroup->addWidget(new Label("Total: " + toString(_fsMon->getTotal()) + " GB"));
fsGroup->addWidget(new Label("Free: " + toString(_fsMon->getFree()) + " GB"));
fsGroup->addWidget(new Spacer(Vertical));
fsGroup->addWidget(new Label("Usage:"));
_fsUsage = new ProgressBar();
fsGroup->addWidget(_fsUsage);
//**************************************
GroupBox* netGroup = new GroupBox("Network");
netGroup->setTitleIcon(StyleHint::Network);
// netGroup->setYConstraint(FixedConstraint);
VBoxLayout* netGroupLayout = new VBoxLayout();
netGroup->setLayout(netGroupLayout);
fm->addWidget(netGroup);
_netRXC = new Label("Receiving:" + _netMon->getReceiving());
netGroup->addWidget(_netRXC);
_netTXC = new Label("Sending:" + _netMon->getTransmitting());
netGroup->addWidget(_netTXC);
_netRXT = new Label("Total Received:" + _netMon->getTotalReceived());
netGroup->addWidget(_netRXT);
_netTXT = new Label("Total Sent:" + _netMon->getTotalTransmitted());
netGroup->addWidget(_netTXT);
netGroup->addWidget(new Spacer(Vertical));
//**************************************
GroupBox* cpuGroup = new GroupBox("CPU");
cpuGroup->setTitleIcon(StyleHint::CPU);
VBoxLayout* cpuGroupLayout = new VBoxLayout();
cpuGroup->setLayout(cpuGroupLayout);
fm->addWidget(cpuGroup);
cpuGroupLayout->addWidget(new Label("Idle:"));
_cpuIdle = new ProgressBar();
cpuGroupLayout->addWidget(_cpuIdle);
_cpuChart = new BarChart();
char core[10];
for (unsigned int i = 0; i < _cpuMon->getCpuCores(); ++i)
{
snprintf(core, 10, "Core %d", i);
_cpuChart->addBar(core, Color(rand() % 255, rand() % 255, rand() % 255));
}
cpuGroupLayout->addWidget(_cpuChart);
// fm->addWidget(new Spacer(Vertical));
//****************************************************************************
_monitorTimer = new Timer();
_monitorTimer->sigExec.connect(sigc::mem_fun(this, &Monitor::updateMonitor));
_monitorTimer->start(1000);
}
Monitor::~Monitor()
{
delete _monitorTimer;
delete _cpuMon;
delete _fsMon;
delete _memMon;
delete _netMon;
delete _osMon;
}
void
Monitor::updateMonitor()
{
_cpuMon->refresh();
_fsMon->refresh();
_memMon->refresh();
_netMon->refresh();
_osMon->refresh();
_uptime->setText("Uptime: " + _osMon->getUptime());
_fsUsage->setValue(_fsMon->getUsage());
_memUsage->setValue(_memMon->getUsage());
_netRXC->setText("Receiving:" + _netMon->getReceiving());
_netTXC->setText("Sending:" + _netMon->getTransmitting());
_netRXT->setText("Total Received:" + _netMon->getTotalReceived());
_netTXT->setText("Total Sent:" + _netMon->getTotalTransmitted());
for (unsigned int i = 0; i < _cpuMon->getCpuCores(); ++i)
_cpuChart->addValue(i, _cpuMon->getCpu(i + 1).getUsage());
_cpuIdle->setValue(_cpuMon->getCpu(0).getIdle());
}
int
main(int argc, char* argv[])
{
Monitor app(argc, argv);
app.exec();
return 0;
}
| gpl-3.0 |
lostjared/ats | system/func_continue.cpp | 337 | #include"function.hpp"
#include"code.hpp"
namespace token {
void token_Continue(const std::string &cmd, std::vector<lex::Token> &tokens) {
if(code.instruct.size()==0) {
std::cerr << "Error: requires you run build first.\n";
return;
}
code.cont();
}
}
| gpl-3.0 |
swissfondue/gtta | js/mxgraph/src/js/shape/mxLine.js | 5391 | /**
* $Id: mxLine.js,v 1.36 2012-03-30 04:44:59 gaudenz Exp $
* Copyright (c) 2006-2010, JGraph Ltd
*/
/**
* Class: mxLine
*
* Extends <mxShape> to implement a horizontal line shape.
* This shape is registered under <mxConstants.SHAPE_LINE> in
* <mxCellRenderer>.
*
* Constructor: mxLine
*
* Constructs a new line shape.
*
* Parameters:
*
* bounds - <mxRectangle> that defines the bounds. This is stored in
* <mxShape.bounds>.
* stroke - String that defines the stroke color. Default is 'black'. This is
* stored in <stroke>.
* strokewidth - Optional integer that defines the stroke width. Default is
* 1. This is stored in <strokewidth>.
*/
function mxLine(bounds, stroke, strokewidth)
{
this.bounds = bounds;
this.stroke = stroke;
this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};
/**
* Extends mxShape.
*/
mxLine.prototype = new mxShape();
mxLine.prototype.constructor = mxLine;
/**
* Variable: vmlNodes
*
* Adds local references to <mxShape.vmlNodes>.
*/
mxLine.prototype.vmlNodes = mxLine.prototype.vmlNodes.concat(['label', 'innerNode']);
/**
* Variable: mixedModeHtml
*
* Overrides the parent value with false, meaning it will
* draw in VML in mixed Html mode.
*/
mxLine.prototype.mixedModeHtml = false;
/**
* Variable: preferModeHtml
*
* Overrides the parent value with false, meaning it will
* draw as VML in prefer Html mode.
*/
mxLine.prototype.preferModeHtml = false;
/**
* Function: clone
*
* Overrides the clone method to add special fields.
*/
mxLine.prototype.clone = function()
{
var clone = new mxLine(this.bounds,
this.stroke, this.strokewidth);
clone.isDashed = this.isDashed;
return clone;
};
/**
* Function: createVml
*
* Creates and returns the VML node to represent this shape.
*/
mxLine.prototype.createVml = function()
{
var node = document.createElement('v:group');
node.style.position = 'absolute';
// Represents the text label container
this.label = document.createElement('v:rect');
this.label.style.position = 'absolute';
this.label.stroked = 'false';
this.label.filled = 'false';
node.appendChild(this.label);
// Represents the straight line shape
this.innerNode = document.createElement('v:shape');
this.configureVmlShape(this.innerNode);
node.appendChild(this.innerNode);
return node;
};
/**
* Function: redrawVml
*
* Redraws this VML shape by invoking <updateVmlShape> on this.node.
*/
mxLine.prototype.reconfigure = function()
{
if (mxUtils.isVml(this.node))
{
this.configureVmlShape(this.innerNode);
}
else
{
mxShape.prototype.reconfigure.apply(this, arguments);
}
};
/**
* Function: redrawVml
*
* Updates the VML node(s) to reflect the latest bounds and scale.
*/
mxLine.prototype.redrawVml = function()
{
this.updateVmlShape(this.node);
this.updateVmlShape(this.label);
this.innerNode.coordsize = this.node.coordsize;
this.innerNode.strokeweight = (this.strokewidth * this.scale) + 'px';
this.innerNode.style.width = this.node.style.width;
this.innerNode.style.height = this.node.style.height;
var w = this.bounds.width;
var h =this.bounds.height;
if (this.direction == mxConstants.DIRECTION_NORTH ||
this.direction == mxConstants.DIRECTION_SOUTH)
{
this.innerNode.path = 'm ' + Math.round(w / 2) + ' 0' +
' l ' + Math.round(w / 2) + ' ' + Math.round(h) + ' e';
}
else
{
this.innerNode.path = 'm 0 ' + Math.round(h / 2) +
' l ' + Math.round(w) + ' ' + Math.round(h / 2) + ' e';
}
};
/**
* Function: createSvg
*
* Creates and returns the SVG node(s) to represent this shape.
*/
mxLine.prototype.createSvg = function()
{
var g = this.createSvgGroup('path');
// Creates an invisible shape around the path for easier
// selection with the mouse. Note: Firefox does not ignore
// the value of the stroke attribute for pointer-events: stroke.
// It does, however, ignore the visibility attribute.
this.pipe = this.createSvgPipe();
g.appendChild(this.pipe);
return g;
};
/**
* Function: redrawSvg
*
* Updates the SVG node(s) to reflect the latest bounds and scale.
*/
mxLine.prototype.redrawSvg = function()
{
var strokeWidth = Math.round(Math.max(1, this.strokewidth * this.scale));
this.innerNode.setAttribute('stroke-width', strokeWidth);
if (this.bounds != null)
{
var x = this.bounds.x;
var y = this.bounds.y;
var w = this.bounds.width;
var h = this.bounds.height;
var d = null;
if (this.direction == mxConstants.DIRECTION_NORTH || this.direction == mxConstants.DIRECTION_SOUTH)
{
d = 'M ' + Math.round(x + w / 2) + ' ' + Math.round(y) + ' L ' + Math.round(x + w / 2) + ' ' + Math.round(y + h);
}
else
{
d = 'M ' + Math.round(x) + ' ' + Math.round(y + h / 2) + ' L ' + Math.round(x + w) + ' ' + Math.round(y + h / 2);
}
this.innerNode.setAttribute('d', d);
this.pipe.setAttribute('d', d);
this.pipe.setAttribute('stroke-width', this.strokewidth + mxShape.prototype.SVG_STROKE_TOLERANCE);
this.updateSvgTransform(this.innerNode, false);
this.updateSvgTransform(this.pipe, false);
if (this.crisp)
{
this.innerNode.setAttribute('shape-rendering', 'crispEdges');
}
else
{
this.innerNode.removeAttribute('shape-rendering');
}
if (this.isDashed)
{
var phase = Math.max(1, Math.round(3 * this.scale * this.strokewidth));
this.innerNode.setAttribute('stroke-dasharray', phase + ' ' + phase);
}
}
};
| gpl-3.0 |
eungtony/ProjetS4 | laravel/app/Http/Middleware/Owner.php | 1258 | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
class Owner
{
public $auth;
public function __construct(Guard $auth){
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
$controller_name = explode('@', $request->route()->getAction()['uses'])['0'];
$controller = app($controller_name);
$reflection_method = new \ReflectionMethod($controller_name, 'getResource');
$resource = $reflection_method->invokeArgs($controller, $request->route()->parameters());
if ($resource->user_id != $this->auth->user()->id) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/home')->with('error', "Vous n'avez pas accès à cette page !");
}
}
$request->route()->setParameter($request->route()->parameterNames()['0'], $resource);
return $next($request);
}
}
| gpl-3.0 |
fga-gpp-mds/2016.1-Emergo | EmerGo/app/src/androidTest/java/unlv/erc/emergo/controller/EmergencyContactControllerTest.java | 9579 | package unlv.erc.emergo.controller;
import android.support.test.espresso.Espresso;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.test.ActivityInstrumentationTestCase2;
import org.junit.Before;
import unlv.erc.emergo.R;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
public class EmergencyContactControllerTest extends ActivityInstrumentationTestCase2<EmergencyContactController>{
private UiDevice device;
public EmergencyContactControllerTest() {
super(EmergencyContactController.class);
}
@Before
public void setUp() throws Exception{
super.setUp();
getActivity();
device = UiDevice.getInstance(getInstrumentation());
}
public void testSaveFirstContact(){
onView(withId(R.id.saveButtonFirstContact)).perform(click());
onView(withId(R.id.saveButtonFirstContact)).check(matches(withText("Salvar")));
}
public void testNameFirstContactIsEmpty(){
onView(withId(R.id.nameFirstContactEditText)).perform(typeText(""));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
}
public void testNameFirstContactIsLessThanThree(){
onView(withId(R.id.nameFirstContactEditText)).perform(typeText("Mr"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
}
public void testUpdateFirstContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameFirstContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
onView(withId(R.id.updateButtonFirstContact)).perform(click());
onView(withId(R.id.nameFirstContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
onView(withId(R.id.deleteFirstContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testDeleteFirstContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameFirstContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
onView(withId(R.id.updateButtonFirstContact)).perform(click());
onView(withId(R.id.nameFirstContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveButtonFirstContact)).perform(click());
onView(withId(R.id.deleteFirstContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testSaveSecondContactOption(){
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.saveSecondContactButton)).check(matches(withText("Salvar")));
}
public void testNameSecondContactIsEmpty(){
onView(withId(R.id.nameSecondContactEditText)).perform(typeText(""));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
}
public void testSaveSecondContactIsLessThanThree(){
onView(withId(R.id.nameSecondContactEditText)).perform(typeText("Mr"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.saveSecondContactButton)).check(matches(withText("Salvar")));
}
public void testUpdateSecondContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameSecondContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneSecondContactEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.updateSecondContactButton)).perform(click());
onView(withId(R.id.nameSecondContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneSecondContactEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.deleteSecondContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testDeleteSecondContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameSecondContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneSecondContactEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.updateSecondContactButton)).perform(click());
onView(withId(R.id.nameSecondContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneSecondContactEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveSecondContactButton)).perform(click());
onView(withId(R.id.deleteSecondContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testSaveThirdContactOption(){
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.saveThirdContactButton)).check(matches(withText("Salvar")));
}
public void testNameThirdContactIsEmpty(){
onView(withId(R.id.nameThirdContactEditText)).perform(typeText(""));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
}
public void testSaveThirdContactIsLessThanThree(){
onView(withId(R.id.nameThirdContactEditText)).perform(typeText("Mr"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.saveThirdContactButton)).check(matches(withText("Salvar")));
}
public void testUpdateThirdContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameThirdContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneThirdContactEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.updateThirdContactButton)).perform(click());
onView(withId(R.id.nameThirdContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneThirdContactEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.deleteThirdContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testDeleteThirdContactOption() throws UiObjectNotFoundException {
onView(withId(R.id.nameThirdContactEditText)).perform(typeText("MrVictor"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneThirdContactEditText)).perform(typeText("(61)83104981"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.updateThirdContactButton)).perform(click());
onView(withId(R.id.nameThirdContactEditText)).perform(typeText("Naiara Gatinha"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.phoneThirdContactEditText)).perform(typeText("(42)14031912"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.saveThirdContactButton)).perform(click());
onView(withId(R.id.deleteThirdContactButton)).perform(click());
UiObject button = device.findObject(new UiSelector().text("Sim"));
button.click();
}
public void testButtonConfig(){
onView(withId(R.id.iconMenu)).perform(click());
}
public void testButtonMap(){
onView(withId(R.id.iconMap)).perform(click());
}
}
| gpl-3.0 |
a-v-k/astrid | src/main/java/com/todoroo/astrid/dao/Database.java | 11666 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.SqlConstructorVisitor;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.StoreObject;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.TaskAttachment;
import com.todoroo.astrid.data.TaskListMetadata;
import com.todoroo.astrid.data.UserActivity;
import com.todoroo.astrid.provider.Astrid2TaskProvider;
import com.todoroo.astrid.provider.Astrid3ContentProvider;
import org.tasks.analytics.Tracker;
import org.tasks.injection.ForApplication;
import javax.inject.Inject;
import javax.inject.Singleton;
import timber.log.Timber;
/**
* Database wrapper
*
* @author Tim Su <tim@todoroo.com>
*
*/
@Singleton
public class Database {
private static final int VERSION = 36;
private static final String NAME = "database";
private static final Table[] TABLES = new Table[] {
Task.TABLE,
Metadata.TABLE,
StoreObject.TABLE,
TagData.TABLE,
UserActivity.TABLE,
TaskAttachment.TABLE,
TaskListMetadata.TABLE,
};
private final SQLiteOpenHelper helper;
private final Context context;
private final Tracker tracker;
private SQLiteDatabase database;
// --- listeners
@Inject
public Database(@ForApplication Context context, Tracker tracker) {
this.context = context;
this.tracker = tracker;
helper = new DatabaseHelper(context, getName(), VERSION);
}
// --- implementation
public String getName() {
return NAME;
}
/**
* Create indices
*/
private void onCreateTables() {
StringBuilder sql = new StringBuilder();
sql.append("CREATE INDEX IF NOT EXISTS md_tid ON ").
append(Metadata.TABLE).append('(').
append(Metadata.TASK.name).
append(')');
database.execSQL(sql.toString());
sql.setLength(0);
sql.append("CREATE INDEX IF NOT EXISTS md_tkid ON ").
append(Metadata.TABLE).append('(').
append(Metadata.TASK.name).append(',').
append(Metadata.KEY.name).
append(')');
database.execSQL(sql.toString());
sql.setLength(0);
sql.append("CREATE INDEX IF NOT EXISTS so_id ON ").
append(StoreObject.TABLE).append('(').
append(StoreObject.TYPE.name).append(',').
append(StoreObject.ITEM.name).
append(')');
database.execSQL(sql.toString());
sql.setLength(0);
sql.append("CREATE UNIQUE INDEX IF NOT EXISTS t_rid ON ").
append(Task.TABLE).append('(').
append(Task.UUID.name).
append(')');
database.execSQL(sql.toString());
sql.setLength(0);
}
private boolean onUpgrade(int oldVersion, int newVersion) {
SqlConstructorVisitor visitor = new SqlConstructorVisitor();
switch(oldVersion) {
case 35:
try {
tryExecSQL(addColumnSql(TagData.TABLE, TagData.COLOR, visitor, "-1"));
} catch (SQLiteException e) {
tracker.reportException(e);
}
return true;
}
return false;
}
private void tryExecSQL(String sql) {
try {
database.execSQL(sql);
} catch (SQLiteException e) {
Timber.e(e, "SQL Error: " + sql);
}
}
private static String addColumnSql(Table table, Property<?> property, SqlConstructorVisitor visitor, String defaultValue) {
StringBuilder builder = new StringBuilder();
builder.append("ALTER TABLE ")
.append(table.name)
.append(" ADD ")
.append(property.accept(visitor, null));
if (!TextUtils.isEmpty(defaultValue)) {
builder.append(" DEFAULT ").append(defaultValue);
}
return builder.toString();
}
private void tryAddColumn(Table table, Property<?> column, String defaultValue) {
try {
SqlConstructorVisitor visitor = new SqlConstructorVisitor();
String sql = "ALTER TABLE " + table.name + " ADD " + //$NON-NLS-1$//$NON-NLS-2$
column.accept(visitor, null);
if (!TextUtils.isEmpty(defaultValue)) {
sql += " DEFAULT " + defaultValue;
}
database.execSQL(sql);
} catch (SQLiteException e) {
// ignored, column already exists
Timber.e(e, e.getMessage());
}
}
private String createTableSql(SqlConstructorVisitor visitor,
String tableName, Property<?>[] properties) {
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE IF NOT EXISTS ").append(tableName).append('(').
append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT");
for(Property<?> property : properties) {
if(AbstractModel.ID_PROPERTY.name.equals(property.name)) {
continue;
}
sql.append(',').append(property.accept(visitor, null));
}
sql.append(')');
return sql.toString();
}
private void onDatabaseUpdated() {
Astrid2TaskProvider.notifyDatabaseModification(context);
Astrid3ContentProvider.notifyDatabaseModification(context);
}
/**
* Return the name of the table containing these models
*/
public final Table getTable(Class<? extends AbstractModel> modelType) {
for(Table table : TABLES) {
if(table.modelClass.equals(modelType)) {
return table;
}
}
throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$
}
/**
* Open the database for writing. Must be closed afterwards. If user is
* out of disk space, database may be opened for reading instead
*/
public synchronized final void openForWriting() {
if(database != null && !database.isReadOnly() && database.isOpen()) {
return;
}
try {
database = helper.getWritableDatabase();
} catch (NullPointerException e) {
Timber.e(e, e.getMessage());
throw new IllegalStateException(e);
} catch (final RuntimeException original) {
Timber.e(original, original.getMessage());
try {
// provide read-only database
openForReading();
} catch (Exception readException) {
Timber.e(readException, readException.getMessage());
// throw original write exception
throw original;
}
}
}
/**
* Open the database for reading. Must be closed afterwards
*/
public synchronized final void openForReading() {
if(database != null && database.isOpen()) {
return;
}
database = helper.getReadableDatabase();
}
/**
* Close the database if it has been opened previously
*/
public synchronized final void close() {
if(database != null) {
database.close();
}
database = null;
}
/**
* @return sql database. opens database if not yet open
*/
public synchronized final SQLiteDatabase getDatabase() {
if(database == null) {
AndroidUtilities.sleepDeep(300L);
openForWriting();
}
return database;
}
/**
* @return human-readable database name for debugging
*/
@Override
public String toString() {
return "DB:" + getName();
}
// --- database wrapper
public Cursor rawQuery(String sql) {
return getDatabase().rawQuery(sql, null);
}
public long insert(String table, String nullColumnHack, ContentValues values) {
long result;
try {
result = getDatabase().insertOrThrow(table, nullColumnHack, values);
} catch (SQLiteConstraintException e) { // Throw these exceptions
throw e;
} catch (Exception e) { // Suppress others
Timber.e(e, e.getMessage());
result = -1;
}
onDatabaseUpdated();
return result;
}
public int delete(String table, String whereClause, String[] whereArgs) {
int result = getDatabase().delete(table, whereClause, whereArgs);
onDatabaseUpdated();
return result;
}
public int update(String table, ContentValues values, String whereClause) {
int result = getDatabase().update(table, values, whereClause, null);
onDatabaseUpdated();
return result;
}
// --- helper classes
/**
* Default implementation of Astrid database helper
*/
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, int version) {
super(context, name, null, version);
}
/**
* Called to create the database tables
*/
@Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor();
// create tables
for(Table table : TABLES) {
sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('(').
append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT");
for(Property<?> property : table.getProperties()) {
if(AbstractModel.ID_PROPERTY.name.equals(property.name)) {
continue;
}
sql.append(',').append(property.accept(sqlVisitor, null));
}
sql.append(')');
db.execSQL(sql.toString());
sql.setLength(0);
}
// post-table-creation
database = db;
onCreateTables();
}
/**
* Called to upgrade the database to a new version
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Timber.i("Upgrading database from version %s to %s", oldVersion, newVersion);
database = db;
try {
if(!Database.this.onUpgrade(oldVersion, newVersion)) {
// We don't know how to handle this case because someone forgot to
// implement the upgrade. We can't drop tables, we can only
// throw a nasty exception at this time
throw new IllegalStateException("Missing database migration " +
"from " + oldVersion + " to " + newVersion);
}
} catch (Exception e) {
Timber.e(e, "database-upgrade-%s-%s-%s", getName(), oldVersion, newVersion);
}
}
}
}
| gpl-3.0 |
rconfig/rconfig | www/install/dbinstall.php | 3306 | <?php
require('includes/head.php');
?>
<div id="content">
<h2>Database Setup</h2>
<h3>Settings</h3>
<hr/>
<div id="section">
<div id="notes">
<p>
Please complete the form with your Database server settings
</p>
<p>
If you need to modify these settings later, you will have to update includes/config.inc.php file manually
</p>
</div>
<div id="items">
<div class="cell">
<ul>
<li><label><strong>Database Server</strong></label></li>
<li><label><strong>Database Port</strong></label></li>
<li><label><strong>Database Name</strong></label></li>
<li><label><strong>Database Username</strong></label></li>
<li><label><strong>Database Password</strong></label></li>
</ul>
</div>
<div class="cellinside">
<ul>
<li><input type="text" id="dbServer" name="dbServer" placeholder="x.x.x.x / hostname"></li>
<li><input type="text" id="dbPort" name="dbPort" value="3306"></li>
<li><input type="text" id="dbName" name="dbName" placeholder="my_Database"></li>
<li><input type="text" id="dbUsername" name="dbUsername" placeholder="username"></li>
<li><input type="password" id="dbPassword" name="dbPassword" placeholder="password"></li>
</ul>
</div>
</div>
</div>
<div class="clear"></div>
<h3>Verify Settings</h3>
<hr/>
<div id="section">
<div id="notes">
<p>
Please click the 'check settings' button before installation to ensure settings are valid
</p>
<div id="chkDbSettingsBtn"><a href="#javascript:void(0);" onclick="getStatus();">Check Settings</a></div>
</div>
<div id="items">
<div class="cell">
<ul>
<li><label><strong>Database Server/Port</strong></label><span id="dbServerPortTest"></span></li>
<li><label><strong>Database Credentials</strong></label><span id="dbNameTest"></span></li>
<li><label><strong>Database Name</strong></label><span id="dbCredTest"></span></li>
</ul>
</div>
</div>
</div>
<div class="clear"></div><br/><br/>
<h3>Install Configuration Settings</h3>
<hr/>
<div id="section">
<div id="notes">
<div id="chkDbSettingsBtn"><a href="#javascript:void(0);" onclick="installConfig();">Install Database</a></div>
</div>
<div id="items">
<div class="cellinside">
<ul>
<li><div id="msg"><br/></div></li>
</ul>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<!-- JS script Include -->
<script type="text/JavaScript" src="js/dbinstall.js"></script>
<div id="footer">
<div id="footerNav">
<div id="last"><a href="license.php"><< Last</a></div>
<div id="next"><a href="finalcheck.php">Next >></a></div>
</div>
</div>
</div>
</body>
</html> | gpl-3.0 |
sephiroth2029/SpringTests | logging-filter/src/main/java/com/gmmr/springcore/loggingfilter/configuration/WebConfig.java | 1332 | package com.gmmr.springcore.loggingfilter.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
/**
* Created by Giovanni on 08/08/2017.
*
* The profiled configuration. If the active profile is "regular" there won't be logging; if
* it's "logged" the request/response will be logged.
*/
@Configuration
public class WebConfig {
public static final String PROFILE_REGULAR = "regular";
public static final String PROFILE_LOGGED = "logged";
@Bean
@Profile(PROFILE_REGULAR)
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
@Bean
@Profile(PROFILE_LOGGED)
public RestTemplate loggedRestTemplate() {
RestTemplate restTemplate = new RestTemplate(
new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
restTemplate.setInterceptors(Arrays.asList(new MyLogInterceptor()));
return restTemplate;
}
}
| gpl-3.0 |
jpmac26/PGE-Project | Editor/tools/external_tools/lazyfixtool_gui.cpp | 3936 | /*
* Platformer Game Engine by Wohlstand, a free platform for game making
* Copyright (c) 2014-2016 Vitaly Novichkov <admin@wohlnet.ru>
*
* 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 <QMessageBox>
#include <QFileDialog>
#include <common_features/app_path.h>
#include <dev_console/devconsole.h>
#include "lazyfixtool_gui.h"
#include <ui_lazyfixtool_gui.h>
LazyFixTool_gui::LazyFixTool_gui(QWidget *parent) :
QDialog(parent),
ui(new Ui::LazyFixTool_gui)
{
connect(&proc, SIGNAL(readyReadStandardOutput()),this, SLOT(consoleMessage()) );
ui->setupUi(this);
}
LazyFixTool_gui::~LazyFixTool_gui()
{
disconnect(&proc, SIGNAL(readyReadStandardOutput()),this, SLOT(consoleMessage()) );
delete ui;
}
void LazyFixTool_gui::on_BrowseInput_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Open Source Directory"),
(ui->inputDir->text().isEmpty() ? ApplicationPath : ui->inputDir->text()),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if(dir.isEmpty()) return;
ui->inputDir->setText(dir);
}
void LazyFixTool_gui::on_BrowseOutput_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Open Target Directory"),
(ui->outputDir->text().isEmpty() ? ApplicationPath : ui->outputDir->text()),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if(dir.isEmpty()) return;
ui->outputDir->setText(dir);
}
void LazyFixTool_gui::on_startTool_clicked()
{
if(ui->inputDir->text().isEmpty())
{
QMessageBox::warning(this, tr("Source directory is not set"), tr("Please, set the source directory"), QMessageBox::Ok);
return;
}
QString command;
if(proc.state()==QProcess::Running)
return;
#ifdef _WIN32
command = ApplicationPath+"/LazyFixTool.exe";
#else
command = ApplicationPath+"/LazyFixTool";
#endif
if(!QFile(command).exists())
{
QMessageBox::warning(this, tr("Tool not found"), tr("Can't run application:\n%1\nPlease, check the application directory and make sure it is installed properly.").arg(command), QMessageBox::Ok);
return;
}
QStringList args;
if(!ui->outputDir->text().isEmpty())
{
args << "--output";
args << ui->outputDir->text();
}
if(ui->WalkSubDirs->isChecked())
args << "-d";
if(ui->noBackUp->isChecked())
args << "-n";
args << "--";
args << ui->inputDir->text();
DevConsole::show();
DevConsole::log("Ready>>>", "LazyFix Tool");
DevConsole::log("----------------------------------", "LazyFix Tool", true);
proc.waitForFinished(1);
proc.start(command, args);
//connect(proc, SIGNAL(readyReadStandardError()), this, SLOT(consoleMessage()) );
}
void LazyFixTool_gui::consoleMessage()
{
QByteArray strdata = proc.readAllStandardOutput();
QString out = QString::fromUtf8(strdata);
#ifdef Q_OS_WIN
out.remove('\r');
#endif
DevConsole::log(out, "LazyFix Tool");
}
void LazyFixTool_gui::on_close_clicked()
{
this->close();
}
| gpl-3.0 |
arvidn/libsimulator | src/io_service.cpp | 6988 | /*
Copyright (c) 2015, Arvid Norberg
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 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 "simulator/simulator.hpp"
#include <boost/make_shared.hpp>
#include <boost/system/error_code.hpp>
namespace sim { namespace asio {
io_context::io_context(sim::simulation& sim)
: io_context(sim, std::vector<asio::ip::address>())
{}
io_context::io_context(sim::simulation& sim, asio::ip::address const& ip)
: io_context(sim, std::vector<asio::ip::address>{ip})
{}
io_context::io_context(sim::simulation& sim, std::vector<asio::ip::address> const& ips)
: m_sim(sim)
, m_ips(ips)
, m_stopped(false)
{
for (auto const& ip : m_ips)
{
m_outgoing_route[ip] = m_sim.config().outgoing_route(ip);
m_incoming_route[ip] = m_sim.config().incoming_route(ip);
}
m_sim.add_io_service(this);
}
io_context::~io_context()
{
m_sim.remove_io_service(this);
}
io_context::io_context(std::size_t)
: m_sim(*reinterpret_cast<sim::simulation*>(0))
{
assert(false);
}
int io_context::get_path_mtu(const asio::ip::address& source, const asio::ip::address& dest) const
{
// TODO: it would be nice to actually traverse the virtual network nodes
// and ask for their MTU instead
assert(std::count(m_ips.begin(), m_ips.end(), source) > 0 && "source address must be a local address to this node/io_context");
return m_sim.config().path_mtu(source, dest);
}
void io_context::stop()
{
// TODO: cancel all outstanding handler associated with this io_context
m_stopped = true;
}
bool io_context::stopped() const
{
return m_stopped;
}
void io_context::restart()
{
m_stopped = false;
}
std::size_t io_context::run()
{
assert(false);
return 0;
}
std::size_t io_context::run(boost::system::error_code&)
{
assert(false);
return 0;
}
std::size_t io_context::poll()
{
assert(false);
return 0;
}
std::size_t io_context::poll(boost::system::error_code&)
{
assert(false);
return 0;
}
std::size_t io_context::poll_one()
{
assert(false);
return 0;
}
std::size_t io_context::poll_one(boost::system::error_code&)
{
assert(false);
return 0;
}
// private interface
void io_context::add_timer(high_resolution_timer* t)
{
m_sim.add_timer(t);
}
void io_context::remove_timer(high_resolution_timer* t)
{
m_sim.remove_timer(t);
}
boost::asio::io_context& io_context::get_internal_service()
{ return m_sim.get_internal_service(); }
ip::tcp::endpoint io_context::bind_socket(ip::tcp::socket* socket
, ip::tcp::endpoint ep, boost::system::error_code& ec)
{
assert(!m_ips.empty() && "you cannot use an internal io_context (one without an IP address) for creating and binding sockets");
if (ep.address() == ip::address_v4::any())
{
auto it = std::find_if(m_ips.begin(), m_ips.end()
, [](ip::address const& ip) { return ip.is_v4(); } );
if (it == m_ips.end())
{
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::tcp::endpoint();
}
// TODO: pick the first local endpoint for now. In the future we may
// want have a bias toward
ep.address(*it);
}
else if (ep.address() == ip::address_v6::any())
{
auto it = std::find_if(m_ips.begin(), m_ips.end()
, [](ip::address const& ip) { return ip.is_v6(); } );
if (it == m_ips.end())
{
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::tcp::endpoint();
}
// TODO: pick the first local endpoint for now. In the future we may
// want have a bias toward
ep.address(*it);
}
else if (std::count(m_ips.begin(), m_ips.end(), ep.address()) == 0)
{
// you can only bind to the IP assigned to this node.
// TODO: support loopback
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::tcp::endpoint();
}
return m_sim.bind_socket(socket, ep, ec);
}
void io_context::unbind_socket(ip::tcp::socket* socket
, const ip::tcp::endpoint& ep)
{
m_sim.unbind_socket(socket, ep);
}
void io_context::rebind_socket(asio::ip::tcp::socket* s, asio::ip::tcp::endpoint ep)
{
m_sim.rebind_socket(s, ep);
}
ip::udp::endpoint io_context::bind_udp_socket(ip::udp::socket* socket
, ip::udp::endpoint ep, boost::system::error_code& ec)
{
assert(!m_ips.empty() && "you cannot use an internal io_context (one without an IP address) for creating and binding sockets");
if (ep.address() == ip::address_v4::any())
{
auto it = std::find_if(m_ips.begin(), m_ips.end()
, [](ip::address const& ip) { return ip.is_v4(); });
if (it == m_ips.end())
{
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::udp::endpoint();
}
// TODO: pick the first local endpoint for now. In the future we may
// want have a bias toward
ep.address(*it);
}
else if (ep.address() == ip::address_v6::any())
{
auto it = std::find_if(m_ips.begin(), m_ips.end()
, [](ip::address const& ip) { return ip.is_v6(); });
if (it == m_ips.end())
{
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::udp::endpoint();
}
// TODO: pick the first local endpoint for now. In the future we may
// want have a bias toward
ep.address(*it);
}
else if (std::count(m_ips.begin(), m_ips.end(), ep.address()) == 0)
{
// you can only bind to the IP assigned to this node.
// TODO: support loopback
ec.assign(boost::system::errc::address_not_available
, boost::system::generic_category());
return ip::udp::endpoint();
}
return m_sim.bind_udp_socket(socket, ep, ec);
}
void io_context::unbind_udp_socket(ip::udp::socket* socket
, const ip::udp::endpoint& ep)
{
m_sim.unbind_udp_socket(socket, ep);
}
void io_context::rebind_udp_socket(asio::ip::udp::socket* socket, asio::ip::udp::endpoint ep)
{
m_sim.rebind_udp_socket(socket, ep);
}
std::shared_ptr<aux::channel> io_context::internal_connect(ip::tcp::socket* s
, ip::tcp::endpoint const& target, boost::system::error_code& ec)
{
return m_sim.internal_connect(s, target, ec);
}
route io_context::find_udp_socket(asio::ip::udp::socket const& socket
, ip::udp::endpoint const& ep)
{
return m_sim.find_udp_socket(socket, ep);
}
} // asio
} // sim
| gpl-3.0 |
Ostrich-Emulators/semtool | common/src/test/java/com/ostrichemulators/semtool/user/RemoteUserImplTest.java | 2043 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ostrichemulators.semtool.user;
import com.ostrichemulators.semtool.user.RemoteUserImpl;
import com.ostrichemulators.semtool.user.User.UserProperty;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author ryan
*/
public class RemoteUserImplTest {
public RemoteUserImplTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testAuthorInfo1() {
RemoteUserImpl rui = new RemoteUserImpl( "testuser" );
rui.setProperty( UserProperty.USER_ORG, "org");
rui.setProperty( UserProperty.USER_FULLNAME, "test name");
assertEquals( "test name, org", rui.getAuthorInfo() );
}
@Test
public void testAuthorInfo2() {
RemoteUserImpl rui = new RemoteUserImpl( "testuser" );
rui.setProperty( UserProperty.USER_ORG, "org");
rui.setProperty( UserProperty.USER_EMAIL, "test@name.com");
assertEquals( "<test@name.com> org", rui.getAuthorInfo() );
}
@Test
public void testAuthorInfo3() {
RemoteUserImpl rui = new RemoteUserImpl( "testuser" );
rui.setProperty( UserProperty.USER_FULLNAME, "test name");
rui.setProperty( UserProperty.USER_ORG, "org");
rui.setProperty( UserProperty.USER_EMAIL, "test@name.com");
assertEquals( "test name <test@name.com>, org", rui.getAuthorInfo() );
}
@Test
public void testAuthorInfo4() {
RemoteUserImpl rui = new RemoteUserImpl( "testuser" );
assertEquals( "testuser", rui.getAuthorInfo() );
}
@Test
public void testAuthorInfo5() {
RemoteUserImpl rui = new RemoteUserImpl( "testuser" );
rui.setProperty( UserProperty.USER_ORG, "org");
assertEquals( "org", rui.getAuthorInfo() );
}
}
| gpl-3.0 |
aidGer/aidGer | tests/de/aidger/model/validators/ValidatorTest.java | 2868 | /*
* This file is part of the aidGer project.
*
* Copyright (C) 2010-2013 The aidGer 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 de.aidger.model.validators;
import org.junit.Test;
import static org.junit.Assert.*;
import de.aidger.model.AbstractModel;
/**
* Tests the abstract Validator class.
*
* @author aidGer Team
*/
public class ValidatorTest {
/**
* Test of validate method, of class Validator.
*/
@Test
public void testValidate() {
System.out.println("validate");
ModelImpl model = new ModelImpl();
Validator valid = new ValidatorImpl(new String[] { "test", "name" });
assertTrue(valid.validate(model));
valid = new ValidatorImpl(new String[] { "notdefined" });
assertFalse(valid.validate(model));
}
/**
* Test of setMessage method, of class Validator.
*/
@Test
public void testSetMessage() {
System.out.println("setMessage");
ModelImpl model = new ModelImpl();
Validator valid = new ValidatorImpl(new String[] { "notdefined" });
valid.setMessage("Bla");
assertFalse(valid.validate(model));
assertEquals(model.getErrors().get(0), "notdefined Bla");
}
/**
* Test of getMessage method, of class Validator.
*/
@Test
public void testGetMessage() {
System.out.println("getMessage");
Validator valid = new ValidatorImpl(null);
valid.setMessage("Bla");
assertEquals("Bla", valid.getMessage());
}
public class ValidatorImpl extends Validator {
public ValidatorImpl(String[] members) {
super(members, members);
}
public boolean validateVar(Object o) {
if (o instanceof String && ((String) o).equals("Test")) {
return true;
}
return false;
}
}
public class ModelImpl extends AbstractModel<ModelImpl> {
public String test = "Test";
protected String name = "Test";
@Override
public ModelImpl clone() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getName() {
return name;
}
}
}
| gpl-3.0 |
choperlizer/Dojima | dojima/model/ot/__init__.py | 1221 | # Dojima, a markets client.
# Copyright (C) 2012 Emery Hemingway
#
# 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/>.
import otapi
from PyQt4 import QtCore
class OTBaseModel(QtCore.QAbstractTableModel):
COLUMNS = 2
ID, NAME = list(range(COLUMNS))
def columnCount(self, parent=None):
if parent and parent.isValid():
return 0
return self.COLUMNS
def parent(self):
return QtCore.QModelIndex()
def flags(self, index):
flags = super(OTBaseModel, self).flags(index)
if index.column == self.NAME:
flags |= QtCore.Qt.ItemIsEditable
return flags
| gpl-3.0 |
lionelliang/zico | zico-core/src/main/java/com/jitlogic/zico/core/eql/ast/EqlSymbol.java | 1510 | /**
* Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
* <p/>
* This 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.
* <p/>
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zico.core.eql.ast;
import com.jitlogic.zico.core.eql.EqlNodeVisitor;
import com.jitlogic.zorka.common.util.ZorkaUtil;
public class EqlSymbol extends EqlExpr {
private String name;
public EqlSymbol(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return this.name;
}
@Override
public boolean equals(Object obj) {
return obj instanceof EqlSymbol &&
ZorkaUtil.objEquals(((EqlSymbol) obj).getName(), name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public <T> T accept(EqlNodeVisitor<T> visitor) {
return visitor.visit(this);
}
}
| gpl-3.0 |
Dacktar13/Power_Storage-MC1.4.7 | common/powerstorage/client/ClientProxy.java | 392 | package powerstorage.client;
import net.minecraftforge.client.MinecraftForgeClient;
import powerstorage.CommonProxy;
public class ClientProxy extends CommonProxy {
@Override
public void registerRenderers() {
MinecraftForgeClient.preloadTexture(TEXTURE_ITEMS);
MinecraftForgeClient.preloadTexture(TEXTURE_BLOCKS);
}
} | gpl-3.0 |
duszekmestre/MassCo | src/Server/MassCo/MassCo.Data/GenericDbContext.cs | 1247 | using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Reflection;
namespace MassCo.Data
{
public class GenericDbContext : DbContext
{
private static bool created = false;
public GenericDbContext(DbContextOptions options)
: base(options)
{
if (!created)
{
Database.EnsureCreated();
created = true;
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var iEntityType = typeof(IEntity);
var modelAssembly = iEntityType.GetTypeInfo().Assembly;
var types = modelAssembly.GetTypes()
.Where(x => iEntityType.IsAssignableFrom(x) && x.GetTypeInfo().IsClass);
var method = typeof(ModelBuilder).GetMethods().First(m => m.Name == "Entity"
&& m.IsGenericMethodDefinition
&& m.GetParameters().Length == 0);
foreach (var type in types)
{
var genericMethod = method.MakeGenericMethod(type);
genericMethod.Invoke(modelBuilder, null);
}
base.OnModelCreating(modelBuilder);
}
}
} | gpl-3.0 |
ilovefox8/zhcrm | vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php | 1838 | <?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler\FingersCrossed;
/**
* Channel and Error level based monolog activation strategy. Allows to trigger activation
* based on level per channel. e.g. trigger activation on level 'ERROR' by default, except
* for records of the 'sql' channel; those should trigger activation on level 'WARN'.
*
* Example:
*
* <code>
* $activationStrategy = new ChannelLevelActivationStrategy(
* Logger::CRITICAL,
* array(
* 'request' => Logger::ALERT,
* 'sensitive' => Logger::ERROR,
* )
* );
* $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy);
* </code>
*
* @author Mike Meessen <netmikey@gmail.com>
*/
class ChannelLevelActivationStrategy implements ActivationStrategyInterface
{
private $defaultActionLevel;
private $channelToActionLevel;
/**
* @param int $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param array $categoryToActionLevel An array that maps channel names to action levels.
*/
public function __construct($defaultActionLevel, $channelToActionLevel = array())
{
$this->defaultActionLevel = $defaultActionLevel;
$this->channelToActionLevel = $channelToActionLevel;
}
public function isHandlerActivated(array $record)
{
if (isset($this->channelToActionLevel[$record['channel']])) {
return $record['level'] >= $this->channelToActionLevel[$record['channel']];
}
return $record['level'] >= $this->defaultActionLevel;
}
}
| gpl-3.0 |
robottitto/lab | apis/jsonplaceholder/src/app/app.routing.ts | 533 | import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { PostComponent } from './post/post.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent }, // Home
{ path: 'posts', component: PostComponent }, // Thing
{ path: '**', component: HomeComponent } // 404
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
| gpl-3.0 |
ltf/lab | jlab/namerank/src/main/java/ltf/namerank/lab/RankingTest.java | 8722 | package ltf.namerank.lab;
import com.alibaba.fastjson.JSON;
import com.hankcs.hanlp.dictionary.CoreSynonymDictionary;
import ltf.namerank.entity.WordFeeling;
import ltf.namerank.rank.*;
import ltf.namerank.rank.dictrank.meaning.SameMeaningFilter;
import ltf.namerank.rank.dictrank.meaning.SameMeaningRanker;
import ltf.namerank.rank.dictrank.pronounce.PronounceRank;
import ltf.namerank.rank.dictrank.pronounce.YinYunFilter;
import ltf.namerank.rank.dictrank.support.dict.HanYuDaCidian;
import ltf.namerank.rank.dictrank.support.dict.MdxtDict;
import ltf.namerank.rank.filter.BlacklistCharsFilter;
import ltf.namerank.rank.filter.ChainedFilter;
import ltf.namerank.rank.filter.LengthFilter;
import ltf.namerank.utils.LinesInFile;
import java.io.IOException;
import java.util.*;
import static ltf.namerank.rank.CachedRanker.cache;
import static ltf.namerank.utils.FileUtils.*;
import static ltf.namerank.utils.PathUtils.*;
/**
* @author ltf
* @since 6/29/16, 10:05 PM
*/
public class RankingTest {
private List<MdxtDict> dictList;
private List<RankItem> rankItems = new LinkedList<>();
private Ranker ranker;
private ChainedFilter filter;
private void initDicts() {
if (dictList == null) {
dictList = new ArrayList<>();
dictList.add(new HanYuDaCidian());
}
}
private void testNewDict() {
}
private void testWordFeeling() {
List<WordFeeling> wordFeelingList = null;
try {
wordFeelingList = JSON.parseArray(file2Str(getJsonHome() + "/wordfeeling"), WordFeeling.class);
} catch (IOException e) {
}
List<String> list = new ArrayList<>();
for (WordFeeling feeling : wordFeelingList) {
if (!( //"noun".equals(feeling.getProperty()) ||
// "verb".equals(feeling.getProperty()) ||
"adj".equals(feeling.getProperty()) ||
"adv".equals(feeling.getProperty())))
continue;
if (feeling.getPolar() == 1) {
//System.out.println(feeling.getWord());
list.add(feeling.getWord());
}
}
testWordUnion(list);
}
private void testWordUnion(List<String> list) {
//List<String> list = new ArrayList<>();
List<String> keys = new ArrayList<>();
try {
RankRecordList result = new RankRecordList();
//file2Lines(getRawHome() + "/buty-keywords.txt", list);
file2Lines(getRawHome() + "/buty-keywords.txt", keys);
for (String s : list) {
double score = CoreSynonymDictionary.distance(s, "美丽") * 100000;
score += CoreSynonymDictionary.distance(s, "漂亮") * 100000;
score += CoreSynonymDictionary.distance(s, "可爱") * 100000;
for (String k : keys) {
score += CoreSynonymDictionary.distance(s, k);
}
result.add(s, score);
}
result.sortAsc();
result.listDetails();
lines2File(result.getWordList(), getRawHome() + "/buty-keywords2.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
public void go() {
testNewDict();
//new HanYuDaCidian().listKeys();
//testWordFeeling();
// List<String> list = new ArrayList<>();
// try {
// file2Lines(getRawHome() + "/buty-keywords.txt", list);
// testWordUnion(list);
//
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// FileUtils.distinct(getNamesHome() + "/givenNames.txt");
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// FileUtils.distinct(getWordsHome() + "/positive.txt");
// FileUtils.distinct(getWordsHome() + "/negative.txt");
// } catch (IOException e) {
// e.printStackTrace();
// }
//HanyuXgXfCidian dict = new HanyuXgXfCidian();
//dict.listKeys();
//dict.debug();
// List<String> list = new ArrayList<>();
// try {
// file2Lines(getRawHome() + "/ranking4.txt", list);
// //
// String ignore = "姣娇";
// for (int i = list.size() - 1; i >= 0; i--) {
// //if (list.get(i).contains("淑")) list.remove(i);
// //if (list.get(i).contains("春")) list.remove(i);
// if (list.get(i).contains("妍")) list.remove(i);
// if (list.get(i).contains("馨")) list.remove(i);
// if (list.get(i).contains("雅")) list.remove(i);
// if (list.get(i).contains("快")) list.remove(i);
// if (list.get(i).contains("熙")) list.remove(i);
//
// for (char c: ignore.toCharArray()){
// if (list.get(i).contains(c+"")) list.remove(i);
// }
// }
//
// lines2File(list, getRawHome() + "/ranking4.txt");
//
// } catch (IOException e) {
// e.printStackTrace();
// }
//System.out.println(dict.getItemsMap().size());
//WordFeelingRank.getInstance().listItems();
try {
HanYuDaCidian hanYuDaCidian = new HanYuDaCidian();
CachedRanker cachedHanyuCidian = cache(hanYuDaCidian);
SameMeaningRanker sameMeaningRanker = new SameMeaningRanker();
AllCasesRanker allCasesRanker = new AllCasesRanker(
new SumRankers()
.addRanker(cache(sameMeaningRanker), 8)
.addRanker(cachedHanyuCidian, 4)
.addRanker(cache(new PronounceRank(cachedHanyuCidian)), 1)
);
ExistWordRanker existWordRanker = new ExistWordRanker(hanYuDaCidian);
// BihuaRanker bihuaRanker = new BihuaRanker()
// .addWantedChar('金', 100)
// .addWantedChar('水', 80);
ranker = new SumRankers()
.addRanker(allCasesRanker, 1)
.addRanker(existWordRanker, 1);
BlacklistCharsFilter blacklistCharsFilter = new BlacklistCharsFilter()
.addChars(getWordsHome() + "/fyignore.txt")
//.addChars(getWordsHome() + "/taboo_girl.txt")
//.addChars(getWordsHome() + "/gaopinzi.txt")
.addChars(getWordsHome() + "/badchars.txt");
filter = new ChainedFilter()
.add(new LengthFilter())
//.add(new WugeFilter())
.add(blacklistCharsFilter)
.add(new YinYunFilter())
.add(new SameMeaningFilter())
;
doRanking();
filter.printBannedCount();
} catch (IOException e) {
e.printStackTrace();
}
}
private Set<String> picked = new HashSet<>();
private static final String PICKED_LIST = getRawHome() + "/picked.txt";
private void doRanking() throws IOException {
RankSettings.reportMode = true;
if (RankSettings.reportMode && exists(PICKED_LIST)) file2Lines(PICKED_LIST, picked);
new LinesInFile(getNamesHome() + "/givenNames.txt").each(this::nameRanking);
//new LinesInFile(getWordsHome() + "/allWords.txt").each(this::nameRanking);
rankItems.sort(RankItem::descOrder);
StringBuilder sb = new StringBuilder();
for (RankItem item : rankItems) {
System.out.println(String.format("%s: %f", item.getKey(), item.getScore()));
sb.append(String.format("%s: %f", item.getKey(), item.getScore())).append("\n");
}
str2File(sb.toString(), getRawHome() + "/ranking.txt");
List<RankItem> genHtmlItems = new ArrayList<>();
for (int i = 0; i < (rankItems.size() < 2000 ? rankItems.size() : 2000); i++) {
genHtmlItems.add(rankItems.get(i));
}
if (RankSettings.reportMode) HtmlGenerator.gen(genHtmlItems, getRawHome() + "/test.htm");
}
private void nameRanking(String givenName) {
//if (filter.banned(givenName)) return;
if (RankSettings.reportMode && !picked.contains(givenName)) return;
//if (!"钰琦".equals(givenName)) return;
//if (givenName.length() == 2 && givenName.substring(0, 1).equals(givenName.substring(1))) {
RankItem item = new RankItem(givenName);
ranker.rank(item);
rankItems.add(item);
//for (MdxtDict dict : dictList) dict.rank(record);
//}
}
}
| gpl-3.0 |
RHamidR/XMPP-Client | src/libs/QXmpp/src/base/QXmppResultSet.cpp | 6730 | /*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Olivier Goffart <ogoffart@woboq.com>
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppConstants.h"
#include "QXmppResultSet.h"
#include "QXmppUtils.h"
#include <QDomElement>
#include <QDebug>
QXmppResultSetQuery::QXmppResultSetQuery()
: m_index (-1)
, m_max (-1)
{
}
/// Returns the maximum number of results.
///
/// \note -1 means no limit, 0 means no results are wanted.
///
int QXmppResultSetQuery::max() const
{
return m_max;
}
/// Sets the maximum number of results.
///
/// \note -1 means no limit, 0 means no results are wanted.
void QXmppResultSetQuery::setMax (int max)
{
m_max = max;
}
/// Returns the index for the first element in the page.
///
/// This is used for retrieving pages out of order.
int QXmppResultSetQuery::index() const
{
return m_index;
}
/// Sets the index for the first element in the page.
///
/// This is used for retrieving pages out of order.
void QXmppResultSetQuery::setIndex (int index)
{
m_index = index;
}
/// Returns the UID of the first result in the next page.
///
/// This is used for for paging backwards through results.
QString QXmppResultSetQuery::before() const
{
return m_before;
}
/// Sets the UID of the first result in the next page.
///
/// This is used for for paging backwards through results.
void QXmppResultSetQuery::setBefore (const QString& before)
{
m_before = before;
}
/// Returns the UID of the last result in the previous page.
///
/// This is used for for paging forwards through results.
QString QXmppResultSetQuery::after() const
{
return m_after;
}
/// Sets the UID of the last result in the previous page.
///
/// This is used for for paging forwards through results.
void QXmppResultSetQuery::setAfter (const QString& after)
{
m_after = after;
}
/// Returns true if no result set information is present.
bool QXmppResultSetQuery::isNull() const
{
return m_max == -1 && m_index == -1 && m_after.isNull() && m_before.isNull();
}
/// \cond
void QXmppResultSetQuery::parse (const QDomElement& element)
{
QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement ("set");
if (setElement.namespaceURI() == ns_rsm)
{
bool ok = false;
m_max = setElement.firstChildElement ("max").text().toInt (&ok);
if (!ok) m_max = -1;
m_after = setElement.firstChildElement ("after").text();
m_before = setElement.firstChildElement ("before").text();
m_index = setElement.firstChildElement ("index").text().toInt (&ok);
if (!ok) m_index = -1;
}
}
void QXmppResultSetQuery::toXml (QXmlStreamWriter *writer) const
{
if (isNull())
return;
writer->writeStartElement ("set");
writer->writeAttribute ("xmlns", ns_rsm);
if (m_max >= 0)
helperToXmlAddTextElement (writer, "max", QString::number (m_max));
if (!m_after.isNull())
helperToXmlAddTextElement (writer, "after", m_after);
if (!m_before.isNull())
helperToXmlAddTextElement (writer, "before", m_before);
if (m_index >= 0)
helperToXmlAddTextElement (writer, "index", QString::number (m_index));
writer->writeEndElement();
}
/// \endcond
QXmppResultSetReply::QXmppResultSetReply()
: m_count (-1)
, m_index (-1)
{
}
/// Returns the UID of the first result in the page.
QString QXmppResultSetReply::first() const
{
return m_first;
}
/// Sets the UID of the first result in the page.
void QXmppResultSetReply::setFirst (const QString& first)
{
m_first = first;
}
/// Returns the UID of the last result in the page.
QString QXmppResultSetReply::last() const
{
return m_last;
}
/// Sets the UID of the last result in the page.
void QXmppResultSetReply::setLast (const QString& last)
{
m_last = last;
}
/// Returns the total number of items in the set.
///
/// \note This may be an approximate count.
int QXmppResultSetReply::count() const
{
return m_count;
}
/// Sets the total number of items in the set.
///
/// \note This may be an approximate count.
void QXmppResultSetReply::setCount (int count)
{
m_count = count;
}
/// Returns the index for the first result in the page.
///
/// This is used for retrieving pages out of order.
///
/// \note This may be an approximate index.
int QXmppResultSetReply::index() const
{
return m_index;
}
/// Sets the index for the first result in the page.
///
/// This is used for retrieving pages out of order.
///
/// \note This may be an approximate index.
void QXmppResultSetReply::setIndex (int index)
{
m_index = index;
}
/// Returns true if no result set information is present.
bool QXmppResultSetReply::isNull() const
{
return m_count == -1 && m_index == -1 && m_first.isNull() && m_last.isNull();
}
/// \cond
void QXmppResultSetReply::parse (const QDomElement& element)
{
QDomElement setElement = (element.tagName() == "set") ? element : element.firstChildElement ("set");
if (setElement.namespaceURI() == ns_rsm)
{
m_count = setElement.firstChildElement ("count").text().toInt();
QDomElement firstElem = setElement.firstChildElement ("first");
m_first = firstElem.text();
bool ok = false;
m_index = firstElem.attribute ("index").toInt (&ok);
if (!ok) m_index = -1;
m_last = setElement.firstChildElement ("last").text();
}
}
void QXmppResultSetReply::toXml (QXmlStreamWriter *writer) const
{
if (isNull())
return;
writer->writeStartElement ("set");
writer->writeAttribute ("xmlns", ns_rsm);
if (!m_first.isNull() || m_index >= 0)
{
writer->writeStartElement ("first");
if (m_index >= 0)
writer->writeAttribute ("index", QString::number (m_index));
writer->writeCharacters (m_first);
writer->writeEndElement();
}
if (!m_last.isNull())
helperToXmlAddTextElement (writer, "last", m_last);
if (m_count >= 0)
helperToXmlAddTextElement (writer, "count", QString::number (m_count));
writer->writeEndElement();
}
/// \endcond
| gpl-3.0 |
OpenSilk/Orpheus | renderer-chromecast/src/main/java/org/opensilk/music/renderer/googlecast/ui/DevicePickerActivityModule.java | 871 | /*
* Copyright (c) 2015 OpenSilk Productions LLC
*
* 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.opensilk.music.renderer.googlecast.ui;
import dagger.Module;
/**
* Created by drew on 10/30/15.
*/
@Module
public class DevicePickerActivityModule {
}
| gpl-3.0 |
beezwax/WP-Publish-to-Apple-News | tests/exporter/components/test-class-heading.php | 746 | <?php
require_once __DIR__ . '/class-component-testcase.php';
use \Exporter\Components\Heading as Heading;
class Heading_Test extends Component_TestCase {
public function testInvalidInput() {
$component = new Heading( '<p>This is not a heading</p>', null,
$this->settings, $this->styles, $this->layouts );
$this->assertEquals(
null,
$component->to_array()
);
}
public function testValidInput() {
$component = new Heading( '<h1>This is a heading</h1>', null,
$this->settings, $this->styles, $this->layouts );
$json = $component->to_array();
$this->assertEquals( 'heading1', $json['role'] );
$this->assertEquals( 'This is a heading', $json['text'] );
$this->assertEquals( 'markdown', $json['format'] );
}
}
| gpl-3.0 |
danieljb/django-hybrid-filefield | hybrid_filefield/__init__.py | 903 | #
# Django Hybrid-FileField
# A combination of Django's FileField and FilePathField.
# Copyright (c) 2011, Daniel J. Becker
#
# This file is part of Django Hybrid-FileField.
#
# Django Hybrid-Filefield 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.
#
# Django Hybrid-FileField 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 Django Hybrid-FileField.
# If not, see <http://www.gnu.org/licenses/>.
#
VERSION = (0, 2, 0)
__version__ = '.'.join(map(str, VERSION))
| gpl-3.0 |
MakeWebsites/PHP | WordPress/Plugins/mdcuba-understrap/mdcuba-understrap.php | 7635 | <?php
/*
Plugin Name: Mdcuba-understrap
Description: Extensions to Understrap Builder WordPress theme (Español)
Version: 1.0
Author: Angel Utset
License: GPLv2
*/
//* Enqueue Lato Google font
/*add_action( 'wp_enqueue_scripts', 'cr_load_google_fonts' );
function cr_load_google_fonts() {
wp_enqueue_style( 'google-font-lato', '//fonts.googleapis.com/css?family=Lato:300,700', array(), CHILD_THEME_VERSION );
}*/
//Registering bootstrap
function mdc_registers () {
wp_enqueue_script( 'jquery' );
wp_enqueue_script('mdc-js', plugin_dir_url( __FILE__ ).'js/mdc.js');
//wp_register_script('vue-js', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
}
add_action('wp_enqueue_scripts', 'mdc_registers');
//Change post orders to ascendent
//function to modify default WordPress query
function mdc_custom_query( $query ) {
// Make sure we only modify the main query on the homepage
if( /*$query->is_main_query() &&*/ ! is_admin() ) {
// Set parameters to modify the query
$query->set( 'orderby', 'date' );
$query->set( 'order', 'ASC' );
//$query->set( 'posts_per_page', 1 );
$query->set( 'suppress_filters', 'true' );
}
}
// Hook our custom query function to the pre_get_posts
add_action( 'pre_get_posts', 'mdc_custom_query' );
//Adding to the content
function mdc_after_post_content($content){
if (is_single()) {
$ppost = '';
$npost = '';
$post_tags = get_the_tags();
if ( $post_tags ) {
$content .= '<b>Etiquetas:</b> <div class=".btn-group-justified" role="group" aria-label="Basic example">';
$etiquetas = '';
foreach( $post_tags as $tag ) {
$tagn = $tag->name;
//$etiquetas.= '<a class="btn btn-info btn-sm" href="'.get_tag_link( $tag ).'" title="Etiqueta: '.$tagn.'">'.$tagn.'</a> ';
$etiquetas.= '<button type="button" class="btn btn-outline-secondary btn-sm ml-1" data-toggle="tooltip" data-placement="top" title="Etiqueta: '.$tagn.'"><i>'.$tagn.'</i></button>';
}
$content .= $etiquetas.'</div><div class="divider"></div>';
}
// Next post
$next_post = get_next_post();
if (!empty($next_post)) {
$npostt = get_the_title( $next_post->ID );
$npostl = str_replace(' ', '-', get_permalink( $next_post->ID ));
$npost = '<a class="btn btn-primary btn-sm float-right" href="'.$npostl.'" title="'.$npostt.'">Siguiente entrada</a>';
}
// Previous post
$pre_post = get_previous_post();
if (!empty($pre_post)) {
$ppostt = get_the_title( $pre_post->ID );
$ppostl = str_replace(' ', '-', get_permalink( $pre_post->ID ));
$ppost = '<a class="btn btn-primary btn-sm" href="'.$ppostl.'" title="'.$ppostt.'">Entrada anterior</a>';
}
$content .= '<div class="row"><div class="col-6">'.$ppost.'</div><div class="col-6">'.$npost.'</div></div>';
}
return $content;
}
add_filter( "the_content", "mdc_after_post_content" );
//Change logo
function mdc_login_logo() {
?>
<style type="text/css">
body.login div#login h1 a {
background-image: url(https://memoriasdecuba.blog/wp-content/uploads/2020/04/memorias-de-cuba-icon.png);
padding-bottom: 30px;
}
</style>
<?php
} add_action( 'login_enqueue_scripts', 'mdc_login_logo' );
/*function mdc_blog_page_title() {
// if the current entry's ID matches with that of the Posts page..
if ( $id == $posts_page ) {
// set your new title here.
//if (has_post_thumbnail()) {
$title = 'Memoria: '.the_title();
//}
}
return $title;
}
add_filter( 'the_title', 'mdc_blog_page_title');*/
// Shortcodes
function mdc_divider() {
return '<div class="divider"></div>';
}
add_shortcode('divider', 'mdc_divider');
function c_bmodal ($attr, $content) {
$divm = $attr['divm']; //Name of the modal div - Compulsory
$hrefr = get_permalink()."#$divm";
$mtitle = $attr['mtitle']; // Modal title
//$content = esc_html($content);
$ppim = plugin_dir_url( __FILE__ ).'images/icon_info.gif';
if (isset($attr['mtitle'])) {
$bmh = <<<bmht
<div class="modal-header btn-primary">
<h4 class="modal-title">$mtitle</h4>
<button class="close" aria-hidden="true" style="color:white" type="btn btn-lg btn-filled" data-dismiss="modal">×</button>
</div>
bmht;
}
else
$bmh = null;
if (isset($attr['divm'])) {
$bmd = <<<bdivm
<img class="align-top" data-toggle="modal" data-target="#$divm" src="$ppim" title="Click para mas informacion">
<div class="modal fade" id="$divm">
<div class="modal-dialog">
<div class="modal-content">
$bmh
<div class="modal-body text-justify">
$content
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
bdivm;
}
else
$bmd = null;
return $bmd;
}
add_shortcode('bmodal', 'c_bmodal');
/// Includes additional PHP file
function mdc_include_func( $atts ) {
extract( shortcode_atts( array(
'include' => ''
), $atts ) );
$include = $atts['include'];
if ($include!='') { // Algo a incluir
$ppi = plugin_dir_path( __FILE__ ) .'mdc-includes/'.$include.'/';
$file = $ppi.$include.'.php';
ob_start(); // turn on output buffering
include_once($file);
$res = ob_get_contents();
ob_end_clean();
}
return $res;
}
add_shortcode( 'mdc_include', 'mdc_include_func' );
//Widgets
// Creating the widget
class wpb_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'cforecast',
// Widget name will appear in UI
'City Forecast',
// Widget description
array( 'description' => "Tomorrow's forecast for the selected city") //__( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
);
}
// Creating widget front-end
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
// This is where you run the code and display the output
echo "<h5>Pronóstico para mañana en <b>La Habana</b></h5>";
include_once (plugin_dir_path( __FILE__ ).'mdc-widgets/met-habana/met-habana.php');
echo $args['after_widget'];
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
/*else {
$title = //__( 'New title', 'wpb_widget_domain' );
}*/
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
// Class wpb_widget ends here
}
// Register and load the widget
function wpb_load_widget() {
register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );
?> | gpl-3.0 |
murilotimo/moodle | question/type/ddmarker/tests/helper.php | 10048 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test helpers for the drag-and-drop markers question type.
*
* @package qtype_ddmarker
* @copyright 2012 The Open University
* @author Jamie Pratt <me@jamiep.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Test helper class for the drag-and-drop markers question type.
*
* @copyright 2010 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_ddmarker_test_helper extends question_test_helper {
public function get_test_questions() {
return array('fox', 'maths', 'mkmap', 'zerodrag');
}
/**
* @return qtype_ddmarker_question
*/
public function make_ddmarker_question_fox() {
question_bank::load_question_definition_classes('ddmarker');
$dd = new qtype_ddmarker_question();
test_question_maker::initialise_a_question($dd);
$dd->name = 'Drag-and-drop markers question';
$dd->questiontext = 'The quick brown fox jumped over the lazy dog.';
$dd->generalfeedback = 'This sentence uses each letter of the alphabet.';
$dd->qtype = question_bank::get_qtype('ddmarker');
$dd->shufflechoices = true;
test_question_maker::set_standard_combined_feedback_fields($dd);
$dd->choices = $this->make_choice_structure(array(
new qtype_ddmarker_drag_item('quick', 1, 0, 1),
new qtype_ddmarker_drag_item('fox', 2, 0, 1),
new qtype_ddmarker_drag_item('lazy', 3, 0, 1)
));
$dd->places = $this->make_place_structure(array(
new qtype_ddmarker_drop_zone(1, 'circle', '50,50;50'),
new qtype_ddmarker_drop_zone(2, 'rectangle', '100,0;100,100'),
new qtype_ddmarker_drop_zone(3, 'polygon', '0,100;200,100;200,200;0,200')
));
$dd->rightchoices = array(1 => 1, 2 => 2, 3 => 3);
return $dd;
}
protected function make_choice_structure($choices) {
$choicestructure = array();
foreach ($choices as $choice) {
$group = $choice->choice_group();
if (!isset($choicestructure[$group])) {
$choicestructure[$group] = array();
}
$choicestructure[$group][$choice->no] = $choice;
}
return $choicestructure;
}
protected function make_place_structure($places) {
$placestructure = array();
foreach ($places as $place) {
$placestructure[$place->no] = $place;
}
return $placestructure;
}
/**
* @return qtype_ddmarker_question
*/
public function make_ddmarker_question_maths() {
question_bank::load_question_definition_classes('ddmarker');
$dd = new qtype_ddmarker_question();
test_question_maker::initialise_a_question($dd);
$dd->name = 'Drag-and-drop markers question';
$dd->questiontext = 'Fill in the operators to make this equation work: ';
$dd->generalfeedback = 'Hmmmm...';
$dd->qtype = question_bank::get_qtype('ddmarker');
$dd->shufflechoices = true;
test_question_maker::set_standard_combined_feedback_fields($dd);
$dd->choices = $this->make_choice_structure(array(
new qtype_ddmarker_drag_item('+', 1, 1, 0),
new qtype_ddmarker_drag_item('-', 2, 1, 0),
new qtype_ddmarker_drag_item('*', 3, 1, 0),
new qtype_ddmarker_drag_item('/', 4, 1, 0)
));
$dd->places = $this->make_place_structure(array(
new qtype_ddmarker_drop_zone(1, 'circle', '50,50;50'),
new qtype_ddmarker_drop_zone(2, 'rectangle', '100,0;100,100'),
new qtype_ddmarker_drop_zone(3, 'polygon', '0,100;100,100;100,200;0,200')
));
$dd->rightchoices = array(1 => 1, 2 => 1, 3 => 1);
return $dd;
}
/**
* @return stdClass date to create a ddmarkers question.
*/
public function get_ddmarker_question_form_data_mkmap() {
global $CFG, $USER;
$fromform = new stdClass();
$bgdraftitemid = 0;
file_prepare_draft_area($bgdraftitemid, null, null, null, null);
$fs = get_file_storage();
$filerecord = new stdClass();
$filerecord->contextid = context_user::instance($USER->id)->id;
$filerecord->component = 'user';
$filerecord->filearea = 'draft';
$filerecord->itemid = $bgdraftitemid;
$filerecord->filepath = '/';
$filerecord->filename = 'mkmap.png';
$fs->create_file_from_pathname($filerecord, $CFG->dirroot .
'/question/type/ddmarker/tests/fixtures/mkmap.png');
$fromform->name = 'Milton Keynes landmarks';
$fromform->questiontext = array(
'text' => 'Please place the markers on the map of Milton Keynes and be aware that '.
'there is more than one railway station.',
'format' => FORMAT_HTML,
);
$fromform->defaultmark = 1;
$fromform->generalfeedback = array(
'text' => 'The Open University is at the junction of Brickhill Street and Groveway. '.
'There are three railway stations, Wolverton, Milton Keynes Central and Bletchley.',
'format' => FORMAT_HTML,
);
$fromform->bgimage = $bgdraftitemid;
$fromform->shuffleanswers = 0;
$fromform->drags = array(
array('label' => 'OU', 'noofdrags' => 1),
array('label' => 'Railway station', 'noofdrags' => 3),
);
$fromform->drops = array(
array('shape' => 'Circle', 'coords' => '322,213;10', 'choice' => 1),
array('shape' => 'Circle', 'coords' => '144,84;10', 'choice' => 2),
array('shape' => 'Circle', 'coords' => '195,180;10', 'choice' => 2),
array('shape' => 'Circle', 'coords' => '267,302;10', 'choice' => 2),
);
test_question_maker::set_standard_combined_feedback_form_data($fromform);
$fromform->penalty = '0.3333333';
$fromform->hint = array(
array(
'text' => 'You are trying to place four markers on the map.',
'format' => FORMAT_HTML,
),
array(
'text' => 'You are trying to mark three railway stations.',
'format' => FORMAT_HTML,
),
);
$fromform->hintshownumcorrect = array(1, 1);
$fromform->hintclearwrong = array(0, 1);
$fromform->hintoptions = array(0, 1);
return $fromform;
}
/**
* Return the test data needed by the question generator (the data that
* would come from saving the editing form).
* @return stdClass date to create a ddmarkers question where one of the drag items has text '0'.
*/
public function get_ddmarker_question_form_data_zerodrag() {
global $CFG, $USER;
$fromform = new stdClass();
$bgdraftitemid = 0;
file_prepare_draft_area($bgdraftitemid, null, null, null, null);
$fs = get_file_storage();
$filerecord = new stdClass();
$filerecord->contextid = context_user::instance($USER->id)->id;
$filerecord->component = 'user';
$filerecord->filearea = 'draft';
$filerecord->itemid = $bgdraftitemid;
$filerecord->filepath = '/';
$filerecord->filename = 'mkmap.png';
$fs->create_file_from_pathname($filerecord, $CFG->dirroot .
'/question/type/ddmarker/tests/fixtures/mkmap.png');
$fromform->name = 'Drag digits';
$fromform->questiontext = array(
'text' => 'Put 0 in the left of the image, and 1 in the right.',
'format' => FORMAT_HTML,
);
$fromform->defaultmark = 2;
$fromform->generalfeedback = array(
'text' => '',
'format' => FORMAT_HTML,
);
$fromform->bgimage = $bgdraftitemid;
$fromform->shuffleanswers = 0;
$fromform->drags = array(
array('label' => '0', 'noofdrags' => 1),
array('label' => '1', 'noofdrags' => 1),
);
$fromform->drops = array(
array('shape' => 'Rectangle', 'coords' => '0,0;272,389', 'choice' => 1),
array('shape' => 'Rectangle', 'coords' => '272,0;272,389', 'choice' => 2),
);
test_question_maker::set_standard_combined_feedback_form_data($fromform);
$fromform->penalty = '0.3333333';
$fromform->hint = array(
array(
'text' => 'Hint 1.',
'format' => FORMAT_HTML,
),
array(
'text' => 'Hint 2.',
'format' => FORMAT_HTML,
),
);
$fromform->hintshownumcorrect = array(1, 1);
$fromform->hintclearwrong = array(0, 1);
$fromform->hintoptions = array(0, 1);
return $fromform;
}
}
| gpl-3.0 |
pierobonfada/pypsf | login/views.py | 303 | #! -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def index(request):
template = loader.get_template('login/index.html')
context = {}
return HttpResponse(template.render(context, request))
| gpl-3.0 |
ice-blaze/talent-linker | app/Providers/AuthServiceProvider.php | 616 | <?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
| gpl-3.0 |
TheTransitClock/transitime | transitclockApi/src/main/java/org/transitclock/api/data/ApiBlocksTerse.java | 1709 | /*
* This file is part of Transitime.org
*
* Transitime.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Transitime.org 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 Transitime.org . If not, see <http://www.gnu.org/licenses/>.
*/
package org.transitclock.api.data;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.transitclock.ipc.data.IpcBlock;
/**
* A list of terse blocks, without trip pattern or schedule info
*
* @author Michael Smith
*
*/
@XmlRootElement(name = "blocks")
public class ApiBlocksTerse {
@XmlElement(name = "block")
private List<ApiBlockTerse> blocksData;
/********************** Member Functions **************************/
/**
* Need a no-arg constructor for Jersey. Otherwise get really obtuse
* "MessageBodyWriter not found for media type=application/json" exception.
*/
protected ApiBlocksTerse() {
}
public ApiBlocksTerse(Collection<IpcBlock> blocks) {
blocksData = new ArrayList<ApiBlockTerse>(blocks.size());
for (IpcBlock block : blocks) {
blocksData.add(new ApiBlockTerse(block));
}
}
}
| gpl-3.0 |
aurenen/Chronica | chronica/settings.php | 5799 | <?php
/************************************************************
*
* (c) Chronica
* https://github.com/aurenen/chronica
*
* settings.php
*
* Manages script settings.
*
************************************************************/
require_once 'includes/connect.php';
require_once 'includes/util.php';
require_once 'includes/crud.php';
require_once 'includes/PasswordHash.php';
session_start();
if (!isset($_SESSION['login'])) {
header('Location: login.php');
exit();
}
// pull settings
$username = getSettings("username");
$email = getSettings("email");
$full_path = getSettings("full_path");
$full_url = getSettings("full_url");
$timezone = getSettings("timezone_offset");
$site_name = getSettings("site_name");
$entry_format = getSettings("entry_format");
// TODO: process settings
if (isset($_POST['save'])) {
$setting = true;
if ($_POST['password'] !== $_POST['password2']) {
$entry_msg .= '<div class="warning">Passwords do not match.</div>';
$setting = false;
}
if (strlen($_POST['password']) > 0 && strlen($_POST['password']) < 8) {
$entry_msg .= '<div class="warning">Password must be at least 8 characters.</div>';
$setting = false;
}
if (strpos($_POST['full_url'], 'http') !== 0) {
$entry_msg .= '<div class="warning">Please make sure the full url begins with http:// or https://</div>';
$setting = false;
}
$settings = array();
if ($_POST['username'] !== $username)
$settings['username'] = $_POST['username'];
if ($_POST['email'] !== $email)
$settings['email'] = $_POST['email'];
if ($_POST['full_path'] !== $full_path)
$settings['full_path'] = $_POST['full_path'];
if ($_POST['full_url'] !== $full_url)
$settings['full_url'] = $_POST['full_url'];
if ($_POST['timezone'] !== $timezone)
$settings['timezone_offset'] = $_POST['timezone'];
if ($_POST['site_name'] !== $site_name)
$settings['site_name'] = $_POST['site_name'];
if ($_POST['entry_format'] !== $entry_format)
$settings['entry_format'] = $_POST['entry_format'];
if (strlen($_POST['password']) > 0) {
// hash password before inserting into db
$hasher = new PasswordHash(8, FALSE);
$hash = $hasher->HashPassword( $_POST['password'] );
if (strlen($hash) < 20)
fail('Failed to hash new password');
unset($hasher);
$settings['password'] = $hash;
}
// process post if no issues
if ($setting) {
$success = editSettings($settings);
if ($success)
header('Location: settings.php?success=true');
}
}
require_once 'includes/admin_header.php';
?>
<h2>Settings</h2>
<p>
Enter anything you'd like to change. Leave password blank unless you'd like to change it.
Entry format is in <em>markdown</em> by default, only change if you absolutely need to.
Avoid editing old entries when you switch entry formats.
</p>
<?php echo $entry_msg;
if ($_GET['success'] == true)
echo '<div class="success">Settings successfully updated.</div>';
?>
<form action="settings.php" method="post">
<div class="form-row">
<label title="<?php echo $username['description']; ?>">Username</label>
<input type="text" name="username" value="<?php echo $username['set_value']; ?>">
</div>
<div class="form-row">
<label>Password</label>
<input type="password" name="password" value="" placeholder="enter only if changing">
</div>
<div class="form-row">
<label>Password again</label>
<input type="password" name="password2" value="" placeholder="enter only if changing">
</div>
<div class="form-row">
<label title="<?php echo $email['description']; ?>">Email</label>
<input type="text" name="email" value="<?php echo $email['set_value']; ?>">
</div>
<div class="form-row">
<label title="<?php echo $full_path['description']; ?>">Full Path</label>
<input type="text" name="full_path" value="<?php echo $full_path['set_value']; ?>">
</div>
<div class="form-row">
<label title="<?php echo $full_url['description']; ?>">Full URL</label>
<input type="text" name="full_url" value="<?php echo $full_url['set_value']; ?>">
</div>
<div class="form-row">
<label title="<?php echo $timezone['description']; ?>">Timezone Offset</label>
<input type="text" name="timezone" value="<?php echo $timezone['set_value']; ?>">
</div>
<div class="form-row">
<label title="<?php echo $site_name['description']; ?>">Site Name</label>
<input type="text" name="site_name" value="<?php echo $site_name['set_value']; ?>">
</div>
<div class="form-row">
<label title="<?php echo $entry_format['description']; ?>">Entry Format</label>
<label class="radio"><input type="radio" name="entry_format" value="markdown"<?php if ($entry_format['set_value'] == "markdown") echo " checked"; ?>> Markdown</label>
<label class="radio"><input type="radio" name="entry_format" value="html"<?php if ($entry_format['set_value'] == "html") echo " checked"; ?>> HTML</label>
</div>
<div class="form-row">
<input type="submit" name="save" value="Save">
</div>
</form>
<?php
require_once 'includes/admin_footer.php';
?> | gpl-3.0 |
cim--/colonia-database | resources/views/components/megashiplocation.blade.php | 145 | @if (is_object($location))
<a href="{{route('systems.show', $location->id)}}">
{{$location->displayName()}}
</a>
@else
{{$location}}
@endif
| gpl-3.0 |
PaintQuest/paintquest | src/deepstream/node_modules/deepstream.io/test/utils/read-messageSpec.js | 2225 | var Deepstream = require( '../../src/deepstream.io' );
describe( 'parses low level authData to simpler output', function() {
var message;
var parsedMessage;
beforeEach( function() {
message = {
topic: 'R',
action: 'CR',
data: [ 'RecordName', 1, 'data' ]
};
parsedMessage = {
isRecord: false,
isEvent: false,
isRPC: false,
isCreate: false,
isRead: false,
isChange: false,
isDelete: false,
isAck: false,
isSubscribe: false,
isUnsubscribe: false,
isRequest: false,
isRejection: false,
name: 'RecordName',
path: undefined,
data: 'data'
};
});
it( 'parses RPC message correctly', function() {
message.topic = 'P';
message.action = '';
parsedMessage.isRPC = true;
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
it( 'parses Event message correctly', function() {
message.topic = 'E';
message.action = '';
parsedMessage.isEvent = true;
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
describe( 'when a record is recieved', function() {
beforeEach( function() {
parsedMessage.isRecord = true;
});
it( 'parses read/create message correctly', function() {
message.action = 'CR';
message.data = [ 'RecordName', 1, 'data' ];
parsedMessage.isCreate = true;
parsedMessage.isRead = true;
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
it( 'parses patch message correctly', function() {
message.action = 'P';
message.data = [ 'RecordName', 1, 'path', 'data' ];
parsedMessage.isChange = true;
parsedMessage.path = 'path';
parsedMessage.data = 'data';
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
it( 'returns record gets changed via update', function() {
message.action = 'U';
message.data = [ 'RecordName', 1, 'data' ];
parsedMessage.isChange = true;
parsedMessage.data = 'data';
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
it( 'returns record gets deleted', function() {
message.action = 'D';
parsedMessage.isDelete = true;
expect( Deepstream.readMessage( message ) ).toEqual( parsedMessage );
});
});
});
| gpl-3.0 |
mikusher/JavaBasico | src/cv/mikusher/outros/Calculos.java | 788 |
package cv.mikusher.outros;
/**
*
* @author Miky Mikusher
*/
public class Calculos {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Soma(3, 5);
multiplica(3, 2);
multiplica(-3, 2);
}
public static void Soma (int a, int b){
int c = a + b;
System.out.println(c);
}
public static int multiplica(int d1, int d2){
int cc = 0;
if (d1 > 0) {
cc = d1 * d2;
System.out.println("Primeiro if: "+cc);
} else {
cc = d2 * 2;
System.out.println("Segundo if: "+cc);
}
return cc;
}
}
| gpl-3.0 |
nunes0188/AspNetAulas | Aula250517/Aula250517/About.aspx.cs | 287 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Aula250517 {
public partial class About : Page {
protected void Page_Load(object sender, EventArgs e) {
}
}
} | gpl-3.0 |
hartwigmedical/hmftools | cuppa/src/main/java/com/hartwig/hmftools/cup/common/ResultType.java | 117 | package com.hartwig.hmftools.cup.common;
public enum ResultType
{
PERCENTILE,
PREVALENCE,
LIKELIHOOD;
}
| gpl-3.0 |
hungyao/context-toolkit | src/main/java/context/arch/comm/CommunicationsServer.java | 2806 | package context.arch.comm;
import java.net.Socket;
import context.arch.comm.protocol.ProtocolException;
import context.arch.comm.protocol.RequestData;
/**
* This interface specifies all the methods a CommunicationsServer object must support
* allowing the details of the specific protocol used to be abstracted away.
*
* @see context.arch.comm.CommunicationsObject
*/
public interface CommunicationsServer {
/**
* Abstract method to call when starting a CommunicationsServer object
*/
public abstract void start();
/**
* Abstract method to call when stopping a CommunicationsServer object
*/
public abstract void quit();
/**
* Abstract method to get the communications protocol being used
*
* @return the protocol being used
*/
public abstract String getProtocol();
/**
* This abstract method strips the protocol away from the received request
*
* @param socket The socket the request is being received on
* @return the request with the protocol stripped away
* @exception context.arch.comm.protocol.ProtocolException thrown if protocol can't be stripped away
* @see #addReplyProtocol(String)
* @see CommunicationsClient#addRequestProtocol(String,String)
* @see CommunicationsClient#stripReplyProtocol(java.net.Socket)
*/
public abstract RequestData stripRequestProtocol(Socket socket) throws ProtocolException;
/**
* This abstract method strips the protocol away from the received request
*
* @param reply The reply to add the protocol to
* @return the reply with the protocol added
* @exception context.arch.comm.protocol.ProtocolException thrown if protocol can't be added
* @see #stripRequestProtocol(java.net.Socket)
* @see CommunicationsClient#addRequestProtocol(String,String)
* @see CommunicationsClient#stripReplyProtocol(java.net.Socket)
*/
public abstract String addReplyProtocol(String reply) throws ProtocolException;
/**
* This abstract method handles incoming requests on a given socket
*
* @param socket The socket requests are coming in on
*/
public abstract void handleIncomingRequest(Socket socket);
/**
* This abstract method generates an error message if a request can't
* be handled properly, to the point where a contextual error message
* can still be sent as the reply
*
* @return DataObject containing the error message
* @see #getFatalMessage()
*/
public abstract DataObject getErrorMessage();
/**
* This abstract method generates an fatal message if a request can't
* be handled properly, to the point where no contextual error message
* can be sent as the reply
*
* @return String containing the fatal message
* @see #getErrorMessage()
*/
public abstract String getFatalMessage();
}
| gpl-3.0 |
wiwie/clustevalWebsite | clustevalWebsite/test/unit/run_configs_run_data_analysis_test.rb | 139 | require 'test_helper'
class RunConfigsRunDataAnalysisTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| gpl-3.0 |
mefcorvi/mirgames | MirGames/Infrastructure/UserSettings/HeaderType.cs | 1395 | // --------------------------------------------------------------------------------------------------------------------
// <copyright company="MirGames" file="HeaderType.cs">
// Copyright 2014 Bulat Aykaev
// This file is part of MirGames.
// MirGames 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.
// MirGames 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 MirGames. If not, see http://www.gnu.org/licenses/.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace MirGames.Infrastructure.UserSettings
{
/// <summary>
/// Type of the header.
/// </summary>
public enum HeaderType
{
/// <summary>
/// The fixed.
/// </summary>
Fixed,
/// <summary>
/// The static.
/// </summary>
Static,
/// <summary>
/// The automatic hide.
/// </summary>
AutoHide
}
} | gpl-3.0 |
sfotiadis/SEMonitor | src/main/Models/MetricsRecord.java | 2254 | package Models;
import java.util.Date;
public class MetricsRecord {
/**
* A data structure that holds the changes of the release
*/
private ChangeRecord changeRecord;
private int previousTotal;
private Date previousDate;
/**
* Constructor
* @param cr ChangeRecord
* @param prFun Previous total of changes
* @param prDate Previous date
*/
public MetricsRecord(ChangeRecord cr, int prTot, Date prDate) {
this.changeRecord = cr;
this.previousTotal = prTot;
this.previousDate = prDate;
}
public ChangeRecord getChangeRecord() {
return changeRecord;
}
public int getPreviousTotal() {
return previousTotal;
}
public Date getPreviousDate() {
return previousDate;
}
/**
* Return the total number of changes up to now
* @return
*/
public int getTotalNumber() {
return previousTotal + changeRecord.getAdditions() - changeRecord.getDeletions();
}
/**
* Returns the growth rate of changes for the current release
* @return
*/
public double getGrowthRate() {
return (double)(changeRecord.getAdditions() - changeRecord.getDeletions());
}
/**
* Returns the complexity of the current release
* If the additions are zero it divides by 1.
* @return
*/
public double getComplexity() {
double divider = changeRecord.getAdditions() > 0 ? (double)changeRecord.getAdditions() : 1;
return ((double)changeRecord.getChanges() + (double)changeRecord.getDeletions()) / divider;
}
/**
* Returns the task rate of the current release
* If the elapsed time is 0 returns zero
* @return
*/
public double getWorkRate() {
double allChanges = (double)(changeRecord.getChanges() + changeRecord.getDeletions() + changeRecord.getAdditions());
return getTimeSinceLastRelease() == 0 ? 0 : allChanges / getTimeSinceLastRelease();
}
/**
* Returns the elapsed time in days since the last release
*/
private double getTimeSinceLastRelease() {
double diff = changeRecord.getDate().getTime() - previousDate.getTime();
return diff / 1000.0 / 60.0 / 60.0 / 24.0;
}
@Override
public String toString() {
return "Total/Growth/Compl/TaskRate: " + getTotalNumber() + "," + getGrowthRate() + "," + getComplexity() +
"," + getWorkRate();
}
}
| gpl-3.0 |
0xFEEDC0DE64/PGTL-Programs | src/ninja/brunner/pgtl/program3/Wette.java | 385 | package ninja.brunner.pgtl.program3;
public class Wette {
public Person person;
public Rennen rennen;
public Schnecke schnecke;
public float einsatz;
public Wette(Person person, Rennen rennen, Schnecke schnecke, float einsatz) {
this.person = person;
this.rennen = rennen;
this.schnecke = schnecke;
this.einsatz = einsatz;
}
}
| gpl-3.0 |
TeddyDev/MCNetwork | Core/src/main/java/me/lukebingham/core/event/EventFactory.java | 561 | package me.lukebingham.core.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Created by LukeBingham on 23/03/2017.
*/
public abstract class EventFactory extends Event {
private static final HandlerList handlers = new HandlerList();
/**
* Construct a new Event
*/
public EventFactory(boolean async) {
super(async);
}
@Override
public final HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| gpl-3.0 |
mddorfli/leslie | leslie.server/src/test/java/org/leslie/server/vacation/VacationServiceTest.java | 1347 | package org.leslie.server.vacation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.eclipse.scout.rt.platform.BEANS;
import org.eclipse.scout.rt.testing.platform.runner.RunWithSubject;
import org.eclipse.scout.rt.testing.server.runner.RunWithServerSession;
import org.eclipse.scout.rt.testing.server.runner.ServerTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.leslie.server.ServerSession;
import org.leslie.shared.vacation.IVacationService;
import org.leslie.shared.vacation.VacationTablePageData;
import org.leslie.shared.vacation.VacationTablePageData.VacationTableRowData;
@RunWithSubject("mdo")
@RunWith(ServerTestRunner.class)
@RunWithServerSession(ServerSession.class)
public class VacationServiceTest {
@Test
public void testGetVacationTableData() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
VacationTablePageData result = BEANS.get(IVacationService.class).getVacationTableData(null);
assertEquals(1L, result.getRowCount());
VacationTableRowData row = result.getRows()[0];
assertNotNull(row);
assertEquals("Annual leave", row.getDescription());
assertEquals("2017-04-01", df.format(row.getFrom()));
assertEquals("2017-04-07", df.format(row.getTo()));
}
}
| gpl-3.0 |
ANKA-KIT/imageclient | imageclient/realtimecontainer.cpp | 7854 | #include "realtimecontainer.h"
#include <QDebug>
RealtimeContainer::RealtimeContainer(MainWindow *parent) : QWidget(parent)
{
windowElement = parent;
realtimeLast = 0;
setVisible(false);
emptyIcon = "/icons/true.png";
trueIcon = ":/icons/true.png";
QMenu *actSerSide = new QMenu("Server side operations", this);
actSerSideR = new QAction(QIcon(trueIcon),"Read", this);
actSerSideW = new QAction(QIcon(trueIcon),"Write", this);
actSerSide->setEnabled(false);
actSerSide->setIcon(QIcon(trueIcon));
actSerSide->addAction(actSerSideR);
actSerSide->addAction(actSerSideW);
serverMode =new QMenu(tr("&Server Mode"),this);
serverMode->setIcon(QIcon(emptyIcon));
actSerKeepSide = new QMenu("Server keeping side", this);
actSerKeepSideR = new QAction(QIcon(trueIcon),"Read", this);
actSerKeepSideW = new QAction(QIcon(trueIcon),"Write", this);
actSerKeepSide->setIcon(QIcon(trueIcon));
actSerKeepSide->addAction(actSerKeepSideR);
actSerKeepSide->addAction(actSerKeepSideW);
serverMode->addMenu(actSerKeepSide);
serverMode->addMenu(actSerSide);
actSerKeepSideW->setIconVisibleInMenu(false);
actSerKeepSideR->setIconVisibleInMenu(false);
actSerKeepSide->menuAction()->setIconVisibleInMenu(false);
actSerKeepSideR->setIcon(QIcon(emptyIcon));
actSerKeepSideW->setIcon(QIcon(emptyIcon));
actSerKeepSide->setIcon(QIcon(emptyIcon));
actSerSide->menuAction()->setIconVisibleInMenu(false);
actSerSide->setIcon(QIcon(emptyIcon));
actSerSideR->setIcon(QIcon(emptyIcon));
actSerSideW->setIcon(QIcon(emptyIcon));
actSerSideR->setIconVisibleInMenu(false);
actSerSideW->setIconVisibleInMenu(false);
actClientSide = new QAction(QIcon(trueIcon),"Client Mode", this);
actClientSide->setIconVisibleInMenu(true);
connect(actSerKeepSideR,SIGNAL(triggered()),SLOT(setServerModeR()));
connect(actSerKeepSideW,SIGNAL(triggered()),SLOT(setServerModeW()));
connect(actClientSide,SIGNAL(triggered()),SLOT(setClientSideMode()));
}
void RealtimeContainer::windowActivated(SubWindow* curRealtimeWin){
qDebug() << "MainWindow::SnapshotChanged -> activated " << curRealtimeWin;
RealtimeSubWindow* realtimeWindow = dynamic_cast<RealtimeSubWindow*>(curRealtimeWin);
if (!realtimeWindow) {
qDebug() << "Wrong window type passed. Doing nothing.";
return;
}
connect(realtimeWindow->tim, SIGNAL(mousePosition(QPoint)), windowElement, SLOT(curPosition(QPoint)), Qt::UniqueConnection);
connect(realtimeWindow->tim, SIGNAL(greyscaleImageColor(int)), windowElement, SLOT(curColor(int)), Qt::UniqueConnection);
connect(realtimeWindow->tim, SIGNAL(rgbImageColor(int, int, int)), windowElement, SLOT(curColor(int, int, int)), Qt::UniqueConnection);
realtimeLast = realtimeWindow;
setModeIcon();
}
void RealtimeContainer::windowDeactivated(SubWindow* curRealtimeWin){
qDebug() << "MainWindow::SnapshotChanged -> activated " << curRealtimeWin;
RealtimeSubWindow* realtimeWindow = dynamic_cast<RealtimeSubWindow*>(curRealtimeWin);
if (!realtimeWindow) {
qDebug() << "Wrong window type passed. Doing nothing.";
return;
}
disconnect(realtimeWindow->tim, SIGNAL(mousePosition(QPoint)), windowElement, SLOT(curPosition(QPoint)));
disconnect(realtimeWindow->tim, SIGNAL(greyscaleImageColor(int)), windowElement, SLOT(curColor(int)));
disconnect(realtimeWindow->tim, SIGNAL(rgbImageColor(int, int, int)), windowElement, SLOT(curColor(int, int, int)));
realtimeLast = 0;
}
void RealtimeContainer::onCloseRaltime(QObject *pointer){
qDebug("ERase Realsubwin");
}
void RealtimeContainer::setServerModeR(){
if (getRealtimeLastWin()) {
actClientSide->setIconVisibleInMenu(false);
actSerKeepSide->menuAction()->setIconVisibleInMenu(true);
actSerKeepSideR->setIconVisibleInMenu(true);
actSerKeepSideW->setIconVisibleInMenu(false);
serverMode->setIcon(QIcon(trueIcon));
actClientSide->setIcon(QIcon(emptyIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(trueIcon));
actSerKeepSideR->setIcon(QIcon(trueIcon));
actSerKeepSideW->setIcon(QIcon(emptyIcon));
RealtimeSubWindow *rt = getRealtimeLastWin();
rt->setServerModeRead(true);
if (rt->tim->__serverMode == TImage::SINGLE) setModeIcon();
}
}
void RealtimeContainer::setServerModeW(){
if (getRealtimeLastWin()) {
actClientSide->setIconVisibleInMenu(false);
actSerKeepSide->menuAction()->setIconVisibleInMenu(true);
actSerKeepSideR->setIconVisibleInMenu(false);
actSerKeepSideW->setIconVisibleInMenu(true);
serverMode->setIcon(QIcon(trueIcon));
actClientSide->setIcon(QIcon(emptyIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(trueIcon));
actSerKeepSideR->setIcon(QIcon(emptyIcon));
actSerKeepSideW->setIcon(QIcon(trueIcon));
RealtimeSubWindow *rt = getRealtimeLastWin();
rt->setServerModeWrite(true);
if (rt->tim->__serverMode == TImage::SINGLE) setModeIcon(); //in case incorect parameter value it will be Client Mode
}
}
void RealtimeContainer::setClientSideMode(){
if (getRealtimeLastWin()) {
actClientSide->setIconVisibleInMenu(true);
actSerKeepSide->menuAction()->setIconVisibleInMenu(false);
actSerKeepSideR->setIconVisibleInMenu(false);
actSerKeepSideW->setIconVisibleInMenu(false);
serverMode->setIcon(QIcon(emptyIcon));
actClientSide->setIcon(QIcon(trueIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(emptyIcon));
actSerKeepSideR->setIcon(QIcon(emptyIcon));
actSerKeepSideW->setIcon(QIcon(emptyIcon));
RealtimeSubWindow *rt = getRealtimeLastWin();
rt->setClientSideMode(true);
}
}
void RealtimeContainer::setModeIcon(){
if (getRealtimeLastWin()) {
switch(getRealtimeLastImage()->__serverMode){
case TImage::SINGLE:
actClientSide->setIconVisibleInMenu(true);
actSerKeepSide->menuAction()->setIconVisibleInMenu(false);
actSerKeepSideR->setIconVisibleInMenu(false);
actSerKeepSideW->setIconVisibleInMenu(false);
serverMode->setIcon(QIcon(emptyIcon));
actClientSide->setIcon(QIcon(trueIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(emptyIcon));
actSerKeepSideR->setIcon(QIcon(emptyIcon));
actSerKeepSideW->setIcon(QIcon(emptyIcon));
break;
case TImage::WRITE:
actClientSide->setIconVisibleInMenu(false);
actSerKeepSide->menuAction()->setIconVisibleInMenu(true);
actSerKeepSideR->setIconVisibleInMenu(false);
actSerKeepSideW->setIconVisibleInMenu(true);
serverMode->setIcon(QIcon(trueIcon));
actClientSide->setIcon(QIcon(emptyIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(trueIcon));
actSerKeepSideR->setIcon(QIcon(emptyIcon));
actSerKeepSideW->setIcon(QIcon(trueIcon));
break;
case TImage::READ:
actClientSide->setIconVisibleInMenu(false);
actSerKeepSide->menuAction()->setIconVisibleInMenu(true);
actSerKeepSideR->setIconVisibleInMenu(true);
actSerKeepSideW->setIconVisibleInMenu(false);
serverMode->setIcon(QIcon(trueIcon));
actClientSide->setIcon(QIcon(emptyIcon));
actSerKeepSide->menuAction()->setIcon(QIcon(trueIcon));
actSerKeepSideR->setIcon(QIcon(trueIcon));
actSerKeepSideW->setIcon(QIcon(emptyIcon));
break;
}
}
}
| gpl-3.0 |
IntelliPilot/IntelliPilot | IntelliCopter/battery_indicator.cpp | 1161 | //
// battery_indicator.cpp
// IntelliCopter
//
// Created by Daniel Heo on 2016. 7. 12.
// Copyright © 2016 http://dronix.kr. All rights reserved.
//
#include "System.h"
void System::Publish::battery(void *arg) {
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xWakePeriod = 60000 / portTICK_PERIOD_MS;
double batteryVoltageLast;
for (;; ) {
int _analogread = analogRead(A0);
batteryBox.voltages = _analogread * (3.3 / 1023.0);
batteryBox.remain.percents = (batteryBox.voltages / MAX_BATTERY_VOLTAGE) * 100;
batteryBox.remain.minutes = batteryBox.voltages / (batteryVoltageLast - batteryBox.voltages); //(batteryVoltageLast - batteryVoltage);
batteryVoltageLast = batteryBox.voltages;
#if (DEBUG_BATTERY == 1)
Serial.print("bat vol per:\t");
Serial.print(batteryBox.voltages);
Serial.print("\t");
Serial.println(batteryBox.remain.percents);
#endif
vTaskDelayUntil(&xLastWakeTime, xWakePeriod);
}
}
| gpl-3.0 |
diphda/grupoagrupo | lib/form/doctrine/PlaceForm.class.php | 290 | <?php
/**
* Place form.
*
* @package grupos_consumo
* @subpackage form
* @author info@diphda.net
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class PlaceForm extends BasePlaceForm
{
public function configure()
{
}
}
| gpl-3.0 |
DeOlSo/ADC2015_De | ClosedSequentialPatternMining/src/spmf/bide/SequentialPattern.java | 6389 | package spmf.bide;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* This class represents a sequential pattern.
* A sequential pattern is a list of itemsets.
*
* Copyright (c) 2008-2012 Philippe Fournier-Viger
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF 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.
*
* SPMF 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 SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
public class SequentialPattern implements Comparable<SequentialPattern>{
// the list of itemsets
private final List<Itemset> itemsets;
// private int id;
// IDs of sequences containing this pattern
private Set<Integer> sequencesIds;
private int itemCount = -1;
/**
* Set the set of IDs of sequence containing this prefix
* @param a set of integer containing sequence IDs
*/
public void setSequenceIDs(Set<Integer> sequencesIds) {
this.sequencesIds = sequencesIds;
}
/**
* Defaults constructor
*/
public SequentialPattern(){
itemsets = new ArrayList<Itemset>();
}
public SequentialPattern(Itemset itemset, Set<Integer> sequencesIds){
itemsets = new ArrayList<Itemset>();
this.itemsets.add(itemset);
this.sequencesIds = sequencesIds;
}
public SequentialPattern(List<Itemset> itemsets, Set<Integer> sequencesIds){
this.itemsets = itemsets;
this.sequencesIds = sequencesIds;
}
/**
* Get the relative support of this pattern (a percentage)
* @param sequencecount the number of sequences in the original database
* @return the support as a string
*/
public String getRelativeSupportFormated(int sequencecount) {
double relSupport = ((double)sequencesIds.size()) / ((double) sequencecount);
// pretty formating :
DecimalFormat format = new DecimalFormat();
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(5);
return format.format(relSupport);
}
/**
* Get the absolute support of this pattern.
* @return the support (an integer >= 1)
*/
public int getAbsoluteSupport(){
return sequencesIds.size();
}
/**
* Add an itemset to this sequential pattern
* @param itemset the itemset to be added
*/
public void addItemset(Itemset itemset) {
// itemCount += itemset.size();
itemsets.add(itemset);
}
/**
* Make a copy of this sequential pattern
* @return the copy.
*/
public SequentialPattern cloneSequence(){
// create a new empty sequential pattenr
SequentialPattern sequence = new SequentialPattern();
// for each itemset
for(Itemset itemset : itemsets){
// make a copy and add it
sequence.addItemset(itemset.cloneItemSet());
}
return sequence; // return the copy
}
/**
* Print this sequential pattern to System.out
*/
public void print() {
System.out.print(toString());
}
/**
* Get a string representation of this sequential pattern,
* containing the sequence IDs of sequence containing this pattern.
*/
public String toString() {
StringBuilder r = new StringBuilder("");
// For each itemset in this sequential pattern
for(Itemset itemset : itemsets){
r.append('('); // begining of an itemset
// For each item in the current itemset
for(Integer item : itemset.getItems()){
String string = item.toString();
r.append(string); // append the item
r.append(' ');
}
r.append(')');// end of an itemset
}
//
// // add the list of sequence IDs that contains this pattern.
// if(getSequencesID() != null){
// r.append(" Sequence ID: ");
// for(Integer id : getSequencesID()){
// r.append(id);
// r.append(' ');
// }
// }
return r.append(" ").toString();
}
/**
* Get a string representation of this sequential pattern.
*/
public String itemsetsToString() {
StringBuilder r = new StringBuilder("");
for(Itemset itemset : itemsets){
r.append('{');
for(Integer item : itemset.getItems()){
String string = item.toString();
r.append(string);
r.append(' ');
}
r.append('}');
}
return r.append(" ").toString();
}
/**
* Get the itemsets in this sequential pattern
* @return a list of itemsets.
*/
public List<Itemset> getItemsets() {
return itemsets;
}
/**
* Get an itemset at a given position.
* @param index the position
* @return the itemset
*/
public Itemset get(int index) {
return itemsets.get(index);
}
/**
* Get the ith item in this sequential pattern.
* @param i the position of the item.
* @return the item or null if the position does not exist.
*/
public Integer getIthItem(int i) {
// for each item
for(int j=0; j< itemsets.size(); j++){
// check if the position is in this itemset
if(i < itemsets.get(j).size()){
// if yes, return the item
return itemsets.get(j).get(i);
}
// otherwise subtract the size of this itemset
// from i.
i = i- itemsets.get(j).size();
}
return null; // if not found.
}
/**
* Get the number of itemsets in this sequential pattern.
* @return the number of itemsets.
*/
public int size(){
return itemsets.size();
}
/**
* Get the number of items in this pattern.
* Note that if an item appear twice, it will be counted twice.
* @return the number of items
*/
public int getItemOccurencesTotalCount(){
if(itemCount == -1) {
itemCount =0;
// for each itemset
for(Itemset itemset : itemsets){
// add the size of this itemset
itemCount += itemset.size();
}
}
return itemCount; // return the total size.
}
public Set<Integer> getSequenceIDs() {
// TODO Auto-generated method stub
return sequencesIds;
}
@Override
public int compareTo(SequentialPattern o) {
if(o == this){
return 0;
}
int compare = this.getAbsoluteSupport() - o.getAbsoluteSupport();
if(compare !=0){
return compare;
}
return this.hashCode() - o.hashCode();
}
}
| gpl-3.0 |
virani06/Opencart-Newsletter | catalog/model/module/newsletter.php | 1281 | <?php
class ModelModuleNewsletter extends Model
{
public function createNewslettersubscribe()
{
$query = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "newsletter_subscribe'");
$rows =$query->num_rows;
if ($rows == 0) {
$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "newsletter_subscribe`(`newsletter_id` int(11) NOT NULL AUTO_INCREMENT,`newsletter_email` varchar(255) NOT NULL,PRIMARY KEY (`newsletter_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
}
}
public function NewsletterSubscribes($data)
{
$res = $this->db->query("select * from " . DB_PREFIX . "newsletter_subscribe where newsletter_email='" . $data['email'] . "'");
if ($res->num_rows == 1) {
return "Email Already Exist";
} else {
$this->db->query("INSERT INTO " . DB_PREFIX . "newsletter_subscribe(newsletter_email) values ('" . $data['email'] . "')");
return "Subscription Success";
}
}
public function NewsletterDelete($data)
{
$this->db->query("DELETE FROM " . DB_PREFIX . "newsletter_subscribe WHERE newsletter_email = '" . $data['email'] . "'");
}
} | gpl-3.0 |
A1X71/twilight | SCA.WPF/SCA.DatabaseAccess/DBContext/LinkageConfigMixedDBService.cs | 8641 | using System.Collections.Generic;
using System.Text;
using System;
using SCA.Model;
using SCA.Interface.DatabaseAccess;
/* ==============================
*
* Author : William
* Create Date: 2017/5/3 8:49:14
* FileName : LinkageConfigMixedDBService
* Description:
* Version:V1
* ===============================
*/
namespace SCA.DatabaseAccess.DBContext
{
public class LinkageConfigMixedDBService:ILinkageConfigMixedDBService
{
private IDatabaseService _databaseService;
private IDBFileVersionService _dbFileVersionService;
public LinkageConfigMixedDBService(IDatabaseService databaseService)
{
_databaseService = databaseService;
}
public LinkageConfigMixedDBService(IDBFileVersionService dbFileVersionService)
{
_dbFileVersionService = dbFileVersionService;
}
public Model.LinkageConfigMixed GetMixedLinkageConfigInfo(int id)
{
throw new System.NotImplementedException();
}
public Model.LinkageConfigMixed GetMixedLinkageConfigInfo(Model.LinkageConfigMixed linkageConfigMixed)
{
throw new System.NotImplementedException();
}
public bool AddMixedLinkageConfigInfo(Model.LinkageConfigMixed linkageConfigMixed)
{
int intEffectiveRows = 0;
try
{
//StringBuilder sbSQL = new StringBuilder("REPLACE INTO LinkageConfigMixed(ID,Code, ActionCoefficient,ActionType, TypeA, LoopNoA, DeviceCodeA ,BuildingNoA,ZoneNoA , LayerNoA , DeviceTypeCodeA,TypeB,LoopNoB,DeviceCodeB,BuildingNoB ,ZoneNoB , LayerNoB , DeviceTypeCodeB ,TypeC ,MachineNoC,LoopNoC ,DeviceCodeC ,BuildingNoC ,ZoneNoC , LayerNoC ,DeviceTypeCodeC ,controllerID)");
//sbSQL.Append(" VALUES(");
//sbSQL.Append(linkageConfigMixed.ID + ",'");
//sbSQL.Append(linkageConfigMixed.Code + "','");
//sbSQL.Append(linkageConfigMixed.ActionCoefficient + "','");
//sbSQL.Append((int)linkageConfigMixed.ActionType + "','");
//sbSQL.Append((int)linkageConfigMixed.TypeA + "','");
//sbSQL.Append(linkageConfigMixed.LoopNoA + "','");
//sbSQL.Append(linkageConfigMixed.DeviceTypeCodeA + "','");
//sbSQL.Append(linkageConfigMixed.BuildingNoA + "','");
//sbSQL.Append(linkageConfigMixed.ZoneNoA + "','");
//sbSQL.Append(linkageConfigMixed.LayerNoA + "','");
//sbSQL.Append(linkageConfigMixed.DeviceTypeCodeA + "','");
//sbSQL.Append((int)linkageConfigMixed.TypeB + "','");
//sbSQL.Append(linkageConfigMixed.LoopNoB + "','");
//sbSQL.Append(linkageConfigMixed.DeviceCodeB + "','");
//sbSQL.Append(linkageConfigMixed.BuildingNoB + "','");
//sbSQL.Append(linkageConfigMixed.ZoneNoB + "','");
//sbSQL.Append(linkageConfigMixed.LayerNoB + "','");
//sbSQL.Append(linkageConfigMixed.DeviceTypeCodeB + "','");
//sbSQL.Append((int)linkageConfigMixed.TypeC + "','");
//sbSQL.Append(linkageConfigMixed.MachineNoC + "','");
//sbSQL.Append(linkageConfigMixed.LoopNoC + "','");
//sbSQL.Append(linkageConfigMixed.DeviceCodeC + "','");
//sbSQL.Append(linkageConfigMixed.BuildingNoC + "','");
//sbSQL.Append(linkageConfigMixed.ZoneNoC + "','");
//sbSQL.Append(linkageConfigMixed.LayerNoC + "','");
//sbSQL.Append(linkageConfigMixed.DeviceTypeCodeC + "',");
//sbSQL.Append(linkageConfigMixed.ControllerID + ");");
//intEffectiveRows = _databaseService.ExecuteBySql(sbSQL);
intEffectiveRows = _dbFileVersionService.AddMixedLinkageConfigInfo(linkageConfigMixed);
}
catch
{
intEffectiveRows = 0;
}
if (intEffectiveRows > 0)
{
return true;
}
else
{
return false;
}
}
public bool AddMixedLinkageConfigInfo(List<Model.LinkageConfigMixed> lstLinkageConfigMixed)
{
try
{
foreach (var linkageConfig in lstLinkageConfigMixed)
{
AddMixedLinkageConfigInfo(linkageConfig);
}
}
catch
{
return false;
}
return true;
}
public int UpdateMixedLinkageConfigInfo(Model.LinkageConfigMixed lstLinkageConfigMixed)
{
throw new System.NotImplementedException();
}
public bool DeleteMixedLinkageConfigInfo(int id)
{
if (_dbFileVersionService.DeleteMixedLinkageConfigInfo(id) > 0)
{
return true;
}
else
{
return false;
}
}
public List<LinkageConfigMixed> GetMixedLinkageConfigInfo(Model.ControllerModel controller)
{
//List<LinkageConfigMixed> lstData = new List<LinkageConfigMixed>();
//StringBuilder sbQuerySQL = new StringBuilder("select ID,Code, ActionCoefficient,ActionType, TypeA, LoopNoA, DeviceCodeA ,BuildingNoA,ZoneNoA , LayerNoA , DeviceTypeCodeA,TypeB,LoopNoB,DeviceCodeB,BuildingNoB ,ZoneNoB , LayerNoB , DeviceTypeCodeB ,TypeC ,MachineNoC,LoopNoC ,DeviceCodeC ,BuildingNoC ,ZoneNoC , LayerNoC ,DeviceTypeCodeC ,controllerID from LinkageConfigMixed where controllerID=" + controller.ID);
//System.Data.DataTable dt = _databaseService.GetDataTableBySQL(sbQuerySQL);
//for (int i = 0; i < dt.Rows.Count; i++)
//{
// LinkageConfigMixed model = new LinkageConfigMixed();
// model.ID = Convert.ToInt32(dt.Rows[i]["ID"]);
// model.Code = dt.Rows[i]["Code"].ToString();
// model.ActionCoefficient = Convert.ToInt32(dt.Rows[i]["ActionCoefficient"]);
// model.ActionType = (LinkageActionType)Enum.ToObject(typeof(LinkageActionType),Convert.ToInt16(dt.Rows[i]["ActionType"]));
// model.TypeA = (LinkageType)Enum.ToObject(typeof(LinkageType),Convert.ToInt16(dt.Rows[i]["TypeA"]));
// model.LoopNoA = dt.Rows[i]["LoopNoA"].ToString();
// model.DeviceTypeCodeA = Convert.ToInt16(dt.Rows[i]["DeviceTypeCodeA"]);
// model.BuildingNoA = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["BuildingNoA"]));
// model.ZoneNoA = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["ZoneNoA"]));
// model.LayerNoA = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["LayerNoA"]));
// model.DeviceTypeCodeA = Convert.ToInt16(dt.Rows[i]["DeviceTypeCodeA"]);
// model.TypeB = (LinkageType)Enum.ToObject(typeof(LinkageType), Convert.ToInt16(dt.Rows[i]["TypeB"]));
// model.LoopNoB = dt.Rows[i]["LoopNoB"].ToString();
// model.DeviceCodeB = dt.Rows[i]["DeviceCodeB"].ToString();
// model.BuildingNoB = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["BuildingNoB"]));
// model.ZoneNoB = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["ZoneNoB"]));
// model.LayerNoB = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["LayerNoB"]));
// model.DeviceTypeCodeB = Convert.ToInt16(dt.Rows[i]["DeviceTypeCodeB"]);
// model.TypeC = (LinkageType)Enum.ToObject(typeof(LinkageType), Convert.ToInt16(dt.Rows[i]["TypeC"]));
// model.MachineNoC = dt.Rows[i]["MachineNoC"].ToString();
// model.LoopNoC = dt.Rows[i]["LoopNoC"].ToString();
// model.DeviceCodeC = dt.Rows[i]["DeviceCodeC"].ToString();
// model.BuildingNoC = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["BuildingNoC"]));
// model.ZoneNoC = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["ZoneNoC"]));
// model.LayerNoC = new Nullable<Int16>(Convert.ToInt16(dt.Rows[i]["LayerNoC"]));
// model.DeviceTypeCodeC = Convert.ToInt16(dt.Rows[i]["DeviceTypeCodeC"]);
// model.Controller = controller;
// model.ControllerID = controller.ID;
// lstData.Add(model);
//}
//return lstData;
return _dbFileVersionService.GetMixedLinkageConfig(controller);
}
}
}
| gpl-3.0 |
vmlinz/prey-android-client | src/com/prey/json/parser/JSONParser.java | 8292 | package com.prey.json.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.prey.PreyConfig;
import com.prey.PreyLogger;
import com.prey.net.PreyRestHttpClient;
public class JSONParser {
JSONObject jObj;
boolean error;
private final static String COMMAND = "\"command\"";
private final static String TARGET = "\"target\"";
// constructor
public JSONParser() {
}
public List<JSONObject> getJSONFromUrl(Context ctx, String url) {
//PreyLogger.d("getJSONFromUrl:" + url);
String sb=null;
String json=null;
PreyRestHttpClient preyRestHttpClient=PreyRestHttpClient.getInstance(ctx);
try{
sb=preyRestHttpClient.getStringUrl(url,PreyConfig.getPreyConfig(ctx));
if (sb!=null)
json = sb.trim();
}catch(Exception e){
PreyLogger.e("Error, causa:" + e.getMessage(), e);
return null;
}
//json = "[{\"command\":\"history\",\"target\":\"call\",\"options\":{}}]";
// json = "[{\"command\":\"history\",\"target\":\"sms\",\"options\":{}}]";
// json = "[{\"command\":\"history\",\"target\":\"contact\",\"options\":{}}]";
//json = "[{\"command\":\"start\",\"target\":\"system_install\",\"options\":{}}]";
//json = "[{\"command\":\"start\",\"target\":\"server\",\"options\":{}}]";
// json = "[{\"command\":\"start\",\"target\":\"ring\",\"options\":{}}]";
// json = "[{\"command\":\"start\",\"target\":\"video\",\"options\":{}}]";
//json = "[{\"command\":\"get\",\"target\":\"picture\",\"options\":{}}]";
//json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"picture\"]}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"picture\",\"location\",\"screenshot\",\"access_points_list\"]}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"screenshot\",\"picture\",\"location\"]}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"screenshot\"]}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"location\"]}}]";
// json="[ {\"command\": \"start\",\"target\": \"geofencing\",\"options\": {\"origin\": \"-70.60713481,-36.42372147\",\"radius\": \"100\" }}]";
// json="[ {\"command\": \"start\",\"target\": \"geofencing\",\"options\": {\"origin\": \"-70.7193117,-32.7521112\",\"radius\": \"100\" }}]";
// json="[ {\"command\": \"start\",\"target\": \"geofencing\",\"options\": {\"id\":\"id1\",\"origin\":\"-70.60713481,-33.42372147\",\"radius\":\"100\",\"type:\":\"in",\"expire":"-1" }}]";
// json="[ {\"command\": \"stop\",\"target\": \"geofencing\",\"options\": {\"id\":\"id1\"}}]";
// json="[{\"command\":\"start\",\"target\":\"alert\",\"options\":{\"message\":\"This device i.\"}},{\"command\":\"start\",\"target\":\"alarm\",\"options\":null}, {\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\"[\"picture\",\"location\",\"screenshot\",\"access_points_list\"]}}]";
// json="[{\"command\":\"start\",\"target\":\"alert\",\"options\":{\"message\":\"This device i.\"}}, {\"command\":\"get\",\"target\":\"report\",\"options\":{\"delay\": \"25\",\"include\"[\"picture\",\"location\",\"screenshot\",\"access_points_list\"]}}]";
// json="[{\"command\":\"start\",\"target\":\"alert\",\"options\":{\"message\":\"This device i.\"}}
//json = "[ {\"command\": \"data\",\"target\": \"location\",\"options\": {}}]";
// json="[{\"command\":\"start\",\"target\":\"alert\",\"options\":{\"message\":\"This device i.\"}}]";
// json="[{\"command\":\"start\",\"target\":\"alarm\",\"options\":null}]";
// json="[{\"command\":\"start\",\"target\":\"alarm\",\"options\":null}]";
//json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"interval\":\"2\"}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"picture\",\"location\",\"screenshot\",\"access_points_list\"],\"interval\":\"10\"}}]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"include\":[\"picture\",\"location\",\"access_points_list\"],\"interval\":\"10\"}}]";
//json="[{\"command\":\"start\",\"target\":\"camouflage\",\"options\":null}]";
// json="[{\"command\":\"stop\",\"target\":\"camouflage\",\"options\":{\"interval\":\"2\"}}}]";
//json="[{\"target\":\"alert\",\"command\":\"start\",\"options\":{\"alert_message\":\"This device is stolen property. Please contact testforkhq@gmail.com to arrange its safe return.\"}},{\"target\":\"lock\",\"command\":\"start\",\"options\":{\"unlock_pass\":\"oso\"}},{\"command\":\"get\",\"target\":\"location\"},{\"target\":\"network\",\"command\":\"start\"},{\"target\":\"geo\",\"command\":\"start\"}]";
// json="[{\"command\":\"start\",\"target\":\"contacts_backup\" }]";
// json="[{\"command\":\"start\",\"target\":\"contacts_restore\" }]";
// json="[{\"command\":\"start\",\"target\":\"browser\" }]";
// json="[{\"command\":\"get\",\"target\":\"report\",\"options\":{\"interval\":\"2\",\"exclude\":[\"picture\",false]}}]";
// json = "[ {\"command\": \"start\",\"target\": \"detach\",\"options\": {}}]";
if ("[]".equals(json)) {
return null;
}
return getJSONFromTxt(ctx, json);
}
public List<JSONObject> getJSONFromTxt(Context ctx, String json) {
if("Invalid data received".equals(json)) return null;
List<JSONObject> listaJson = new ArrayList<JSONObject>();
json="{\"prey\":"+json+"}";
PreyLogger.d(json);
try{
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("prey");
for (int i = 0; i < jsonArray.length(); i++) {
String jsonCommand= jsonArray.get(i).toString();
JSONObject explrObject =new JSONObject(jsonCommand);
PreyLogger.i(explrObject.toString());
listaJson.add(explrObject);
}
}catch(Exception e){
PreyLogger.e("error in parser:"+e.getMessage(), e);
}
return listaJson;
}
public List<JSONObject> getJSONFromTxt2(Context ctx, String json) {
jObj = null;
List<JSONObject> listaJson = new ArrayList<JSONObject>();
List<String> listCommands = getListCommands(json);
for (int i = 0; listCommands != null && i < listCommands.size(); i++) {
String command = listCommands.get(i);
try {
jObj = new JSONObject(command);
listaJson.add(jObj);
} catch (JSONException e) {
PreyLogger.e("JSON Parser, Error parsing data " + e.toString(), e);
}
}
PreyLogger.i("json:" + json);
// return JSON String
return listaJson;
}
private List<String> getListCommands(String json) {
if (json.indexOf("[{"+COMMAND)==0){
return getListCommandsCmd(json);
}else{
return getListCommandsTarget(json);
}
}
private List<String> getListCommandsTarget(String json) {
json = json.replaceAll("nil", "{}");
json = json.replaceAll("null", "{}");
List<String> lista = new ArrayList<String>();
int posicion = json.indexOf(TARGET);
json = json.substring(posicion + 8);
posicion = json.indexOf(TARGET);
String command = "";
while (posicion > 0) {
command = json.substring(0, posicion);
json = json.substring(posicion + 8);
lista.add("{" + TARGET + cleanChar(command));
posicion = json.indexOf("\"target\"");
}
lista.add("{" + TARGET + cleanChar(json));
return lista;
}
private List<String> getListCommandsCmd(String json) {
json = json.replaceAll("nil", "{}");
json = json.replaceAll("null", "{}");
List<String> lista = new ArrayList<String>();
int posicion = json.indexOf(COMMAND);
json = json.substring(posicion + 9);
posicion = json.indexOf(COMMAND);
String command = "";
while (posicion > 0) {
command = json.substring(0, posicion);
json = json.substring(posicion + 9);
lista.add("{" + COMMAND + cleanChar(command));
posicion = json.indexOf("\"command\"");
}
lista.add("{" + COMMAND + cleanChar(json));
return lista;
}
private String cleanChar(String json) {
if (json != null) {
json = json.trim();
char c = json.charAt(json.length() - 1);
while (c == '{' || c == ',' || c == ']') {
json = json.substring(0, json.length() - 1);
json = json.trim();
c = json.charAt(json.length() - 1);
}
}
return json;
}
}
| gpl-3.0 |
MikeMatt16/Abide | Abide.Guerilla/Abide.Tag.Guerilla/Generated/Effect.Generated.cs | 1391 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Abide.Tag.Guerilla.Generated
{
using System;
using Abide.HaloLibrary;
using Abide.Tag;
/// <summary>
/// Represents the generated effect (effe) tag group.
/// </summary>
public class Effect : Group
{
/// <summary>
/// Initializes a new instance of the <see cref="Effect"/> class.
/// </summary>
public Effect()
{
// Add tag block to list.
this.TagBlocks.Add(new EffectBlock());
}
/// <summary>
/// Gets and returns the name of the effect tag group.
/// </summary>
public override string Name
{
get
{
return "effect";
}
}
/// <summary>
/// Gets and returns the group tag of the effect tag group.
/// </summary>
public override TagFourCc Tag
{
get
{
return "effe";
}
}
}
}
| gpl-3.0 |
wakeupthecat/gastona | base/src/listix/cmds/cmdLoadUnit.java | 6889 | /*
library listix (www.listix.org)
Copyright (C) 2005-2020 Alejandro Xalabarder Aulet
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.
*/
/*
//(o) WelcomeGastona_source_listix_command LOAD UNIT
========================================================================================
================ documentation for javajCatalog.gast ===================================
========================================================================================
This embedded EvaUnit describe the documentation for this listix command. Basically contains
the syntaxes, options and examples for the listix commnad.
#gastonaDoc#
<docType> listix_command
<name> LOAD UNIT
<groupInfo> lang_variables
<javaClass> listix.cmds.cmdLoadUnit
<importance> 4
<desc> //Load an EvaUnit into current data or listix formats ...
<help>
//
// Loads from a file an eva unit either into the unit #data# or the unit #listix#.
//
// This can be used to load data or logic dynamically. Another use is to load the last state
// of the variables of the application (see also DUMP), for example:
//
// <main0>
// LOAD, data, myAppPersist.txt
//
// <-- javaj exit>
// DUMP, data, myAppPersist.txt
//
// NOTE: Loading data in this way produce variables of the #data# section being replaced
// by the variables found in the file. This is usually the desired behaviour for a
// final application, but during development it could be a problem: if we change in the
// script contents of variables in the data section this can be ovewritten by the command
// load, so it is a good idea to disable this LOAD during developement.
//
<aliases>
alias
LOAD
<syntaxHeader>
synIndx, importance, desc
1 , 4 , //Loads a unit either in data or listix formats
<syntaxParams>
synIndx, name , defVal , desc
1 , data|listix|formats|dump, , //Target EvaUnit or dump (no target). Target can be data or listix (old formats)
1 , fileName , , //File name where the EvaUnit 'unitFormats' is to be found
<options>
synIndx, optionName , parameters , defVal , desc
1 , UNIT2LOAD , nameOfEvaUnit , data|formats|listix, //EvaUnit to be load from the file, if not specified it has the same name as the target EvaUnit ('data', 'formats' or 'listix')
1 , MERGE , CLEAN/REPLACE/ADD_LINES/ONLY_NEW, REPLACE , //CLEAN: Clean current before merging, REPLACE: replacing existing Evas, ADD_LINES: Adding lines to existing Evas, ONLY_NEW: Add only new evas
<examples>
desc
#**FIN_EVA#
*/
package listix.cmds;
import listix.*;
import de.elxala.Eva.*;
public class cmdLoadUnit implements commandable
{
/**
get all the different names that the command can have
*/
public String [] getNames ()
{
return new String [] {
"LOAD UNIT",
"LOAD",
};
}
/**
Execute the commnad and returns how many rows of commandEva
the command had.
that : the environment where the command is called
commandEva : the whole command Eva
indxCommandEva : index of commandEva where the commnad starts
*/
public int execute (listix that, Eva commandEva, int indxComm)
{
listixCmdStruct cmd = new listixCmdStruct (that, commandEva, indxComm);
String targetUnit = cmd.getArg(0);
String fileName = cmd.getArg(1);
String mergeType = cmd.takeOptionString ("MERGE" , "REPLACE");
String unit2Load = cmd.takeOptionString ("UNIT2LOAD", targetUnit);
// check number of arguments
if (cmd.getArgSize() != 2)
{
cmd.getLog ().err ("LOAD UNIT", "LOAD command takes 2 and only 2 parameters, given " + cmd.getArgSize());
return 1;
}
// Getting the unit target
//
EvaUnit uTarget = null;
if (targetUnit.equals("data"))
{
uTarget = cmd.getListix ().getGlobalData ();
}
else if (targetUnit.equals("formats") || targetUnit.equals("listix"))
{
uTarget = cmd.getListix ().getGlobalFormats ();
}
else if (targetUnit.equals("dump") || targetUnit.equals("") || targetUnit.equals("-"))
{
uTarget = null;
}
else
{
cmd.getLog ().err ("LOAD UNIT", "LOAD wrong unit target (first parameter), given \"" + targetUnit + "\", it should be either 'data', 'formats' or 'listix'");
return 1;
}
// MERGE_ADD 'A' the rows of the plusEva are added at the end
// MERGE_REPLACE 'R' the eva is replaced (if it already exist)
char iMergeType = Eva.MERGE_ADD;
if (mergeType.equalsIgnoreCase ("CLEAN"))
{
uTarget.clear ();
iMergeType = Eva.MERGE_REPLACE;
}
else if (mergeType.equalsIgnoreCase ("REPLACE"))
{
iMergeType = Eva.MERGE_REPLACE;
}
else if (mergeType.equalsIgnoreCase ("ADD") || mergeType.equalsIgnoreCase ("ADD_LINES"))
{
iMergeType = Eva.MERGE_ADD;
}
else if (mergeType.equalsIgnoreCase ("NEW") || mergeType.equalsIgnoreCase ("ONLY_NEW"))
{
iMergeType = Eva.MERGE_NEW_VARS;
}
else
{
cmd.getLog ().err ("LOAD UNIT", "wrong MERGE option, given \"" + mergeType + "\", it should be either 'CLEAN', 'REPLACE', 'ADD_LINES' or 'ONLY_NEW'");
return 1;
}
// Getting the unit source (to merge)
//
cmd.getLog ().dbg (2, "LOAD UNIT", "load unit [" + unit2Load + "] into [" + targetUnit + "] from [" + fileName + "] merge type " + mergeType + " (" + iMergeType + ")");
EvaUnit uSource = EvaFile.loadEvaUnit (fileName, unit2Load);
if (uTarget != null)
{
uTarget.merge (uSource, iMergeType);
}
else
{
that.writeStringOnTarget ("" + uSource);
}
cmd.checkRemainingOptions ();
return 1;
}
} | gpl-3.0 |
MarcosMota/Blog | Projeto/Blog/Blog.Core/Domain/Menu.cs | 401 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blog.Core.Domain
{
public class Menu
{
public string Nome { get; set; }
public string Role { get; set; }
public string icone { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
}
}
| gpl-3.0 |
elan-ev/StudIPAndroidApp | app/src/androidTest/java/de/elanev/studip/android/app/base/internal/di/component/ApplicationTestComponent.java | 822 | /*
* Copyright (c) 2017 ELAN e.V.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package de.elanev.studip.android.app.base.internal.di.component;
import javax.inject.Singleton;
import dagger.Component;
import de.elanev.studip.android.app.base.internal.di.components.ApplicationComponent;
import de.elanev.studip.android.app.base.internal.di.modules.ApplicationModule;
import de.elanev.studip.android.app.base.internal.di.modules.NetworkModule;
/**
* @author joern
*/
@Singleton
@Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface ApplicationTestComponent extends ApplicationComponent {}
| gpl-3.0 |
lyoshenka/ultiorganizer | seriesstatus.php | 8440 | <?php
include_once 'lib/season.functions.php';
include_once 'lib/series.functions.php';
include_once 'lib/pool.functions.php';
include_once 'lib/team.functions.php';
$LAYOUT_ID = SERIESTATUS;
$title = _("Statistics")." ";
$viewUrl="?view=seriesstatus";
$sort="winavg";
if (!empty($_GET['Series'])) {
$viewUrl .= "&Series=".$_GET['Series'];
$seriesinfo = SeriesInfo($_GET['Series']);
$seasoninfo = SeasonInfo($seriesinfo['season']);
$title.= U_($seriesinfo['name']);
}
if(!empty($_GET["Sort"])){
$sort = $_GET["Sort"];
}
//common page
pageTop($title);
leftMenu($LAYOUT_ID);
contentStart();
$teamstats = array();
$allteams = array();
$teams = SeriesTeams($seriesinfo['series_id']);
foreach ($teams as $team) {
$stats = TeamStats($team['team_id']);
$spiritstats = TeamSpiritStats($team['team_id']);
$points = TeamPoints($team['team_id']);
$teamstats['name']=$team['name'];
$teamstats['team_id']=$team['team_id'];
$teamstats['seed']=$team['rank'];
$teamstats['flagfile']=$team['flagfile'];
$teamstats['pool']=$team['poolname'];
$teamstats['wins']=$stats['wins'];
$teamstats['games']=$stats['games'];
$teamstats['for']=$points['scores'];
$teamstats['against']=$points['against'];
$teamstats['losses']=$teamstats['games']-$teamstats['wins'];
$teamstats['diff']=$teamstats['for']-$teamstats['against'];
$teamstats['spirit']=$points['spirit'];
$teamstats['spiritavg']=number_format(SafeDivide(intval($points['spirit']), intval($spiritstats['games'])),1);
$teamstats['winavg']=number_format(SafeDivide(intval($stats['wins']), intval($stats['games']))*100,1);
$allteams[] = $teamstats;
}
echo "<h2>"._("Division statistics:")." ".utf8entities($seriesinfo['name'])."</h2>";
$style = "";
echo "<table border='1' style='width:100%'>\n";
echo "<tr>";
if($sort == "name" || $sort == "pool" || $sort == "against" || $sort == "seed") {
usort($allteams, create_function('$a,$b','return $a[\''.$sort.'\']==$b[\''.$sort.'\']?0:($a[\''.$sort.'\']<$b[\''.$sort.'\']?-1:1);'));
}else{
usort($allteams, create_function('$a,$b','return $a[\''.$sort.'\']==$b[\''.$sort.'\']?0:($a[\''.$sort.'\']>$b[\''.$sort.'\']?-1:1);'));
}
if($sort == "name") {
echo "<th style='width:180px'>"._("Team")."</th>";
}else{
echo "<th style='width:180px'><a class='thsort' href='".$viewUrl."&Sort=name'>"._("Team")."</a></th>";
}
/*
if($sort == "pool") {
echo "<th style='width:200px'>"._("Pool")."</th>";
}else{
echo "<th style='width:200px'><a href='".$viewUrl."&Sort=pool'>"._("Pool")."</a></th>";
}
*/
if($sort == "seed") {
echo "<th class='center'>"._("Seeding")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=seed'>"._("Seeding")."</a></th>";
}
if($sort == "games") {
echo "<th class='center'>"._("Games")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=games'>"._("Games")."</a></th>";
}
if($sort == "wins") {
echo "<th class='center'>"._("Wins")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=wins'>"._("Wins")."</a></th>";
}
if($sort == "losses") {
echo "<th class='center'>"._("Losses")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=losses'>"._("Losses")."</a></th>";
}
if($sort == "for") {
echo "<th class='center'>"._("Goals for")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=for'>"._("Goals for")."</a></th>";
}
if($sort == "against") {
echo "<th class='center'>"._("Goals against")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=against'>"._("Goals against")."</a></th>";
}
if($sort == "diff") {
echo "<th class='center'>"._("Goals diff")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=diff'>"._("Goals diff")."</a></th>";
}
if($sort == "winavg") {
echo "<th class='center'>"._("Win-%")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=winavg'>"._("Win-%")."</a></th>";
}
if($seasoninfo['spiritpoints'] && ($seasoninfo['showspiritpoints'] || isSeasonAdmin($seriesinfo['season']))){
if($sort == "spirit") {
echo "<th class='center'>"._("Spirit points")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=spirit'>"._("Spirit points")."</a></th>";
}
if($sort == "spiritavg") {
echo "<th class='center'>"._("Spirit points")."</th>";
}else{
echo "<th class='center'><a class='thsort' href='".$viewUrl."&Sort=spiritavg'>"._("Spirit / Game")."</a></th>";
}
}
echo "</tr>\n";
foreach($allteams as $stats){
echo "<tr>";
$flag="";
if(intval($seasoninfo['isinternational'])){
$flag = "<img height='10' src='images/flags/tiny/".$stats['flagfile']."' alt=''/> ";
}
if($sort == "name") {
echo "<td class='highlight'>$flag<a href='?view=teamcard&Team=".$stats['team_id']."'>",utf8entities(U_($stats['name'])),"</a></td>";
}else{
echo "<td>$flag<a href='?view=teamcard&Team=".$stats['team_id']."'>",utf8entities(U_($stats['name'])),"</a></td>";
}
/*
if($sort == "pool") {
echo "<td class='highlight'>",utf8entities(U_($stats['pool'])),"</td>";
}else{
echo "<td>",utf8entities(U_($stats['pool'])),"</td>";
}
*/
if($sort == "seed") {
echo "<td class='center highlight'>".intval($stats['seed']).".</td>";
}else{
echo "<td class='center'>".intval($stats['seed']).".</td>";
}
if($sort == "games") {
echo "<td class='center highlight'>".intval($stats['games'])."</td>";
}else{
echo "<td class='center'>".intval($stats['games'])."</td>";
}
if($sort == "wins") {
echo"<td class='center highlight'>".intval($stats['wins'])."</td>";
}else{
echo"<td class='center'>".intval($stats['wins'])."</td>";
}
if($sort == "losses") {
echo "<td class='center highlight'>",intval($stats['losses']),"</td>";
}else{
echo "<td class='center'>",intval($stats['losses']),"</td>";
}
if($sort == "for") {
echo "<td class='center highlight'>".intval($stats['for'])."</td>";
}else{
echo "<td class='center'>".intval($stats['for'])."</td>";
}
if($sort == "against") {
echo "<td class='center highlight'>".intval($stats['against'])."</td>";
}else{
echo "<td class='center'>".intval($stats['against'])."</td>";
}
if($sort == "diff") {
echo "<td class='center highlight'>",intval($stats['diff']),"</td>";
}else{
echo "<td class='center'>",intval($stats['diff']),"</td>";
}
if($sort == "winavg") {
echo "<td class='center highlight'>".$stats['winavg']."%</td>";
}else{
echo "<td class='center'>".$stats['winavg']."%</td>";
}
if($seasoninfo['spiritpoints'] && ($seasoninfo['showspiritpoints'] || isSeasonAdmin($seriesinfo['season']))){
if($sort == "spirit") {
echo "<td class='center highlight'>".$stats['spirit']."</td>";
}else{
echo "<td class='center'>".$stats['spirit']."</td>";
}
if($sort == "spiritavg") {
echo "<td class='center highlight'>".$stats['spiritavg']."</td>";
}else{
echo "<td class='center'>".$stats['spiritavg']."</td>";
}
}
echo "</tr>\n";
}
echo "</table>\n";
echo "<a href='?view=poolstatus&Series=".$seriesinfo['series_id']."'>"._("Show all pools")."</a>";
echo "<h2>"._("Scoreboard leaders")."</h2>\n";
echo "<table cellspacing='0' border='0' width='100%'>\n";
echo "<tr><th style='width:200px'>"._("Player")."</th><th style='width:200px'>"._("Team")."</th><th class='center'>"._("Games")."</th>
<th class='center'>"._("Assists")."</th><th class='center'>"._("Goals")."</th><th class='center'>"._("Tot.")."</th></tr>\n";
$scores = SeriesScoreBoard($seriesinfo['series_id'],"total", 10);
while($row = mysql_fetch_assoc($scores))
{
echo "<tr><td>". utf8entities($row['firstname']." ".$row['lastname'])."</td>";
echo "<td>".utf8entities($row['teamname'])."</td>";
echo "<td class='center'>".intval($row['games'])."</td>";
echo "<td class='center'>".intval($row['fedin'])."</td>";
echo "<td class='center'>".intval($row['done'])."</td>";
echo "<td class='center'>".intval($row['total'])."</td></tr>\n";
}
echo "</table>";
echo "<a href='?view=scorestatus&Series=".$seriesinfo['series_id']."'>"._("Scoreboard")."</a>";
contentEnd();
pageEnd();
?>
| gpl-3.0 |
KyleGrund/ViTeMBP-BEJava | ViTeMBP Services/src/com/vitembp/services/sensors/DistanceVL53L0X.java | 4376 | /*
* Video Telemetry for Mountain Bike Platform back-end services.
* Copyright (C) 2017 Kyle Grund
*
* 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 com.vitembp.services.sensors;
import com.vitembp.embedded.data.Sample;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
/**
* Class providing an interface to the VL53L0X sensor.
*/
class DistanceVL53L0X extends DistanceSensor {
/**
* A UUID representing the type of this sensor.
*/
static final UUID TYPE_UUID = UUID.fromString("3972d3a9-d55f-4e74-a61f-f2f8fe62f858");
/**
* The function which applies the calibration data.
*/
private Function<Double, Double> calFunction;
/**
* The function which applies the calibration data and returns data as a percentage.
*/
private Function<Double, Double> calPercentageFunction;
/**
* Initializes a new instance of the DistanceVL53L0X class.
* @param name The name of the sensor.
* @param calData The sensor calibration data.
*/
DistanceVL53L0X(String name, String calData) {
super(name);
// decode cal data of the form "([min],[max])"
if (calData != null && !calData.isEmpty()) {
String[] split = calData.split(",");
if (split.length != 2) {
throw new IllegalArgumentException("VL53L0X calibration data must be of the form \"([min],[max])\".");
}
// calibration values
double calMinimum, calMaximum;
try {
calMinimum = Double.parseDouble(split[0].substring(1));
calMaximum = Double.parseDouble(split[1].substring(0, split[1].length() - 2));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("VL53L0X calibration data must be of the form \"([min],[max])\".", ex);
}
// this funciton applies the calibration data to a sample
this.calFunction = (value) -> {
double newVal = value;
newVal = Math.min(newVal, calMaximum);
newVal = Math.max(newVal, calMinimum);
newVal -= calMinimum;
return newVal;
};
// this funciton applies the calibration and then converts the
// result to a percentage represented on the 0, 1 interval
this.calPercentageFunction = this.calFunction.andThen((value) -> value / (calMaximum - calMinimum));
} else {
// no calibration data provided so use identity
this.calFunction = d -> d;
this.calPercentageFunction = d -> d;
}
}
@Override
public Optional<Double> getDistanceMilimeters(Sample toDecode) {
return this.decodeData(toDecode, this.calFunction);
}
@Override
public Optional<Double> getDistancePercent(Sample toDecode) {
return this.decodeData(toDecode, this.calPercentageFunction);
}
/**
* Decodes the sample data and applies the given calibration function.
* @param toDecode The sample to decode.
* @param calFunc The function which applies calibration data.
* @return Decoded and calibrated data from the sample.
*/
private Optional<Double> decodeData(Sample toDecode, Function<Double, Double> calFunc) {
String data = this.getData(toDecode);
if (data == null || "".equals(data)) {
return Optional.empty();
} else {
// get the sensor reading value
double value = Double.parseDouble(data);
// return calibrated value
return Optional.of(calFunc.apply(value));
}
}
}
| gpl-3.0 |
pshendry/rust-planets-nu | src/builders/minefield.rs | 1802 | extern crate serialize;
use self::serialize::json;
use error;
use json_helpers::{find, get_bool, get_i32, get_object, get_string};
macro_rules! get(
($i1:ident, $e:expr, $i2:ident) => (try!($i2(try!(find($i1, $e)))))
)
// Public
#[deriving(Eq, PartialEq, Show)]
pub struct Minefield {
pub owner_id: i32,
pub is_web: bool,
pub units: i32,
pub info_turn: i32,
pub friendly_code: String,
pub position: (i32, i32),
pub radius: i32,
pub id: i32,
}
pub fn build(json: &json::Json) -> Result<Minefield, error::Error> {
let map = try!(get_object(json));
Ok(Minefield {
owner_id: get!(map, "ownerid", get_i32),
is_web: get!(map, "isweb", get_bool),
units: get!(map, "units", get_i32),
info_turn: get!(map, "infoturn", get_i32),
friendly_code: get!(map, "friendlycode", get_string),
position: (get!(map, "x", get_i32), get!(map, "y", get_i32)),
radius: get!(map, "radius", get_i32),
id: get!(map, "id", get_i32),
})
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use json_helpers::parse;
#[test]
fn test_build() {
let json = "{\
\"ownerid\":7,\
\"isweb\":true,\
\"units\":1253,\
\"infoturn\":17,\
\"friendlycode\":\"???\",\
\"x\":2729,\
\"y\":2335,\
\"radius\":35,\
\"id\":1\
}";
let result = Minefield {
owner_id: 7i32,
is_web: true,
units: 1253i32,
info_turn: 17i32,
friendly_code: "???".to_string(),
position: (2729i32, 2335i32),
radius: 35i32,
id: 1i32,
};
assert_eq!(result, build(&parse(json).unwrap()).unwrap());
}
}
| gpl-3.0 |
technokratos/Tracker | src/main/java/checks/types/Count.java | 305 | package checks.types;
/**
* Created by denis on 25.02.17.
*/
public class Count {
int value = 0;
public void inc() {
value++;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return Integer.toString(value) ;
}
}
| gpl-3.0 |
RotaruDan/cytopathologyeditor | app/controllers/users/users.authentication.server.controller.js | 5978 | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Signup
*/
exports.signup = function(req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init Variables
var user = new User(req.body);
var message = null;
// Add missing user fields
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
})(req, res, next);
};
/**
* Signout
*/
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
};
/**
* OAuth callback
*/
exports.oauthCallback = function(strategy) {
return function(req, res, next) {
passport.authenticate(strategy, function(err, user, redirectURL) {
if (err || !user) {
return res.redirect('/#!/signin');
}
req.login(user, function(err) {
if (err) {
return res.redirect('/#!/signin');
}
return res.redirect(typeof redirectURL === 'string' ? redirectURL : '/');
});
})(req, res, next);
};
};
/**
* Helper function to save or update a OAuth user profile
*/
exports.saveOAuthUserProfile = function(req, providerUserProfile, done) {
if (!req.user) {
// Define a search query fields
var searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField;
var searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField;
// Define main provider search query
var mainProviderSearchQuery = {};
mainProviderSearchQuery.provider = providerUserProfile.provider;
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define additional provider search query
var additionalProviderSearchQuery = {};
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define a search query to find existing user with current provider profile
var searchQuery = {
$or: [mainProviderSearchQuery, additionalProviderSearchQuery]
};
User.findOne(searchQuery, function(err, user) {
if (err) {
return done(err);
} else {
if (!user) {
var possibleUsername = providerUserProfile.username || ((providerUserProfile.email) ? providerUserProfile.email.split('@')[0] : '');
User.findUniqueUsername(possibleUsername, null, function(availableUsername) {
user = new User({
firstName: providerUserProfile.firstName,
lastName: providerUserProfile.lastName,
username: availableUsername,
displayName: providerUserProfile.displayName,
provider: providerUserProfile.provider,
providerData: providerUserProfile.providerData
});
// Email intentional
// ly added later to allow defaults (sparse settings) to be applid.
// Handles case where no email is supplied.
// See comment: https://github.com/meanjs/mean/pull/1495#issuecomment-246090193
user.email = providerUserProfile.email;
// And save the user
user.save(function(err) {
return done(err, user);
});
});
} else {
return done(err, user);
}
}
});
} else {
// User is already logged in, join the provider data to the existing user
var user = req.user;
// Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if (user.provider !== providerUserProfile.provider && (!user.additionalProvidersData || !user.additionalProvidersData[providerUserProfile.provider])) {
// Add the provider data to the additional provider data field
if (!user.additionalProvidersData) {
user.additionalProvidersData = {};
}
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData;
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
// And save the user
user.save(function(err) {
return done(err, user, '/#!/settings/accounts');
});
} else {
return done(new Error('User is already connected using this provider'), user);
}
}
};
/**
* Remove OAuth provider
*/
exports.removeOAuthProvider = function(req, res, next) {
var user = req.user;
var provider = req.param('provider');
if (user && provider) {
// Delete the additional provider
if (user.additionalProvidersData[provider]) {
delete user.additionalProvidersData[provider];
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
}
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
}
};
| gpl-3.0 |
randomize/VimConfig | tags/unity5/UnityEditor/BillboardAssetInspector.cs | 10402 | namespace UnityEditor
{
using System;
using UnityEditorInternal;
using UnityEngine;
[CanEditMultipleObjects, CustomEditor(typeof(BillboardAsset))]
internal class BillboardAssetInspector : Editor
{
private SerializedProperty m_Bottom;
private Material m_GeometryMaterial;
private Mesh m_GeometryMesh;
private SerializedProperty m_Height;
private SerializedProperty m_ImageCount;
private SerializedProperty m_IndexCount;
private SerializedProperty m_Material;
private Vector2 m_PreviewDir = new Vector2(-120f, 20f);
private bool m_PreviewShaded = true;
private PreviewRenderUtility m_PreviewUtility;
private MaterialPropertyBlock m_ShadedMaterialProperties;
private Mesh m_ShadedMesh;
private SerializedProperty m_VertexCount;
private SerializedProperty m_Width;
private Material m_WireframeMaterial;
private static GUIStyles s_Styles;
private void DoRenderPreview(bool shaded)
{
BillboardAsset target = this.target as BillboardAsset;
Bounds bounds = new Bounds(new Vector3(0f, (this.m_Height.floatValue + this.m_Bottom.floatValue) * 0.5f, 0f), new Vector3(this.m_Width.floatValue, this.m_Height.floatValue, this.m_Width.floatValue));
float magnitude = bounds.extents.magnitude;
float num2 = 8f * magnitude;
Quaternion quaternion = Quaternion.Euler(-this.m_PreviewDir.y, -this.m_PreviewDir.x, 0f);
this.m_PreviewUtility.m_Camera.transform.rotation = quaternion;
this.m_PreviewUtility.m_Camera.transform.position = (Vector3) (quaternion * (-Vector3.forward * num2));
this.m_PreviewUtility.m_Camera.nearClipPlane = num2 - (magnitude * 1.1f);
this.m_PreviewUtility.m_Camera.farClipPlane = num2 + (magnitude * 1.1f);
this.m_PreviewUtility.m_Light[0].intensity = 1.4f;
this.m_PreviewUtility.m_Light[0].transform.rotation = quaternion * Quaternion.Euler(40f, 40f, 0f);
this.m_PreviewUtility.m_Light[1].intensity = 1.4f;
Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f);
InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient);
if (shaded)
{
target.MakeRenderMesh(this.m_ShadedMesh, 1f, 1f, 0f);
target.MakeMaterialProperties(this.m_ShadedMaterialProperties, this.m_PreviewUtility.m_Camera);
ModelInspector.RenderMeshPreviewSkipCameraAndLighting(this.m_ShadedMesh, bounds, this.m_PreviewUtility, target.material, null, this.m_ShadedMaterialProperties, new Vector2(0f, 0f), -1);
}
else
{
target.MakePreviewMesh(this.m_GeometryMesh);
ModelInspector.RenderMeshPreviewSkipCameraAndLighting(this.m_GeometryMesh, bounds, this.m_PreviewUtility, this.m_GeometryMaterial, this.m_WireframeMaterial, null, new Vector2(0f, 0f), -1);
}
InternalEditorUtility.RemoveCustomLighting();
}
public override string GetInfoString()
{
return string.Format("{0} verts, {1} tris, {2} images", this.m_VertexCount.intValue, this.m_IndexCount.intValue / 3, this.m_ImageCount.intValue);
}
public override bool HasPreviewGUI()
{
return (this.target != null);
}
private void InitPreview()
{
if (this.m_PreviewUtility == null)
{
this.m_PreviewUtility = new PreviewRenderUtility();
this.m_ShadedMesh = new Mesh();
this.m_ShadedMesh.hideFlags = HideFlags.HideAndDontSave;
this.m_ShadedMesh.MarkDynamic();
this.m_GeometryMesh = new Mesh();
this.m_GeometryMesh.hideFlags = HideFlags.HideAndDontSave;
this.m_GeometryMesh.MarkDynamic();
this.m_ShadedMaterialProperties = new MaterialPropertyBlock();
this.m_GeometryMaterial = EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Material.mat") as Material;
this.m_WireframeMaterial = ModelInspector.CreateWireframeMaterial();
EditorUtility.SetCameraAnimateMaterials(this.m_PreviewUtility.m_Camera, true);
}
}
private void OnDisable()
{
if (this.m_PreviewUtility != null)
{
this.m_PreviewUtility.Cleanup();
this.m_PreviewUtility = null;
UnityEngine.Object.DestroyImmediate(this.m_ShadedMesh, true);
UnityEngine.Object.DestroyImmediate(this.m_GeometryMesh, true);
this.m_GeometryMaterial = null;
if (this.m_WireframeMaterial != null)
{
UnityEngine.Object.DestroyImmediate(this.m_WireframeMaterial, true);
}
}
}
private void OnEnable()
{
this.m_Width = base.serializedObject.FindProperty("width");
this.m_Height = base.serializedObject.FindProperty("height");
this.m_Bottom = base.serializedObject.FindProperty("bottom");
this.m_ImageCount = base.serializedObject.FindProperty("imageTexCoords.Array.size");
this.m_VertexCount = base.serializedObject.FindProperty("vertices.Array.size");
this.m_IndexCount = base.serializedObject.FindProperty("indices.Array.size");
this.m_Material = base.serializedObject.FindProperty("material");
}
public override void OnInspectorGUI()
{
base.serializedObject.Update();
EditorGUILayout.PropertyField(this.m_Width, Styles.m_Width, new GUILayoutOption[0]);
EditorGUILayout.PropertyField(this.m_Height, Styles.m_Height, new GUILayoutOption[0]);
EditorGUILayout.PropertyField(this.m_Bottom, Styles.m_Bottom, new GUILayoutOption[0]);
GUILayout.Space(10f);
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(this.m_ImageCount, Styles.m_ImageCount, new GUILayoutOption[0]);
EditorGUILayout.PropertyField(this.m_VertexCount, Styles.m_VertexCount, new GUILayoutOption[0]);
EditorGUILayout.PropertyField(this.m_IndexCount, Styles.m_IndexCount, new GUILayoutOption[0]);
EditorGUI.EndDisabledGroup();
GUILayout.Space(10f);
EditorGUILayout.PropertyField(this.m_Material, Styles.m_Material, new GUILayoutOption[0]);
base.serializedObject.ApplyModifiedProperties();
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (!ShaderUtil.hardwareSupportsRectRenderTexture)
{
if (Event.current.type == EventType.Repaint)
{
EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Preview requires\nrender texture support");
}
}
else
{
this.InitPreview();
this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r);
if (Event.current.type == EventType.Repaint)
{
this.m_PreviewUtility.BeginPreview(r, background);
this.DoRenderPreview(this.m_PreviewShaded);
this.m_PreviewUtility.EndAndDrawPreview(r);
}
}
}
public override void OnPreviewSettings()
{
if (ShaderUtil.hardwareSupportsRectRenderTexture)
{
bool flag = this.m_Material.objectReferenceValue != null;
GUI.enabled = flag;
if (!flag)
{
this.m_PreviewShaded = false;
}
GUIContent content = !this.m_PreviewShaded ? Styles.m_Geometry : Styles.m_Shaded;
GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.Width(75f) };
Rect position = GUILayoutUtility.GetRect(content, Styles.m_DropdownButton, options);
if (EditorGUI.ButtonMouseDown(position, content, FocusType.Native, Styles.m_DropdownButton))
{
GUIUtility.hotControl = 0;
GenericMenu menu = new GenericMenu();
menu.AddItem(Styles.m_Shaded, this.m_PreviewShaded, (GenericMenu.MenuFunction) (() => (this.m_PreviewShaded = true)));
menu.AddItem(Styles.m_Geometry, !this.m_PreviewShaded, (GenericMenu.MenuFunction) (() => (this.m_PreviewShaded = false)));
menu.DropDown(position);
}
}
}
public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height)
{
if (!ShaderUtil.hardwareSupportsRectRenderTexture)
{
return null;
}
this.InitPreview();
this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float) width, (float) height));
this.DoRenderPreview(true);
return this.m_PreviewUtility.EndStaticPreview();
}
private static GUIStyles Styles
{
get
{
if (s_Styles == null)
{
s_Styles = new GUIStyles();
}
return s_Styles;
}
}
private class GUIStyles
{
public readonly GUIContent m_Bottom = new GUIContent("Bottom");
public readonly GUIStyle m_DropdownButton = new GUIStyle("MiniPopup");
public readonly GUIContent m_Geometry = new GUIContent("Geometry");
public readonly GUIContent m_Height = new GUIContent("Height");
public readonly GUIContent m_ImageCount = new GUIContent("Image Count");
public readonly GUIContent m_IndexCount = new GUIContent("Index Count");
public readonly GUIContent m_Material = new GUIContent("Material");
public readonly GUIContent m_Shaded = new GUIContent("Shaded");
public readonly GUIContent m_VertexCount = new GUIContent("Vertex Count");
public readonly GUIContent m_Width = new GUIContent("Width");
}
}
}
| gpl-3.0 |
leorue/atticbase | api/models/movie.js | 281 | /* Developed by Leo Schultz - 10/10/2014 */
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var movieSchema=new Schema({
title:'String',
releaseYear:'String',
director:'String',
genre:'String'
});
module.exports=mongoose.model('Movie',movieSchema); | gpl-3.0 |
OutsideTheBoxProject/P | Arduino/RCubes/BluetoothSerial.cpp | 7201 | /*-------------------------------------------------------------------------
Arduino library for the Teensy3Bluetooth Serial shield available at the hackerspaceshop.com
Check it out here:
http://www.hackerspaceshop.com/teensy/teensy-3-1-bluetooth-module.html
Written by Amir Hassan and Florian Bittner for hackerspaceshop.com,
contributions by members of the open source community.
This is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see
<http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------*/
#include "BluetoothSerial.h"
#define INTERRUPT_PIN 3
#define RX 0
#define TX 1
BluetoothSerial BTSerial(RX,TX);
void BluetoothSerial::begin(unsigned long speed) {
//debug
Serial.println("GO");
pinMode(INTERRUPT_PIN,INPUT_PULLUP);
mySerial.begin(speed);
}
void BluetoothSerial::sendCommand(const char* cmd) {
Serial.print("Cmd:");
Serial.print(cmd);
Serial.print(" start response|");
mySerial.write(cmd);
delay(50);
while (mySerial.available()) {
char c = mySerial.read();
Serial.print(c);
}
Serial.println("|end response");
}
void BluetoothSerial::setBaudrate(unsigned long speed) {
// BAUDRATE TABLE
// 1---1200
// 2---2400
// 3---4800
// 4---9600
// 5---19200
// 6---38400
// 7---57600
// 8---115200
// 9---230400
// A---460800
// B---921600
// C---1382400
// default:4---9600
if(speed == 0) speed=9600;
char baudRateCode[1];
switch (speed){
case 1200: baudRateCode[0]='1'; break;
case 2400: baudRateCode[0]='2'; break;
case 4800: baudRateCode[0]='3'; break;
case 19200: baudRateCode[0]='5'; break;
case 38400: baudRateCode[0]='6'; break;
case 57600: baudRateCode[0]='7'; break;
case 115200: baudRateCode[0]='8'; break;
case 230400: baudRateCode[0]='9'; break;
case 460800: baudRateCode[0]='A'; break;
case 921600: baudRateCode[0]='B'; break;
case 1382400: baudRateCode[0]='C'; break;
default:
// 9600
baudRateCode[0]='4';
break;
}
// DEBUG
Serial.println("");
Serial.print("Setting BAUDRATE on device to: ");
Serial.print(speed);
Serial.print(" (");
Serial.print(baudRateCode[0]);
Serial.println(")");
mySerial.write("AT+BAUD");
mySerial.write(baudRateCode[0]);
mySerial.write("\r\n");
delay(50);
while (mySerial.available()) {
char c = mySerial.read();
Serial.print(c); // assuming OK
}
Serial.println("|");
// should we close the connection and reopen with set baudrate here?
// TODO return 1 on succcess / -1 on fail
}
void BluetoothSerial::setPinCode(const char* pin_code) {
// DEBUG
Serial.println("");
Serial.print("Setting PINCODE on device to: '");
Serial.print(pin_code);
Serial.println("'");
// set pin code
mySerial.write("AT+PIN");
mySerial.write(pin_code);
mySerial.write("\r\n");
delay(50);
while (mySerial.available()) {
char c = mySerial.read();
Serial.print(c); // assuming OK
}
Serial.println("|");
// TODO return 1 on succcess / -1 on fail
}
void BluetoothSerial::setDeviceName(const char* device_name) {
// DEBUG
Serial.println("");
Serial.print("Setting DEVICENAME on device to: ");
Serial.println(device_name);
// set name of bluetooth device
mySerial.write("AT+NAME");
mySerial.write(device_name);
mySerial.write("\r\n");
delay(50);
while (mySerial.available()) {
char c = mySerial.read();
Serial.print(c); // assuming OK
}
Serial.println("|");
// TODO return 1 on succcess / -1 on fail
}
void BluetoothSerial::makeMaster() {
// DEBUG
Serial.println("");
Serial.println("Making device Master");
sendCommand("AT+ROLE1\r\n");
myRole = 1;
}
void BluetoothSerial::makeSlave() {
// DEBUG
Serial.println("");
Serial.println("Making device Slave");
sendCommand("AT+ROLE0\r\n");
myRole = 0;
}
void BluetoothSerial::resetDevice() {
// DEBUG
Serial.println("");
Serial.println("Resetting device");
sendCommand("AT+RESET\r\n"); // Set search the remote Bluetooth device automatically
}
int BluetoothSerial::searchDevices() {
// DEBUG
Serial.println("");
Serial.println("Searching for remote devices");
String response = "";
char buf[512];
int devices = 0;
int i = 0;
int j = 0;
for (int j=0; j<20; j++) availableDevices[j] = "";
sendCommand("AT+ROLE\r\n");
sendCommand("AT+IAC9e8b33\r\n");
sendCommand("AT+COD001f00\r\n");
sendCommand("AT+INQM1,9,15\r\n");
sendCommand("AT+INQ\r\n"); // Start search
sendCommand("AT+STATE\r\n");
delay(10000);
while (mySerial.available()) {
buf[j] = mySerial.read();
Serial.print(buf[j]);
j++;
}
buf[j] = '\0';
Serial.println("|");
response = String(buf);
Serial.println(response);
// Sample response:
// +INQS
// +INQ: 11:22:33:44:55:66,001f00,-90
// ..
// +INQE
i=response.indexOf("+INQ:");
while (i > -1) {
availableDevices[devices] = response.substring(i,response.indexOf(",",i));
response = response.substring(i+6);
devices++;
i=response.indexOf("+INQ:");
}
return devices;
}
char* BluetoothSerial::getRemoteName(const char* device_mac) {
// DEBUG
Serial.println("");
Serial.println("Getting a remote name from mac");
String response = "";
char rname[64];
int i;
mySerial.write("AT+RNAME");
mySerial.write(device_mac);
mySerial.write("\r\n");
delay(50);
while (mySerial.available()) response += (char)mySerial.read();
// +RNAME=BC04-B
i=response.indexOf("+RNAME:");
if (i > -1) {
response = response.substring(i);
response.toCharArray(rname, 64);
return rname;
}
return "";
}
void BluetoothSerial::connectTo(const char* device_mac) {
// DEBUG
Serial.println("");
Serial.println("Connect to a mac");
mySerial.write("AT+CONNECT");
mySerial.write(device_mac);
mySerial.write("\r\n");
delay(50);
while (mySerial.available()) {
char c = mySerial.read();
Serial.print(c); // assuming OK
}
Serial.println("");
}
void BluetoothSerial::onSerialConnectionChange(void (*userFunc)(void)) {
attachInterrupt(INTERRUPT_PIN,userFunc,CHANGE);
}
void BluetoothSerial::end() {
mySerial.end();
}
int BluetoothSerial::available() {
return mySerial.available();
}
int BluetoothSerial::read() {
return mySerial.read();
}
int BluetoothSerial::peek() {
return mySerial.peek();
}
void BluetoothSerial::flush() {
mySerial.flush();
}
size_t BluetoothSerial::write(uint8_t c) {
mySerial.write(c);
}
| gpl-3.0 |
StarGate01/map2agb | map2agblib/Tilesets/BlockBehaviour.cs | 4703 | using System;
namespace map2agblib.Tilesets
{
public class BlockBehaviour
{
#region Fields
private byte _hmUsage;
private byte _field2;
private byte _field3;
private byte _field4;
private byte _field5;
private byte _field6;
#endregion
#region Properties
/// <summary>
/// Represents the behavior of a block (range 0-255)
/// </summary>
public byte Behavior { get; set; }
/// <summary>
/// Represents the HM Usage of the block as bitfield (5 bits)
/// </summary>
public byte HmUsage
{
get
{
return _hmUsage;
}
set
{
if (value > (1 << 5))
throw new ArgumentOutOfRangeException("value");
_hmUsage = value;
}
}
/// <summary>
/// Range: 4 bits
/// </summary>
public byte Field2
{
get
{
return _field2;
}
set
{
if (value > (1 << 4))
throw new ArgumentOutOfRangeException("value");
_field2 = value;
}
}
/// <summary>
/// Range: 6 bits
/// </summary>
public byte Field3
{
get
{
return _field3;
}
set
{
if (value > (1 << 6))
throw new ArgumentOutOfRangeException("value");
_field3 = value;
}
}
/// <summary>
/// Range: 3 bits
/// </summary>
public byte Field4
{
get
{
return _field4;
}
set
{
if (value > (1 << 3))
throw new ArgumentOutOfRangeException("value");
_field4 = value;
}
}
/// <summary>
/// Range: 2 bits
/// </summary>
public byte Field5
{
get
{
return _field5;
}
set
{
if (value > (1 << 2))
throw new ArgumentOutOfRangeException("value");
_field5 = value;
}
}
/// <summary>
/// Range: 3 bits
/// </summary>
public byte Field6
{
get
{
return _field6;
}
set
{
if (value > (1 << 3))
throw new ArgumentOutOfRangeException("value");
_field6 = value;
}
}
/// <summary>
/// Range: 1 bit
/// </summary>
public bool Field7 { get; set; }
#endregion
#region Constructor
public BlockBehaviour(uint data)
{
Behavior = (byte)(data & 0xFF); //redundant cast, but who cares
HmUsage = (byte)((data >> 8) & 0x1F);
Field2 = (byte)((data >> 13) & 0xF);
Field3 = (byte)((data >> 17) & 0x3F);
Field4 = (byte)((data >> 23) & 0x7);
Field5 = (byte)((data >> 26) & 0x3);
Field6 = (byte)((data >> 28) & 0x7);
Field7 = (byte)((data >> 31) & 0x1) > 0;
}
/// <summary>
/// Creates a new BlockBehavior object with default values of 0
/// </summary>
public BlockBehaviour()
{
}
/// <summary>
/// Creates a new Blockbehavior object with the given values
/// </summary>
public BlockBehaviour(byte Behavior, byte HmUsage, byte Field2,
byte Field3, byte Field4, byte Field5, byte Field6,
bool Field7)
{
this.Behavior = Behavior;
this.HmUsage = HmUsage;
this.Field2 = Field2;
this.Field3 = Field3;
this.Field4 = Field4;
this.Field5 = Field5;
this.Field6 = Field6;
this.Field7 = Field7;
}
#endregion
#region Methods
public uint ToUint32()
{
return (uint) (Behavior | (HmUsage << 8) | (Field2 << 13) |
(Field3 << 17) | (Field4 << 23) | (Field5 << 26) |
(Field6 << 28) | (Field7 ? (1 << 31) : 0));
}
#endregion
}
}
| gpl-3.0 |
vvc/mtasa-blue | MTA10/mods/shared_logic/CClientVehicle.cpp | 144127 | /*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* (Shared logic for modifications)
* LICENSE: See LICENSE in the top level directory
* FILE: mods/shared_logic/CClientVehicle.cpp
* PURPOSE: Vehicle entity class
* DEVELOPERS: Christian Myhre Lundheim <>
* Ed Lyons <eai@opencoding.net>
* Oliver Brown <>
* Kent Simon <>
* Jax <>
* Cecill Etheredge <ijsf@gmx.net>
* Kevin Whiteside <kevuwk@gmail.com>
* Chris McArthur <>
* Derek Abdine <>
* Stanislav Bobrov <lil_toady@hotmail.com>
* Alberto Alonso <rydencillo@gmail.com>
*
*****************************************************************************/
#include "StdInc.h"
using std::list;
extern CClientGame* g_pClientGame;
std::set < const CClientEntity* > ms_AttachedVehiclesToIgnore;
// To hide the ugly "pointer truncation from DWORD* to unsigned long warning
#pragma warning(disable:4311)
// Maximum distance between current position and target position (for interpolation)
// before we disable interpolation and warp to the position instead
#define VEHICLE_INTERPOLATION_WARP_THRESHOLD 15
#define VEHICLE_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED 10
CClientVehicle::CClientVehicle ( CClientManager* pManager, ElementID ID, unsigned short usModel, unsigned char ucVariation, unsigned char ucVariation2 ) : ClassInit ( this ), CClientStreamElement ( pManager->GetVehicleStreamer (), ID )
{
CClientEntityRefManager::AddEntityRefs ( ENTITY_REF_DEBUG ( this, "CClientVehicle" ), &m_pDriver, &m_pOccupyingDriver, &m_pPreviousLink, &m_pNextLink, &m_pTowedVehicle, &m_pTowedByVehicle, &m_pPickedUpWinchEntity, NULL );
// Initialize members
m_pManager = pManager;
m_pObjectManager = m_pManager->GetObjectManager ();
m_pVehicleManager = pManager->GetVehicleManager ();
m_pModelRequester = pManager->GetModelRequestManager ();
m_usModel = usModel;
m_eVehicleType = CClientVehicleManager::GetVehicleType ( usModel );
m_bHasDamageModel = CClientVehicleManager::HasDamageModel ( m_eVehicleType );
m_pVehicle = NULL;
m_pUpgrades = new CVehicleUpgrades ( this );
m_pClump = NULL;
m_pOriginalHandlingEntry = g_pGame->GetHandlingManager ()->GetOriginalHandlingData ( static_cast < eVehicleTypes > ( usModel ) );
m_pHandlingEntry = g_pGame->GetHandlingManager ()->CreateHandlingData ();
m_pHandlingEntry->Assign ( m_pOriginalHandlingEntry );
SetTypeName ( "vehicle" );
// Grab the model info and the bounding box
m_pModelInfo = g_pGame->GetModelInfo ( usModel );
m_ucMaxPassengers = CClientVehicleManager::GetMaxPassengerCount ( usModel );
// Set our default properties
m_pDriver = NULL;
m_pOccupyingDriver = NULL;
memset ( &m_pPassengers[0], 0, sizeof ( m_pPassengers ) );
memset ( &m_pOccupyingPassengers[0], 0, sizeof ( m_pOccupyingPassengers ) );
m_pPreviousLink = NULL;
m_pNextLink = NULL;
m_Matrix.vFront.fY = 1.0f;
m_Matrix.vUp.fZ = 1.0f;
m_Matrix.vRight.fX = 1.0f;
m_MatrixLast = m_Matrix;
m_dLastRotationTime = 0;
m_fHealth = DEFAULT_VEHICLE_HEALTH;
m_fTurretHorizontal = 0.0f;
m_fTurretVertical = 0.0f;
m_fGasPedal = 0.0f;
m_bVisible = true;
m_bIsCollisionEnabled = true;
m_bEngineOn = false;
m_bEngineBroken = false;
m_bSireneOrAlarmActive = false;
m_bLandingGearDown = true;
m_usAdjustablePropertyValue = 0;
for ( unsigned int i = 0; i < 6; ++i )
{
m_bAllowDoorRatioSetting [ i ] = true;
m_fDoorOpenRatio [ i ] = 0.0f;
m_doorInterp.fStart [ i ] = 0.0f;
m_doorInterp.fTarget [ i ] = 0.0f;
m_doorInterp.ulStartTime [ i ] = 0UL;
m_doorInterp.ulTargetTime [ i ] = 0UL;
}
m_bSwingingDoorsAllowed = false;
m_bDoorsLocked = false;
m_bDoorsUndamageable = false;
m_bCanShootPetrolTank = true;
m_bCanBeTargettedByHeatSeekingMissiles = true;
m_bColorSaved = false;
m_bIsFrozen = false;
m_bScriptFrozen = false;
m_bFrozenWaitingForGroundToLoad = false;
m_fGroundCheckTolerance = 0.f;
m_fObjectsAroundTolerance = 0.f;
GetInitialDoorStates ( m_ucDoorStates );
memset ( &m_ucWheelStates[0], 0, sizeof ( m_ucWheelStates ) );
memset ( &m_ucPanelStates[0], 0, sizeof ( m_ucPanelStates ) );
memset ( &m_ucLightStates[0], 0, sizeof ( m_ucLightStates ) );
m_bCanBeDamaged = true;
m_bSyncUnoccupiedDamage = false;
m_bScriptCanBeDamaged = true;
m_bTyresCanBurst = true;
m_ucOverrideLights = 0;
m_pTowedVehicle = NULL;
m_pTowedByVehicle = NULL;
m_eWinchType = WINCH_NONE;
m_pPickedUpWinchEntity = NULL;
m_ucPaintjob = 3;
m_fDirtLevel = 0.0f;
m_bSmokeTrail = false;
m_bJustBlewUp = false;
m_ucAlpha = 255;
m_bAlphaChanged = false;
m_bBlowNextFrame = false;
m_bIsOnGround = false;
m_ulIllegalTowBreakTime = 0;
m_bBlown = false;
m_LastSyncedData = new SLastSyncedVehData;
m_bIsDerailed = false;
m_bIsDerailable = true;
m_bTrainDirection = false;
m_fTrainSpeed = 0.0f;
m_fTrainPosition = -1.0f;
m_ucTrackID = 0xFF;
m_bChainEngine = false;
m_bTaxiLightOn = false;
m_vecGravity = CVector ( 0.0f, 0.0f, -1.0f );
m_HeadLightColor = SColorRGBA ( 255, 255, 255, 255 );
m_bHeliSearchLightVisible = false;
m_fHeliRotorSpeed = 0.0f;
m_bHasCustomHandling = false;
m_ucVariation = ucVariation;
m_ucVariation2 = ucVariation2;
m_bEnableHeliBladeCollisions = true;
m_fNitroLevel = 1.0f;
m_cNitroCount = 0;
#ifdef MTA_DEBUG
m_pLastSyncer = NULL;
m_ulLastSyncTime = 0;
m_szLastSyncType = "none";
#endif
m_interp.rot.ulFinishTime = 0;
m_interp.pos.ulFinishTime = 0;
ResetInterpolation ();
// Check if we have landing gears
m_bHasLandingGear = DoCheckHasLandingGear ();
m_bHasAdjustableProperty = CClientVehicleManager::HasAdjustableProperty ( m_usModel );
// Add this vehicle to the vehicle list
m_pVehicleManager->AddToList ( this );
m_tSirenBeaconInfo.m_bSirenSilent = false;
// clear our component data to regenerate
m_ComponentData.clear ( );
// Prepare the sirens
RemoveVehicleSirens();
// reset our fall through map count
m_ucFellThroughMapCount = 1;
}
CClientVehicle::~CClientVehicle ( void )
{
// Unreference us
m_pManager->UnreferenceEntity ( this );
// Unlink any towing attachments
SetTowedVehicle ( NULL );
if ( m_pTowedByVehicle )
m_pTowedByVehicle->SetTowedVehicle ( NULL );
SetNextTrainCarriage ( NULL );
SetPreviousTrainCarriage ( NULL );
AttachTo ( NULL );
// Remove all our projectiles
RemoveAllProjectiles ();
// Destroy the vehicle
Destroy ();
// Make sure we haven't requested any model that will make us crash
// when it's done loading.
m_pModelRequester->Cancel ( this, false );
// Unreference us from the driving player model (if any)
if ( m_pDriver )
{
m_pDriver->SetVehicleInOutState ( VEHICLE_INOUT_NONE );
UnpairPedAndVehicle( m_pDriver, this );
}
// And the occupying ones eventually
if ( m_pOccupyingDriver )
{
m_pOccupyingDriver->SetVehicleInOutState ( VEHICLE_INOUT_NONE );
UnpairPedAndVehicle( m_pOccupyingDriver, this );
}
// And the passenger models
int i;
for ( i = 0; i < (sizeof(m_pPassengers)/sizeof(CClientPed*)); i++ )
{
if ( m_pPassengers [i] )
{
m_pPassengers [i]->m_uiOccupiedVehicleSeat = 0;
m_pPassengers [i]->SetVehicleInOutState ( VEHICLE_INOUT_NONE );
UnpairPedAndVehicle( m_pPassengers [i], this );
}
}
// Occupying passenger models
for ( i = 0; i < (sizeof(m_pOccupyingPassengers)/sizeof(CClientPed*)); i++ )
{
if ( m_pOccupyingPassengers [i] )
{
m_pOccupyingPassengers [i]->m_uiOccupiedVehicleSeat = 0;
m_pOccupyingPassengers [i]->SetVehicleInOutState ( VEHICLE_INOUT_NONE );
UnpairPedAndVehicle( m_pOccupyingPassengers [i], this );
}
}
// Remove us from the vehicle list
Unlink ();
delete m_pUpgrades;
delete m_pHandlingEntry;
delete m_LastSyncedData;
CClientEntityRefManager::RemoveEntityRefs ( 0, &m_pDriver, &m_pOccupyingDriver, &m_pPreviousLink, &m_pNextLink, &m_pTowedVehicle, &m_pTowedByVehicle, &m_pPickedUpWinchEntity, NULL );
}
void CClientVehicle::Unlink ( void )
{
m_pVehicleManager->RemoveFromLists ( this );
}
void CClientVehicle::GetPosition ( CVector& vecPosition ) const
{
if ( m_bIsFrozen )
{
vecPosition = m_matFrozen.vPos;
}
// Is this a trailer being towed?
else if ( m_pTowedByVehicle )
{
// Is it streamed out or not attached properly?
if ( !m_pVehicle || !m_pVehicle->GetTowedByVehicle () )
{
// Grab the position behind the vehicle (should take X/Y rotation into acount)
// Prevent infinte recursion by ignoring attach link back to this towed vehicle (during GetPosition call)
MapInsert( ms_AttachedVehiclesToIgnore, this );
m_pTowedByVehicle->GetPosition ( vecPosition );
MapRemove( ms_AttachedVehiclesToIgnore, this );
CVector vecRotation;
m_pTowedByVehicle->GetRotationRadians ( vecRotation );
vecPosition.fX -= ( 5.0f * sin ( vecRotation.fZ ) );
vecPosition.fY -= ( 5.0f * cos ( vecRotation.fZ ) );
}
else
{
vecPosition = *m_pVehicle->GetPosition ( );
}
}
// Streamed in?
else if ( m_pVehicle )
{
vecPosition = *m_pVehicle->GetPosition ();
}
// Attached to something?
else if ( m_pAttachedToEntity && !MapContains( ms_AttachedVehiclesToIgnore, m_pAttachedToEntity ) )
{
m_pAttachedToEntity->GetPosition ( vecPosition );
vecPosition += m_vecAttachedPosition;
}
else
{
vecPosition = m_Matrix.vPos;
}
}
void CClientVehicle::SetPosition ( const CVector& vecPosition, bool bResetInterpolation, bool bAllowGroundLoadFreeze )
{
// Is the local player in the vehicle
if ( g_pClientGame->GetLocalPlayer ()->GetOccupiedVehicle () == this )
{
// If move is big enough, do ground checks
float DistanceMoved = ( m_Matrix.vPos - vecPosition ).Length ();
if ( DistanceMoved > 50 && !IsFrozen () && bAllowGroundLoadFreeze )
SetFrozenWaitingForGroundToLoad ( true, true );
}
if ( m_pVehicle )
{
m_pVehicle->SetPosition ( const_cast < CVector* > ( &vecPosition ) );
// Jax: can someone find a cleaner alternative for this, it fixes vehicles not being affected by gravity (supposed to be a flag used only on creation, but isnt)
if ( !m_pDriver )
{
CVector vecMoveSpeed;
m_pVehicle->GetMoveSpeed ( &vecMoveSpeed );
if ( vecMoveSpeed.fX == 0.0f && vecMoveSpeed.fY == 0.0f && vecMoveSpeed.fZ == 0.0f )
{
vecMoveSpeed.fZ -= 0.01f;
m_pVehicle->SetMoveSpeed ( &vecMoveSpeed );
}
}
}
// Have we moved to a different position?
if ( m_Matrix.vPos != vecPosition )
{
// Store our new position
m_Matrix.vPos = vecPosition;
m_matFrozen.vPos = vecPosition;
// Update our streaming position
UpdateStreamPosition ( vecPosition );
}
// If we have any occupants, update their positions
for ( int i = 0; i <= NUMELMS ( m_pPassengers ) ; i++ )
if ( CClientPed* pOccupant = GetOccupant ( i ) )
pOccupant->SetPosition ( vecPosition );
// Reset interpolation
if ( bResetInterpolation )
{
RemoveTargetPosition ();
// Tell GTA it should update the train rail position (set this here since we don't want to call this on interpolation)
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN && !IsDerailed () && !IsStreamedIn () )
{
m_fTrainPosition = -1.0f;
m_ucTrackID = 0xFF;
}
}
}
void CClientVehicle::UpdatePedPositions ( const CVector& vecPosition )
{
// Have we moved to a different position?
if ( m_Matrix.vPos != vecPosition )
{
// Store our new position
m_Matrix.vPos = vecPosition;
m_matFrozen.vPos = vecPosition;
// Update our streaming position
UpdateStreamPosition ( vecPosition );
}
// If we have any occupants, update their positions
for ( int i = 0; i <= NUMELMS ( m_pPassengers ) ; i++ )
if ( CClientPed* pOccupant = GetOccupant ( i ) )
pOccupant->SetPosition ( vecPosition );
}
void CClientVehicle::GetRotationDegrees ( CVector& vecRotation ) const
{
// Grab our rotations in radians
GetRotationRadians ( vecRotation );
ConvertRadiansToDegrees ( vecRotation );
}
void CClientVehicle::GetRotationRadians ( CVector& vecRotation ) const
{
// Grab the rotation in radians from the matrix
CMatrix matTemp;
GetMatrix ( matTemp );
g_pMultiplayer->ConvertMatrixToEulerAngles ( matTemp, vecRotation.fX, vecRotation.fY, vecRotation.fZ );
// ChrML: We flip the actual rotation direction so that the rotation is consistent with
// objects and players.
vecRotation.fX = ( 2 * PI ) - vecRotation.fX;
vecRotation.fY = ( 2 * PI ) - vecRotation.fY;
vecRotation.fZ = ( 2 * PI ) - vecRotation.fZ;
}
void CClientVehicle::SetRotationDegrees ( const CVector& vecRotation, bool bResetInterpolation )
{
// Convert from degrees to radians
CVector vecTemp;
vecTemp.fX = vecRotation.fX * 3.1415926535897932384626433832795f / 180.0f;
vecTemp.fY = vecRotation.fY * 3.1415926535897932384626433832795f / 180.0f;
vecTemp.fZ = vecRotation.fZ * 3.1415926535897932384626433832795f / 180.0f;
// Set the rotation as radians
SetRotationRadians ( vecTemp, bResetInterpolation );
}
void CClientVehicle::SetRotationRadians ( const CVector& vecRotation, bool bResetInterpolation )
{
// Grab the matrix, apply the rotation to it and set it again
// ChrML: We flip the actual rotation direction so that the rotation is consistent with
// objects and players.
CMatrix matTemp;
GetMatrix ( matTemp );
g_pMultiplayer->ConvertEulerAnglesToMatrix ( matTemp, ( 2 * PI ) - vecRotation.fX, ( 2 * PI ) - vecRotation.fY, ( 2 * PI ) - vecRotation.fZ );
SetMatrix ( matTemp );
// Reset target rotation
if ( bResetInterpolation )
RemoveTargetRotation ();
}
void CClientVehicle::ReportMissionAudioEvent ( unsigned short usSound )
{
if ( m_pVehicle )
{
// g_pGame->GetAudio ()->ReportMissionAudioEvent ( m_pVehicle, usSound );
}
}
bool CClientVehicle::SetTaxiLightOn ( bool bLightOn )
{
m_bTaxiLightOn = bLightOn;
if ( m_pVehicle )
{
m_pVehicle->SetTaxiLightOn ( bLightOn );
return true;
}
return false;
}
float CClientVehicle::GetDistanceFromCentreOfMassToBaseOfModel ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetDistanceFromCentreOfMassToBaseOfModel ();
}
return 0.0f;
}
bool CClientVehicle::GetMatrix ( CMatrix& Matrix ) const
{
if ( m_bIsFrozen )
{
Matrix = m_matFrozen;
}
else
{
if ( m_pVehicle )
{
m_pVehicle->GetMatrix ( &Matrix );
}
else
{
Matrix = m_Matrix;
}
}
return true;
}
bool CClientVehicle::SetMatrix ( const CMatrix& Matrix )
{
if ( m_pVehicle )
{
m_pVehicle->SetMatrix ( const_cast < CMatrix* > ( &Matrix ) );
// If it is a boat, we need to call FixBoatOrientation or it won't move/rotate properly
if ( m_eVehicleType == CLIENTVEHICLE_BOAT )
{
m_pVehicle->FixBoatOrientation ();
}
}
// Have we moved to a different position?
if ( m_Matrix.vPos != Matrix.vPos )
{
// Update our streaming position
UpdateStreamPosition ( Matrix.vPos );
}
m_Matrix = Matrix;
m_matFrozen = Matrix;
m_MatrixPure = Matrix;
// If we have any occupants, update their positions
if ( m_pDriver ) m_pDriver->SetPosition ( m_Matrix.vPos );
for ( int i = 0; i < ( sizeof ( m_pPassengers ) / sizeof ( CClientPed * ) ) ; i++ )
{
if ( m_pPassengers [ i ] )
{
m_pPassengers [ i ]->SetPosition ( m_Matrix.vPos );
}
}
return true;
}
void CClientVehicle::GetMoveSpeed ( CVector& vecMoveSpeed ) const
{
if ( m_bIsFrozen )
{
vecMoveSpeed = CVector ( 0, 0, 0 );
}
else
{
if ( m_pVehicle )
{
m_pVehicle->GetMoveSpeed ( &vecMoveSpeed );
}
else
{
vecMoveSpeed = m_vecMoveSpeed;
}
}
}
void CClientVehicle::GetMoveSpeedMeters ( CVector& vecMoveSpeed ) const
{
if ( m_bIsFrozen )
{
vecMoveSpeed = CVector ( 0, 0, 0 );
}
else
{
vecMoveSpeed = m_vecMoveSpeedMeters;
}
}
void CClientVehicle::SetMoveSpeed ( const CVector& vecMoveSpeed )
{
if ( !m_bIsFrozen )
{
if ( m_pVehicle )
{
m_pVehicle->SetMoveSpeed ( const_cast < CVector* > ( &vecMoveSpeed ) );
}
m_vecMoveSpeed = vecMoveSpeed;
if ( IsFrozenWaitingForGroundToLoad() )
m_vecWaitingForGroundSavedMoveSpeed = vecMoveSpeed;
}
}
void CClientVehicle::GetTurnSpeed ( CVector& vecTurnSpeed ) const
{
if ( m_bIsFrozen )
{
vecTurnSpeed = CVector ( 0, 0, 0 );
}
if ( m_pVehicle )
{
m_pVehicle->GetTurnSpeed ( &vecTurnSpeed );
}
else
{
vecTurnSpeed = m_vecTurnSpeed;
}
}
void CClientVehicle::SetTurnSpeed ( const CVector& vecTurnSpeed )
{
if ( !m_bIsFrozen )
{
if ( m_pVehicle )
{
m_pVehicle->SetTurnSpeed ( const_cast < CVector* > ( &vecTurnSpeed ) );
}
m_vecTurnSpeed = vecTurnSpeed;
if ( IsFrozenWaitingForGroundToLoad() )
m_vecWaitingForGroundSavedTurnSpeed = vecTurnSpeed;
}
}
bool CClientVehicle::IsVisible ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsVisible ();
}
return m_bVisible;
}
void CClientVehicle::SetVisible ( bool bVisible )
{
if ( m_pVehicle )
{
m_pVehicle->SetVisible ( bVisible );
}
m_bVisible = bVisible;
}
void CClientVehicle::SetDoorOpenRatioInterpolated ( unsigned char ucDoor, float fRatio, unsigned long ulDelay )
{
unsigned long ulTime = CClientTime::GetTime ();
m_doorInterp.fStart [ ucDoor ] = m_fDoorOpenRatio [ ucDoor ];
m_doorInterp.fTarget [ ucDoor ] = fRatio;
m_doorInterp.ulStartTime [ ucDoor ] = ulTime;
m_doorInterp.ulTargetTime [ ucDoor ] = ulTime + ulDelay;
}
void CClientVehicle::ResetDoorInterpolation ( )
{
for ( unsigned char i = 0; i < 6; ++i )
{
if ( m_doorInterp.ulTargetTime [ i ] != 0 )
SetDoorOpenRatio ( i, m_doorInterp.fTarget [ i ], 0, true );
m_doorInterp.ulTargetTime [ i ] = 0;
}
}
void CClientVehicle::CancelDoorInterpolation ( unsigned char ucDoor )
{
m_doorInterp.ulTargetTime [ ucDoor ] = 0;
}
void CClientVehicle::ProcessDoorInterpolation ()
{
unsigned long ulTime = CClientTime::GetTime ();
for ( unsigned char i = 0; i < 6; ++i )
{
if ( m_doorInterp.ulTargetTime [ i ] != 0 )
{
if ( m_doorInterp.ulTargetTime [ i ] <= ulTime )
{
// Interpolation finished.
SetDoorOpenRatio ( i, m_doorInterp.fTarget [ i ], 0, true );
m_doorInterp.ulTargetTime [ i ] = 0;
}
else
{
unsigned long ulElapsedTime = ulTime - m_doorInterp.ulStartTime [ i ];
unsigned long ulDelay = m_doorInterp.ulTargetTime [ i ] - m_doorInterp.ulStartTime [ i ];
float fStep = ulElapsedTime / (float)ulDelay;
float fRatio = SharedUtil::Lerp ( m_doorInterp.fStart [ i ], fStep, m_doorInterp.fTarget [ i ] );
SetDoorOpenRatio ( i, fRatio, 0, true );
}
}
}
}
void CClientVehicle::SetDoorOpenRatio ( unsigned char ucDoor, float fRatio, unsigned long ulDelay, bool bForced )
{
unsigned char ucSeat;
if ( ucDoor <= 5 )
{
bool bAllow = m_bAllowDoorRatioSetting [ ucDoor ];
// Prevent setting the door angle ratio while a ped is entering/leaving the vehicle.
if ( bAllow && bForced == false )
{
switch ( ucDoor )
{
case 2:
bAllow = m_pOccupyingDriver == 0;
break;
case 3:
case 4:
case 5:
ucSeat = ucDoor - 2;
bAllow = m_pOccupyingPassengers [ ucSeat ] == 0;
break;
}
}
if ( bAllow )
{
if ( ulDelay == 0UL )
{
if ( m_pVehicle )
{
m_pVehicle->OpenDoor ( ucDoor, fRatio, false );
}
m_fDoorOpenRatio [ ucDoor ] = fRatio;
}
else
{
SetDoorOpenRatioInterpolated ( ucDoor, fRatio, ulDelay );
}
}
}
}
float CClientVehicle::GetDoorOpenRatio ( unsigned char ucDoor )
{
if ( ucDoor <= 5 )
{
if ( m_pVehicle )
{
return m_pVehicle->GetDoor ( ucDoor )->GetAngleOpenRatio ();
}
return m_fDoorOpenRatio [ ucDoor ];
}
return 0.0f;
}
void CClientVehicle::SetSwingingDoorsAllowed ( bool bAllowed )
{
if ( m_pVehicle )
{
m_pVehicle->SetSwingingDoorsAllowed ( bAllowed );
}
m_bSwingingDoorsAllowed = bAllowed;
}
bool CClientVehicle::AreSwingingDoorsAllowed () const
{
if ( m_pVehicle )
{
return m_pVehicle->AreSwingingDoorsAllowed ();
}
return m_bSwingingDoorsAllowed;
}
void CClientVehicle::AllowDoorRatioSetting ( unsigned char ucDoor, bool bAllow, bool bAutoReallowAfterDelay )
{
if ( ucDoor < NUMELMS(m_bAllowDoorRatioSetting) )
{
m_bAllowDoorRatioSetting [ucDoor] = bAllow;
CancelDoorInterpolation ( ucDoor );
MapRemove( m_AutoReallowDoorRatioMap, (eDoors)ucDoor );
if ( !bAllow && bAutoReallowAfterDelay )
{
MapSet( m_AutoReallowDoorRatioMap, (eDoors)ucDoor, CTickCount::Now() );
}
}
}
bool CClientVehicle::AreDoorsLocked ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->AreDoorsLocked ();
}
return m_bDoorsLocked;
}
void CClientVehicle::SetDoorsLocked ( bool bLocked )
{
if ( m_pVehicle )
{
m_pVehicle->LockDoors ( bLocked );
}
m_bDoorsLocked = bLocked;
}
bool CClientVehicle::AreDoorsUndamageable ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->AreDoorsUndamageable ();
}
return m_bDoorsUndamageable;
}
void CClientVehicle::SetDoorsUndamageable ( bool bUndamageable )
{
if ( m_pVehicle )
{
m_pVehicle->SetDoorsUndamageable ( bUndamageable );
}
m_bDoorsUndamageable = bUndamageable;
}
float CClientVehicle::GetHealth ( void ) const
{
// If we're blown, return 0
if ( m_bBlown ) return 0.0f;
if ( m_pVehicle )
{
return m_pVehicle->GetHealth ();
}
return m_fHealth;
}
void CClientVehicle::SetHealth ( float fHealth )
{
if ( m_pVehicle )
{
// Is the car is dead and we want to un-die it?
if ( fHealth > 0.0f && GetHealth () <= 0.0f )
{
Destroy ();
m_fHealth = fHealth; // NEEDS to be here!
Create ();
}
else
{
m_pVehicle->SetHealth ( fHealth );
}
}
m_fHealth = fHealth;
}
void CClientVehicle::Fix ( void )
{
m_bBlown = false;
m_bBlowNextFrame = false;
if ( m_pVehicle )
{
m_pVehicle->Fix ();
// Make sure its visible, if its supposed to be
m_pVehicle->SetVisible ( m_bVisible );
}
SetHealth ( DEFAULT_VEHICLE_HEALTH );
SFixedArray < unsigned char, MAX_DOORS > ucDoorStates;
GetInitialDoorStates ( ucDoorStates );
for ( int i = 0 ; i < MAX_DOORS ; i++ ) SetDoorStatus ( i, ucDoorStates [ i ] );
for ( int i = 0 ; i < MAX_PANELS ; i++ ) SetPanelStatus ( i, 0 );
for ( int i = 0 ; i < MAX_LIGHTS ; i++ ) SetLightStatus ( i, 0 );
for ( int i = 0 ; i < MAX_WHEELS ; i++ ) SetWheelStatus ( i, 0 );
// Grab our component data
std::map < SString, SVehicleComponentData > ::iterator iter = m_ComponentData.begin ();
// Loop through our component data
for ( ; iter != m_ComponentData.end () ; iter++ )
{
// store our string in a temporary variable
SString strTemp = (*iter).first;
// get our poisition and rotation and store it into
//GetComponentPosition ( strTemp, (*iter).second.m_vecComponentPosition );
//GetComponentRotation ( strTemp, (*iter).second.m_vecComponentRotation );
// is our position changed?
if ( (*iter).second.m_bPositionChanged )
{
// Make sure it's different
if ( (*iter).second.m_vecOriginalComponentPosition != (*iter).second.m_vecComponentPosition )
{
// apply our new position
SetComponentPosition( strTemp, (*iter).second.m_vecComponentPosition );
}
}
// is our position changed?
if ( (*iter).second.m_bRotationChanged )
{
// Make sure it's different
if ( (*iter).second.m_vecOriginalComponentRotation != (*iter).second.m_vecComponentRotation )
{
// apple our new position
SetComponentRotation( strTemp, (*iter).second.m_vecComponentRotation );
}
}
// set our visibility
SetComponentVisible ( strTemp, (*iter).second.m_bVisible );
}
}
void CClientVehicle::Blow ( bool bAllowMovement )
{
if ( m_pVehicle )
{
// Make sure it can be damaged
m_pVehicle->SetCanBeDamaged ( true );
// Grab our current speeds
CVector vecMoveSpeed, vecTurnSpeed;
GetMoveSpeed ( vecMoveSpeed );
GetTurnSpeed ( vecTurnSpeed );
// Set the health to 0
m_pVehicle->SetHealth ( 0.0f );
// "Fuck" the car completely, so we don't have weird client-side jumpyness because of differently synced wheel states on clients
FuckCarCompletely ( true );
m_pVehicle->BlowUp ( NULL, 0 );
// And force the wheel states to "burst"
SetWheelStatus ( FRONT_LEFT_WHEEL, DT_WHEEL_BURST );
SetWheelStatus ( FRONT_RIGHT_WHEEL, DT_WHEEL_BURST );
SetWheelStatus ( REAR_LEFT_WHEEL, DT_WHEEL_BURST );
SetWheelStatus ( REAR_RIGHT_WHEEL, DT_WHEEL_BURST );
if ( !bAllowMovement )
{
// Make sure it doesn't change speeds (slightly cleaner for syncing)
SetMoveSpeed ( vecMoveSpeed );
SetTurnSpeed ( vecTurnSpeed );
}
// Restore the old can be damaged state
CalcAndUpdateCanBeDamagedFlag ();
}
m_fHealth = 0.0f;
m_bBlown = true;
}
CVehicleColor& CClientVehicle::GetColor ( void )
{
if ( m_pVehicle )
{
SColor colors[4];
m_pVehicle->GetColor ( &colors[0], &colors[1], &colors[2], &colors[3], 0 );
m_Color.SetRGBColors ( colors[0], colors[1], colors[2], colors[3] );
}
return m_Color;
}
void CClientVehicle::SetColor ( const CVehicleColor& color )
{
m_Color = color;
if ( m_pVehicle )
{
m_pVehicle->SetColor ( m_Color.GetRGBColor ( 0 ), m_Color.GetRGBColor ( 1 ), m_Color.GetRGBColor ( 2 ), m_Color.GetRGBColor ( 3 ), 0 );
}
}
void CClientVehicle::GetTurretRotation ( float& fHorizontal, float& fVertical )
{
if ( m_pVehicle )
{
// Car, plane or quad?
if ( m_eVehicleType == CLIENTVEHICLE_CAR ||
m_eVehicleType == CLIENTVEHICLE_PLANE ||
m_eVehicleType == CLIENTVEHICLE_QUADBIKE )
{
m_pVehicle->GetTurretRotation ( &fHorizontal, &fVertical );
}
else
{
fHorizontal = 0;
fVertical = 0;
}
}
else
{
fHorizontal = m_fTurretHorizontal;
fVertical = m_fTurretVertical;
}
}
void CClientVehicle::SetTurretRotation ( float fHorizontal, float fVertical )
{
if ( m_pVehicle )
{
// Car, plane or quad?
if ( m_eVehicleType == CLIENTVEHICLE_CAR ||
m_eVehicleType == CLIENTVEHICLE_PLANE ||
m_eVehicleType == CLIENTVEHICLE_QUADBIKE )
{
m_pVehicle->SetTurretRotation ( fHorizontal, fVertical );
}
}
m_fTurretHorizontal = fHorizontal;
m_fTurretVertical = fVertical;
}
void CClientVehicle::SetModelBlocking ( unsigned short usModel, unsigned char ucVariant, unsigned char ucVariant2 )
{
// Different vehicle ID than we have now?
if ( m_usModel != usModel )
{
// Destroy the old vehicle if we have one
if ( m_pVehicle )
{
Destroy ();
}
// Get rid of our upgrades, they might be incompatible
if ( m_pUpgrades )
m_pUpgrades->RemoveAll ( false );
// Are we swapping from a vortex or skimmer?
bool bResetWheelAndDoorStates = ( m_usModel == VT_VORTEX || m_usModel == VT_SKIMMER || ( m_eVehicleType == CLIENTVEHICLE_PLANE && m_eVehicleType != CClientVehicleManager::GetVehicleType ( usModel ) ) );
// Apply variant requirements
if ( ucVariant == 255 && ucVariant2 == 255 )
CClientVehicleManager::GetRandomVariation ( usModel, ucVariant, ucVariant2 );
m_ucVariation = ucVariant;
m_ucVariation2 = ucVariant2;
// Set the new vehicle id and type
m_usModel = usModel;
m_eVehicleType = CClientVehicleManager::GetVehicleType ( usModel );
m_bHasDamageModel = CClientVehicleManager::HasDamageModel ( m_eVehicleType );
if ( bResetWheelAndDoorStates )
{
GetInitialDoorStates ( m_ucDoorStates );
memset ( &m_ucWheelStates[0], 0, sizeof ( m_ucWheelStates ) );
}
// Check if we have landing gears and adjustable properties
m_bHasLandingGear = DoCheckHasLandingGear ();
m_bHasAdjustableProperty = CClientVehicleManager::HasAdjustableProperty ( m_usModel );
m_usAdjustablePropertyValue = 0;
// Grab the model info and the bounding box
m_pModelInfo = g_pGame->GetModelInfo ( usModel );
m_ucMaxPassengers = CClientVehicleManager::GetMaxPassengerCount ( usModel );
// Reset handling to fit the vehicle
m_pOriginalHandlingEntry = g_pGame->GetHandlingManager()->GetOriginalHandlingData ( (eVehicleTypes)usModel );
m_pHandlingEntry->Assign ( m_pOriginalHandlingEntry );
ApplyHandling ();
SetSirenOrAlarmActive ( false );
// clear our component data to regenerate it
m_ComponentData.clear ( );
// Create the vehicle if we're streamed in
if ( IsStreamedIn () )
{
// Preload the model
if( !m_pModelInfo->IsLoaded () )
{
m_pModelInfo->Request ( BLOCKING, "CClientVehicle::SetModelBlocking" );
m_pModelInfo->MakeCustomModel ();
}
// Create the vehicle now. Don't prerequest the model ID for this func.
Create ();
}
}
}
void CClientVehicle::SetVariant ( unsigned char ucVariant, unsigned char ucVariant2 )
{
m_ucVariation = ucVariant;
m_ucVariation2 = ucVariant2;
// clear our component data to regenerate it
m_ComponentData.clear ( );
ReCreate ( );
}
bool CClientVehicle::IsEngineBroken ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsEngineBroken ();
}
return m_bEngineBroken;
}
void CClientVehicle::SetEngineBroken ( bool bEngineBroken )
{
if ( m_pVehicle )
{
m_pVehicle->SetEngineBroken ( bEngineBroken );
m_pVehicle->SetEngineOn ( !bEngineBroken );
// We need to recreate the vehicle if we're going from broken to unbroken
if ( !bEngineBroken && m_pVehicle->IsEngineBroken () )
{
ReCreate ();
}
}
m_bEngineBroken = bEngineBroken;
}
bool CClientVehicle::IsEngineOn ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsEngineOn ();
}
return m_bEngineOn;
}
void CClientVehicle::SetEngineOn ( bool bEngineOn )
{
if ( m_pVehicle )
{
m_pVehicle->SetEngineOn ( bEngineOn );
}
m_bEngineOn = bEngineOn;
}
bool CClientVehicle::CanBeDamaged ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetCanBeDamaged ();
}
return m_bCanBeDamaged;
}
// This can be called frequently to ensure the correct setting gets to the SA vehicle
void CClientVehicle::CalcAndUpdateCanBeDamagedFlag ( void )
{
bool bCanBeDamaged = false;
// CanBeDamaged if local driver or syncing unoccupiedVehicle
if ( m_pDriver && m_pDriver->IsLocalPlayer () )
bCanBeDamaged = true;
if ( m_bSyncUnoccupiedDamage )
bCanBeDamaged = true;
// Script override
if ( !m_bScriptCanBeDamaged )
bCanBeDamaged = false;
if ( m_pVehicle )
{
m_pVehicle->SetCanBeDamaged ( bCanBeDamaged );
}
m_bCanBeDamaged = bCanBeDamaged;
}
void CClientVehicle::SetScriptCanBeDamaged ( bool bCanBeDamaged )
{
// Needed so script doesn't interfere with syncing unoccupied vehicles
m_bScriptCanBeDamaged = bCanBeDamaged;
CalcAndUpdateCanBeDamagedFlag ();
CalcAndUpdateTyresCanBurstFlag ();
}
void CClientVehicle::SetSyncUnoccupiedDamage ( bool bCanBeDamaged )
{
m_bSyncUnoccupiedDamage = bCanBeDamaged;
CalcAndUpdateCanBeDamagedFlag ();
CalcAndUpdateTyresCanBurstFlag ();
}
bool CClientVehicle::GetTyresCanBurst ( void )
{
if ( m_pVehicle )
{
return !m_pVehicle->GetTyresDontBurst ();
}
return m_bTyresCanBurst;
}
// This can be called frequently to ensure the correct setting gets to the SA vehicle
void CClientVehicle::CalcAndUpdateTyresCanBurstFlag ( void )
{
bool bTyresCanBurst = false;
// TyresCanBurst if local driver or syncing unoccupiedVehicle
if ( m_pDriver && m_pDriver->IsLocalPlayer () )
bTyresCanBurst = true;
if ( m_bSyncUnoccupiedDamage )
bTyresCanBurst = true;
// Script override
if ( !m_bScriptCanBeDamaged )
bTyresCanBurst = false;
if ( m_pVehicle )
{
m_pVehicle->SetTyresDontBurst ( !bTyresCanBurst );
}
m_bTyresCanBurst = bTyresCanBurst;
}
float CClientVehicle::GetGasPedal ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetGasPedal ();
}
return m_fGasPedal;
}
bool CClientVehicle::IsBelowWater ( void ) const
{
CVector vecPosition;
GetPosition ( vecPosition );
float fWaterLevel = 0.0f;
if ( g_pGame->GetWaterManager ()->GetWaterLevel ( vecPosition, &fWaterLevel, true, NULL ) )
{
if ( vecPosition.fZ < fWaterLevel - 0.7 )
{
return true;
}
}
return false;
}
bool CClientVehicle::IsDrowning ( void ) const
{
if ( m_pVehicle )
{
return m_pVehicle->IsDrowning ();
}
return false;
}
bool CClientVehicle::IsDriven ( void ) const
{
if ( m_pVehicle )
{
return m_pVehicle->IsBeingDriven () ? true:false;
}
else
{
return GetOccupant ( 0 ) != NULL;
}
}
bool CClientVehicle::IsUpsideDown ( void ) const
{
if ( m_pVehicle )
{
return m_pVehicle->IsUpsideDown ();
}
// TODO: Figure out this using matrix?
return false;
}
bool CClientVehicle::IsBlown ( void ) const
{
// Game layer functions aren't reliable
return m_bBlown;
}
bool CClientVehicle::IsSirenOrAlarmActive ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsSirenOrAlarmActive () ? true:false;
}
return m_bSireneOrAlarmActive;
}
void CClientVehicle::SetSirenOrAlarmActive ( bool bActive )
{
if ( m_pVehicle )
{
m_pVehicle->SetSirenOrAlarmActive ( bActive );
}
m_bSireneOrAlarmActive = bActive;
}
float CClientVehicle::GetLandingGearPosition ( void )
{
if ( m_bHasLandingGear )
{
if ( m_pVehicle )
{
return m_pVehicle->GetLandingGearPosition ();
}
}
return 0.0f;
}
void CClientVehicle::SetLandingGearPosition ( float fPosition )
{
if ( m_bHasLandingGear )
{
if ( m_pVehicle )
{
m_pVehicle->SetLandingGearPosition ( fPosition );
}
}
}
bool CClientVehicle::IsLandingGearDown ( void )
{
if ( m_bHasLandingGear )
{
if ( m_pVehicle )
{
return m_pVehicle->IsLandingGearDown ();
}
return m_bLandingGearDown;
}
return true;
}
void CClientVehicle::SetLandingGearDown ( bool bLandingGearDown )
{
if ( m_bHasLandingGear )
{
if ( m_pVehicle )
{
m_pVehicle->SetLandingGearDown ( bLandingGearDown );
}
m_bLandingGearDown = bLandingGearDown;
}
}
unsigned short CClientVehicle::GetAdjustablePropertyValue ( void )
{
unsigned short usPropertyValue;
if ( m_pVehicle )
{
usPropertyValue = m_pVehicle->GetAdjustablePropertyValue ();
// If it's a Hydra invert it with 5000 (as 0 is "forward"), so we can maintain a standard of 0 being "normal"
if ( m_usModel == VT_HYDRA ) usPropertyValue = 5000 - usPropertyValue;
}
else
{
usPropertyValue = m_usAdjustablePropertyValue;
}
// Return it
return usPropertyValue;
}
void CClientVehicle::SetAdjustablePropertyValue ( unsigned short usValue )
{
if ( m_usModel == VT_HYDRA ) usValue = 5000 - usValue;
_SetAdjustablePropertyValue ( usValue );
}
void CClientVehicle::_SetAdjustablePropertyValue ( unsigned short usValue )
{
// Set it
if ( m_pVehicle )
{
if ( m_bHasAdjustableProperty )
{
m_pVehicle->SetAdjustablePropertyValue ( usValue );
// Update our collision for this adjustable?
if ( HasMovingCollision () )
{
float fAngle = ( float ) usValue / 2499.0f;
m_pVehicle->UpdateMovingCollision ( fAngle );
}
}
}
m_usAdjustablePropertyValue = usValue;
}
bool CClientVehicle::HasMovingCollision ( void )
{
return ( m_usModel == VT_FORKLIFT || m_usModel == VT_FIRELA || m_usModel == VT_ANDROM ||
m_usModel == VT_DUMPER || m_usModel == VT_DOZER || m_usModel == VT_PACKER );
}
unsigned char CClientVehicle::GetDoorStatus ( unsigned char ucDoor )
{
if ( ucDoor < MAX_DOORS )
{
if ( m_pVehicle && HasDamageModel () )
{
return m_pVehicle->GetDamageManager ()->GetDoorStatus ( static_cast < eDoors > ( ucDoor ) );
}
return m_ucDoorStates [ucDoor];
}
return 0;
}
unsigned char CClientVehicle::GetWheelStatus ( unsigned char ucWheel )
{
if ( ucWheel < MAX_WHEELS )
{
// Return our custom state?
if ( m_ucWheelStates [ucWheel] == DT_WHEEL_INTACT_COLLISIONLESS ) return DT_WHEEL_INTACT_COLLISIONLESS;
if ( m_pVehicle )
{
if ( HasDamageModel () )
return m_pVehicle->GetDamageManager ()->GetWheelStatus ( static_cast < eWheels > ( ucWheel ) );
if ( m_eVehicleType == CLIENTVEHICLE_BIKE && ucWheel < 2 )
return m_pVehicle->GetBikeWheelStatus ( ucWheel );
}
return m_ucWheelStates [ucWheel];
}
return 0;
}
unsigned char CClientVehicle::GetPanelStatus ( unsigned char ucPanel )
{
if ( ucPanel < MAX_PANELS )
{
if ( m_pVehicle && HasDamageModel () )
{
return m_pVehicle->GetDamageManager ()->GetPanelStatus ( ucPanel );
}
return m_ucPanelStates [ ucPanel ];
}
return 0;
}
unsigned char CClientVehicle::GetLightStatus ( unsigned char ucLight )
{
if ( ucLight < MAX_LIGHTS )
{
if ( m_pVehicle && HasDamageModel () )
{
return m_pVehicle->GetDamageManager ()->GetLightStatus ( ucLight );
}
return m_ucLightStates [ ucLight ];
}
return 0;
}
void CClientVehicle::SetDoorStatus ( unsigned char ucDoor, unsigned char ucStatus )
{
if ( ucDoor < MAX_DOORS )
{
if ( m_pVehicle && HasDamageModel () )
{
m_pVehicle->GetDamageManager ()->SetDoorStatus ( static_cast < eDoors > ( ucDoor ), ucStatus );
}
m_ucDoorStates [ucDoor] = ucStatus;
}
}
void CClientVehicle::SetWheelStatus ( unsigned char ucWheel, unsigned char ucStatus, bool bSilent )
{
if ( ucWheel < MAX_WHEELS )
{
if ( m_pVehicle )
{
// Is our new status a burst tyre? and do we need to call BurstTyre?
if ( ucStatus == DT_WHEEL_BURST && !bSilent ) m_pVehicle->BurstTyre ( ucWheel );
// Are we using our custom state?
unsigned char ucGTAStatus = ucStatus;
if ( ucStatus == DT_WHEEL_INTACT_COLLISIONLESS ) ucGTAStatus = DT_WHEEL_MISSING;
// Do we have a damage model?
if ( HasDamageModel () )
{
m_pVehicle->GetDamageManager ()->SetWheelStatus ( ( eWheels ) ( ucWheel ), ucGTAStatus );
// Update the wheel's visibility
m_pVehicle->SetWheelVisibility ( ( eWheels ) ucWheel, ( ucStatus != DT_WHEEL_MISSING ) );
}
else if ( m_eVehicleType == CLIENTVEHICLE_BIKE && ucWheel < 2 )
m_pVehicle->SetBikeWheelStatus ( ucWheel, ucGTAStatus );
}
m_ucWheelStates [ucWheel] = ucStatus;
}
}
//
// Returns true if wheel should be invisible because of its state
//
bool CClientVehicle::GetWheelMissing ( unsigned char ucWheel, const SString& strWheelName )
{
// Use name if supplied
if ( strWheelName.BeginsWith( "wheel" ) )
{
if ( strWheelName == "wheel_lf_dummy" ) ucWheel = FRONT_LEFT_WHEEL;
else if ( strWheelName == "wheel_rf_dummy" ) ucWheel = FRONT_RIGHT_WHEEL;
else if ( strWheelName == "wheel_lb_dummy" ) ucWheel = REAR_LEFT_WHEEL;
else if ( strWheelName == "wheel_rb_dummy" ) ucWheel = REAR_RIGHT_WHEEL;
}
if ( ucWheel < MAX_WHEELS )
{
if ( HasDamageModel () )
{
// Check the wheel's invisibility
if ( m_ucWheelStates [ucWheel] == DT_WHEEL_MISSING )
return true;
}
}
return false;
}
void CClientVehicle::SetPanelStatus ( unsigned char ucPanel, unsigned char ucStatus )
{
if ( ucPanel < MAX_PANELS )
{
if ( m_pVehicle && HasDamageModel () )
{
m_pVehicle->GetDamageManager ()->SetPanelStatus ( static_cast < ePanels > ( ucPanel ), ucStatus );
}
m_ucPanelStates [ ucPanel ] = ucStatus;
}
}
void CClientVehicle::SetLightStatus ( unsigned char ucLight, unsigned char ucStatus )
{
if ( ucLight < MAX_LIGHTS )
{
if ( m_pVehicle && HasDamageModel () )
{
m_pVehicle->GetDamageManager ()->SetLightStatus ( static_cast < eLights > ( ucLight ), ucStatus );
}
m_ucLightStates [ ucLight ] = ucStatus;
}
}
float CClientVehicle::GetHeliRotorSpeed ( void )
{
if ( m_pVehicle && m_eVehicleType == CLIENTVEHICLE_HELI )
{
return m_pVehicle->GetHeliRotorSpeed ();
}
return m_fHeliRotorSpeed;
}
void CClientVehicle::SetHeliRotorSpeed ( float fSpeed )
{
if ( m_pVehicle && m_eVehicleType == CLIENTVEHICLE_HELI )
{
m_pVehicle->SetHeliRotorSpeed ( fSpeed );
}
m_fHeliRotorSpeed = fSpeed;
}
bool CClientVehicle::IsHeliSearchLightVisible ( void )
{
if ( m_pVehicle && m_eVehicleType == CLIENTVEHICLE_HELI )
{
return m_pVehicle->IsHeliSearchLightVisible ();
}
return m_bHeliSearchLightVisible;
}
void CClientVehicle::SetHeliSearchLightVisible ( bool bVisible )
{
if ( m_pVehicle && m_eVehicleType == CLIENTVEHICLE_HELI )
{
m_pVehicle->SetHeliSearchLightVisible ( bVisible );
}
m_bHeliSearchLightVisible = bVisible;
}
void CClientVehicle::SetCollisionEnabled ( bool bCollisionEnabled )
{
if ( m_pVehicle )
{
if ( m_bHasAdjustableProperty )
{
m_pVehicle->SetUsesCollision ( bCollisionEnabled );
}
}
m_bIsCollisionEnabled = bCollisionEnabled;
}
bool CClientVehicle::GetCanShootPetrolTank ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetCanShootPetrolTank ();
}
return m_bCanShootPetrolTank;
}
void CClientVehicle::SetCanShootPetrolTank ( bool bCanShoot )
{
if ( m_pVehicle )
{
m_pVehicle->SetCanShootPetrolTank ( bCanShoot );
}
m_bCanShootPetrolTank = bCanShoot;
}
bool CClientVehicle::GetCanBeTargettedByHeatSeekingMissiles ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetCanBeTargettedByHeatSeekingMissiles ();
}
return m_bCanBeTargettedByHeatSeekingMissiles;
}
void CClientVehicle::SetCanBeTargettedByHeatSeekingMissiles ( bool bEnabled )
{
if ( m_pVehicle )
{
m_pVehicle->SetCanBeTargettedByHeatSeekingMissiles ( bEnabled );
}
m_bCanBeTargettedByHeatSeekingMissiles = bEnabled;
}
void CClientVehicle::SetAlpha ( unsigned char ucAlpha )
{
if ( ucAlpha != m_ucAlpha )
{
if ( m_pVehicle )
{
m_pVehicle->SetAlpha ( ucAlpha );
}
m_ucAlpha = ucAlpha;
m_bAlphaChanged = true;
}
}
CClientPed* CClientVehicle::GetOccupant ( int iSeat ) const
{
// Return the driver if the seat is 0
if ( iSeat == 0 )
{
return (CClientPed*)(const CClientPed*)m_pDriver;
}
else if ( iSeat <= (sizeof(m_pPassengers)/sizeof(CClientPed*)) )
{
return m_pPassengers [iSeat - 1];
}
return NULL;
}
CClientPed* CClientVehicle::GetControllingPlayer ( void )
{
CClientPed* pControllingPlayer = m_pDriver;
if ( pControllingPlayer == NULL )
{
CClientVehicle* pCurrentVehicle = this;
CClientVehicle* pTowedByVehicle = m_pTowedByVehicle;
pControllingPlayer = pCurrentVehicle->GetOccupant ( 0 );
while ( pTowedByVehicle )
{
pCurrentVehicle = pTowedByVehicle;
pTowedByVehicle = pCurrentVehicle->GetTowedByVehicle ();
CClientPed* pCurrentDriver = pCurrentVehicle->GetOccupant ( 0 );
if ( pCurrentDriver )
pControllingPlayer = pCurrentDriver;
}
}
// Trains
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN )
{
CClientVehicle* pChainEngine = GetChainEngine ();
if ( pChainEngine )
pControllingPlayer = pChainEngine->GetOccupant ( 0 );
else
pControllingPlayer = NULL;
}
return pControllingPlayer;
}
void CClientVehicle::ClearForOccupants ( void )
{
// TODO: Also check passenger seats for players
// If there are people in the vehicle, remove them from the vehicle
CClientPed* pPed = GetOccupant ( 0 );
if ( pPed )
{
pPed->RemoveFromVehicle ();
}
}
void CClientVehicle::PlaceProperlyOnGround ( void )
{
if ( m_pVehicle )
{
// Place it properly at the ground depending on what kind of vehicle it is
if ( m_eVehicleType == CLIENTVEHICLE_BMX || m_eVehicleType == CLIENTVEHICLE_BIKE )
{
m_pVehicle->PlaceBikeOnRoadProperly ();
}
else if ( m_eVehicleType != CLIENTVEHICLE_BOAT )
{
m_pVehicle->PlaceAutomobileOnRoadProperly ();
}
}
}
void CClientVehicle::FuckCarCompletely ( bool bKeepWheels )
{
if ( m_pVehicle )
{
if ( HasDamageModel () )
{
m_pVehicle->GetDamageManager()->FuckCarCompletely ( bKeepWheels );
}
}
}
unsigned long CClientVehicle::GetMemoryValue ( unsigned long ulOffset )
{
if ( m_pVehicle )
{
return *m_pVehicle->GetMemoryValue ( ulOffset );
}
return 0;
}
unsigned long CClientVehicle::GetGameBaseAddress ( void )
{
if ( m_pVehicle )
{
return reinterpret_cast < unsigned long > ( m_pVehicle->GetMemoryValue ( 0 ) );
}
return 0;
}
void CClientVehicle::WorldIgnore ( bool bWorldIgnore )
{
if ( bWorldIgnore )
{
if ( m_pVehicle )
{
g_pGame->GetWorld ()->IgnoreEntity ( m_pVehicle );
}
}
else
{
g_pGame->GetWorld ()->IgnoreEntity ( NULL );
}
}
void CClientVehicle::FadeOut ( bool bFadeOut )
{
if ( m_pVehicle )
{
m_pVehicle->FadeOut ( bFadeOut );
}
}
bool CClientVehicle::IsFadingOut ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsFadingOut ();
}
return false;
}
void CClientVehicle::SetFrozen ( bool bFrozen )
{
if ( m_bScriptFrozen && bFrozen )
{
m_bIsFrozen = bFrozen;
CVector vecTemp;
if ( m_pVehicle )
{
m_pVehicle->GetMatrix ( &m_matFrozen );
m_pVehicle->SetMoveSpeed ( &vecTemp );
m_pVehicle->SetTurnSpeed ( &vecTemp );
}
else
{
m_matFrozen = m_Matrix;
m_vecMoveSpeed = vecTemp;
m_vecTurnSpeed = vecTemp;
}
}
else if ( !m_bScriptFrozen )
{
m_bIsFrozen = bFrozen;
if ( bFrozen )
{
CVector vecTemp;
if ( m_pVehicle )
{
m_pVehicle->GetMatrix ( &m_matFrozen );
m_pVehicle->SetMoveSpeed ( &vecTemp );
m_pVehicle->SetTurnSpeed ( &vecTemp );
}
else
{
m_matFrozen = m_Matrix;
m_vecMoveSpeed = vecTemp;
m_vecTurnSpeed = vecTemp;
}
}
}
}
bool CClientVehicle::IsFrozenWaitingForGroundToLoad ( void ) const
{
return m_bFrozenWaitingForGroundToLoad;
}
void CClientVehicle::SetFrozenWaitingForGroundToLoad ( bool bFrozen, bool bSuspendAsyncLoading )
{
if ( !g_pGame->IsASyncLoadingEnabled ( true ) )
return;
if ( m_bFrozenWaitingForGroundToLoad != bFrozen )
{
m_bFrozenWaitingForGroundToLoad = bFrozen;
if ( bFrozen )
{
if ( bSuspendAsyncLoading )
{
// Set auto unsuspend time in case changes prevent second call
g_pGame->SuspendASyncLoading ( true, 5000 );
}
m_fGroundCheckTolerance = 0.f;
m_fObjectsAroundTolerance = -1.f;
CVector vecTemp;
if ( m_pVehicle )
{
m_pVehicle->GetMatrix ( &m_matFrozen );
m_pVehicle->SetMoveSpeed ( &vecTemp );
m_pVehicle->SetTurnSpeed ( &vecTemp );
}
else
{
m_matFrozen = m_Matrix;
m_vecMoveSpeed = vecTemp;
m_vecTurnSpeed = vecTemp;
}
m_vecWaitingForGroundSavedMoveSpeed = vecTemp;
m_vecWaitingForGroundSavedTurnSpeed = vecTemp;
m_bAsyncLoadingDisabled = bSuspendAsyncLoading;
}
else
{
// use the member variable here and ignore Suspend Async loading
if ( m_bAsyncLoadingDisabled )
{
g_pGame->SuspendASyncLoading ( false );
}
m_vecMoveSpeed = m_vecWaitingForGroundSavedMoveSpeed;
m_vecTurnSpeed = m_vecWaitingForGroundSavedTurnSpeed;
if ( m_pVehicle )
{
m_pVehicle->SetMoveSpeed ( &m_vecMoveSpeed );
m_pVehicle->SetTurnSpeed ( &m_vecTurnSpeed );
}
m_bAsyncLoadingDisabled = false;
}
}
}
CClientVehicle* CClientVehicle::GetPreviousTrainCarriage ( void )
{
if ( IsDerailed () )
return NULL;
if ( m_pVehicle && m_pVehicle->GetPreviousTrainCarriage () )
{
return m_pVehicleManager->Get ( m_pVehicle->GetPreviousTrainCarriage (), false );
}
return m_pPreviousLink;
}
CClientVehicle* CClientVehicle::GetNextTrainCarriage ( void )
{
if ( IsDerailed () )
return NULL;
if ( m_pVehicle && m_pVehicle->GetNextTrainCarriage () )
{
return m_pVehicleManager->Get ( m_pVehicle->GetNextTrainCarriage (), false );
}
return m_pNextLink;
}
void CClientVehicle::SetPreviousTrainCarriage ( CClientVehicle* pPrevious )
{
// Tell the given vehicle we're the previous link and save the given vehicle as the next link
m_pPreviousLink = pPrevious;
if ( pPrevious )
pPrevious->m_pNextLink = this;
// If both vehicles are streamed in, do the link
if ( m_pVehicle )
{
if ( pPrevious && pPrevious->m_pVehicle )
m_pVehicle->SetPreviousTrainCarriage ( pPrevious->m_pVehicle );
else
m_pVehicle->SetPreviousTrainCarriage ( NULL );
}
}
void CClientVehicle::SetNextTrainCarriage ( CClientVehicle* pNext )
{
// Tell the given vehicle we're the previous link and save the given vehicle as the next link
m_pNextLink = pNext;
if ( pNext )
pNext->m_pPreviousLink = this;
// If both vehicles are streamed in, do the link
if ( m_pVehicle )
{
if ( pNext && pNext->m_pVehicle )
m_pVehicle->SetNextTrainCarriage ( pNext->m_pVehicle );
else
m_pVehicle->SetNextTrainCarriage ( NULL );
}
}
void CClientVehicle::SetIsChainEngine ( bool bChainEngine, bool bTemporary )
{
if ( !bTemporary )
m_bChainEngine = bChainEngine;
if ( m_pVehicle )
m_pVehicle->SetIsChainEngine ( bChainEngine );
// Remove chain engine status from other carriages
if ( bChainEngine == true )
{
CClientVehicle* pCarriage = m_pNextLink;
while ( pCarriage )
{
pCarriage->SetIsChainEngine ( false, bTemporary );
pCarriage = pCarriage->m_pNextLink;
}
pCarriage = m_pPreviousLink;
while ( pCarriage )
{
pCarriage->SetIsChainEngine ( false, bTemporary );
pCarriage = pCarriage->m_pPreviousLink;
}
}
}
bool CClientVehicle::IsTrainConnectedTo ( CClientVehicle * pTrailer )
{
CClientVehicle* pVehicle = this;
while ( pVehicle )
{
if ( pTrailer == pVehicle )
return true;
pVehicle = pVehicle->m_pNextLink;
}
pVehicle = this;
while ( pVehicle )
{
if ( pTrailer == pVehicle )
return true;
pVehicle = pVehicle->m_pPreviousLink;
}
return false;
}
CClientVehicle* CClientVehicle::GetChainEngine ()
{
CClientVehicle* pChainEngine = this;
while ( pChainEngine )
{
if ( pChainEngine->IsChainEngine () )
return pChainEngine;
pChainEngine = pChainEngine->m_pNextLink;
}
pChainEngine = this;
while ( pChainEngine )
{
if ( pChainEngine->IsChainEngine () )
return pChainEngine;
pChainEngine = pChainEngine->m_pPreviousLink;
}
return pChainEngine;
}
bool CClientVehicle::IsDerailed ( void )
{
if ( GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
if ( m_pVehicle )
{
return m_pVehicle->IsDerailed ();
}
return m_bIsDerailed;
}
else
return false;
}
void CClientVehicle::SetDerailed ( bool bDerailed )
{
if ( GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
if ( m_pVehicle && bDerailed != IsDerailed () )
{
m_pVehicle->SetDerailed ( bDerailed );
}
m_bIsDerailed = bDerailed;
}
}
bool CClientVehicle::IsDerailable ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsDerailable ();
}
return m_bIsDerailable;
}
void CClientVehicle::SetDerailable ( bool bDerailable )
{
if ( m_pVehicle )
{
m_pVehicle->SetDerailable ( bDerailable );
}
m_bIsDerailable = bDerailable;
}
bool CClientVehicle::GetTrainDirection ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetTrainDirection ();
}
return m_bTrainDirection;
}
void CClientVehicle::SetTrainDirection ( bool bDirection )
{
if ( m_pVehicle && GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
m_pVehicle->SetTrainDirection ( bDirection );
}
m_bTrainDirection = bDirection;
}
float CClientVehicle::GetTrainSpeed ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetTrainSpeed ();
}
return m_fTrainSpeed;
}
void CClientVehicle::SetTrainSpeed ( float fSpeed )
{
if ( m_pVehicle && GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
m_pVehicle->SetTrainSpeed ( fSpeed );
}
m_fTrainSpeed = fSpeed;
}
float CClientVehicle::GetTrainPosition ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetTrainPosition ();
}
return m_fTrainPosition;
}
void CClientVehicle::SetTrainPosition ( float fTrainPosition, bool bRecalcOnRailDistance )
{
if ( m_pVehicle && GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
m_pVehicle->SetTrainPosition ( fTrainPosition, bRecalcOnRailDistance );
}
m_fTrainPosition = fTrainPosition;
}
uchar CClientVehicle::GetTrainTrack ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetRailTrack ();
}
return m_ucTrackID;
}
void CClientVehicle::SetTrainTrack ( uchar ucTrack )
{
if ( m_pVehicle && GetVehicleType() == CLIENTVEHICLE_TRAIN )
{
m_pVehicle->SetRailTrack ( ucTrack );
}
m_ucTrackID = ucTrack;
}
void CClientVehicle::SetOverrideLights ( unsigned char ucOverrideLights )
{
if ( m_pVehicle )
{
m_pVehicle->SetOverrideLights ( static_cast < unsigned int > ( ucOverrideLights ) );
}
m_ucOverrideLights = ucOverrideLights;
}
bool CClientVehicle::IsNitroInstalled ( void )
{
return this->GetUpgrades ()->GetSlotState ( 8 ) != 0;
}
void CClientVehicle::StreamedInPulse ( void )
{
// Make sure the vehicle doesn't go too far down
if ( m_pVehicle )
{
if ( m_bBlowNextFrame )
{
Blow ( false );
m_bBlowNextFrame = false;
}
// Handle door ratio auto reallowment
if ( !m_AutoReallowDoorRatioMap.empty() )
{
for ( std::map < eDoors, CTickCount >::iterator iter = m_AutoReallowDoorRatioMap.begin() ; iter != m_AutoReallowDoorRatioMap.end() ; )
{
if ( ( CTickCount::Now() - iter->second ).ToInt() > 4000 )
{
uchar ucDoor = iter->first;
m_AutoReallowDoorRatioMap.erase( iter++ );
if ( !m_bAllowDoorRatioSetting[ ucDoor ] )
AllowDoorRatioSetting( ucDoor, true );
}
else
++iter;
}
}
// Are we an unmanned, invisible, blown-up plane?
if ( !GetOccupant () && m_eVehicleType == CLIENTVEHICLE_PLANE && m_bBlown && !m_pVehicle->IsVisible () )
{
// Disable our collisions
m_pVehicle->SetUsesCollision ( false );
}
else
{
// Vehicles have a way of getting their cols back, so we have to force this each frame (not much overhead anyway)
m_pVehicle->SetUsesCollision ( m_bIsCollisionEnabled );
}
// Handle waiting for the ground to load
if ( IsFrozenWaitingForGroundToLoad () )
HandleWaitingForGroundToLoad ();
// If we are frozen, make sure we freeze our matrix and keep move/turn speed at 0,0,0
if ( m_bIsFrozen )
{
CVector vecTemp;
m_pVehicle->SetMatrix ( &m_matFrozen );
m_pVehicle->SetMoveSpeed ( &vecTemp );
m_pVehicle->SetTurnSpeed ( &vecTemp );
}
else
{
CVector vecPos = *m_pVehicle->GetPosition();
// Cols been loaded for where the vehicle is? Only check this if it has no drivers.
if ( m_pDriver ||
( g_pGame->GetWorld ()->HasCollisionBeenLoaded ( &vecPos ) /*&&
m_pObjectManager->ObjectsAroundPointLoaded ( m_matFrozen.vPos, 200.0f, m_usDimension )*/ ) )
{
// Remember the matrix
m_pVehicle->GetMatrix ( &m_matFrozen );
}
else
{
// Force the position to the last remembered matrix (..and make sure gravity doesn't pull it down)
if ( GetVehicleType() != CLIENTVEHICLE_TRAIN || IsDerailed() )
{
m_pVehicle->SetMatrix ( &m_matFrozen );
CVector vec(0.0f, 0.0f, 0.0f);
m_pVehicle->SetMoveSpeed ( &vec );
}
// Added by ChrML 27. Nov: Shouldn't cause any problems
m_pVehicle->SetUsesCollision ( false );
}
}
// Calculate the velocity
CMatrix MatrixCurrent;
m_pVehicle->GetMatrix ( &MatrixCurrent );
m_vecMoveSpeedMeters = ( MatrixCurrent.vPos - m_MatrixLast.vPos ) * g_pGame->GetFPS ();
// Store the current matrix
m_MatrixLast = MatrixCurrent;
// We dont interpolate attached trailers
if ( m_pTowedByVehicle )
{
RemoveTargetPosition ();
RemoveTargetRotation ();
}
// Remove link in CClientVehicle structure if SA does it
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN )
{
if ( !GetNextTrainCarriage () )
m_pNextLink = NULL;
if ( !GetPreviousTrainCarriage () )
m_pPreviousLink = NULL;
}
CClientPed* pControllingPed = GetControllingPlayer ();
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN && ( !pControllingPed || pControllingPed->GetType () != CCLIENTPLAYER ) )
{
// Apply chain engine's speed on its carriages (if chain engine isn't streamed in)
CClientVehicle* pChainEngine = GetChainEngine ();
if ( pChainEngine && pChainEngine != this && !pChainEngine->IsStreamedIn () )
{
SetTrainSpeed ( pChainEngine->GetTrainSpeed () );
}
// Check if we need to update the train position (because of streaming)
CVector vecPosition;
float fCarriageDistance = 20.0f; // approximately || Todo: Find proper distance
if ( GetTrainDirection () )
fCarriageDistance = -fCarriageDistance;
// Calculate and update new stream world position
CClientVehicle* pCarriage = this;
while ( pCarriage->m_pNextLink && !pCarriage->m_pNextLink->IsStreamedIn () )
{
float fNewTrainPosition = pCarriage->GetTrainPosition () + fCarriageDistance;
pCarriage->m_pNextLink->SetTrainPosition ( fNewTrainPosition );
g_pGame->GetWorld ()->FindWorldPositionForRailTrackPosition ( fNewTrainPosition, GetTrainTrack (), &vecPosition );
pCarriage->m_pNextLink->UpdatePedPositions ( vecPosition );
pCarriage = pCarriage->m_pNextLink;
}
pCarriage = this;
while ( pCarriage->m_pPreviousLink && !pCarriage->m_pPreviousLink->IsStreamedIn () )
{
float fNewTrainPosition = pCarriage->GetTrainPosition () - fCarriageDistance;
pCarriage->m_pPreviousLink->SetTrainPosition ( fNewTrainPosition );
g_pGame->GetWorld ()->FindWorldPositionForRailTrackPosition ( fNewTrainPosition, GetTrainTrack (), &vecPosition );
pCarriage->m_pPreviousLink->UpdatePedPositions ( vecPosition );
pCarriage = pCarriage->m_pPreviousLink;
}
}
/*
// Are we blown?
if ( m_bBlown )
{
// Has our engine status been reset to on_fire somewhere?
CDamageManager* pDamageManager = m_pVehicle->GetDamageManager ();
if ( pDamageManager->GetEngineStatus () == DT_ENGINE_ON_FIRE )
{
// Change it back to fucked
pDamageManager->SetEngineStatus ( DT_ENGINE_ENGINE_PIPES_BURST );
}
}
*/
// Limit burnout turn speed to ensure smoothness
if ( m_pDriver )
{
CControllerState cs;
m_pDriver->GetControllerState ( cs );
bool bAcclerate = cs.ButtonCross > 128;
bool bBrake = cs.ButtonSquare > 128;
// Is doing burnout ?
if ( bAcclerate && bBrake )
{
CVector vecMoveSpeed;
m_pVehicle->GetMoveSpeed ( &vecMoveSpeed );
if ( fabsf ( vecMoveSpeed.fX ) < 0.06f * 2 && fabsf ( vecMoveSpeed.fY ) < 0.06f * 2 && fabsf ( vecMoveSpeed.fZ ) < 0.01f * 2 )
{
CVector vecTurnSpeed;
m_pVehicle->GetTurnSpeed ( &vecTurnSpeed );
if ( fabsf ( vecTurnSpeed.fX ) < 0.006f * 2 && fabsf ( vecTurnSpeed.fY ) < 0.006f * 2 && fabsf ( vecTurnSpeed.fZ ) < 0.04f * 2 )
{
// Apply turn speed limit
float fLength = vecTurnSpeed.Normalize ();
fLength = Min ( fLength, 0.02f );
vecTurnSpeed *= fLength;
m_pVehicle->SetTurnSpeed ( &vecTurnSpeed );
}
}
}
}
Interpolate ();
ProcessDoorInterpolation ();
// Grab our current position
CVector vecPosition = *m_pVehicle->GetPosition ();
if ( m_pAttachedToEntity )
{
m_pAttachedToEntity->GetPosition ( vecPosition );
vecPosition += m_vecAttachedPosition;
}
// Have we moved?
if ( vecPosition != m_Matrix.vPos )
{
// If we're setting the position, check whether we're under-water.
// If so, we need to set the Underwater flag so the render draw order is changed.
m_pVehicle->SetUnderwater ( IsBelowWater () );
// Store our new position
m_Matrix.vPos = vecPosition;
m_matFrozen.vPos = vecPosition;
// Update our streaming position
UpdateStreamPosition ( vecPosition );
}
// Check installed nitro
if ( IsNitroInstalled () )
{
// Nitro state changed?
bool bActivated = ( m_pVehicle->GetNitroLevel () < 0 );
if ( m_bNitroActivated != bActivated )
{
CLuaArguments Arguments;
Arguments.PushBoolean ( bActivated );
this->CallEvent ( "onClientVehicleNitroStateChange", Arguments, false );
}
m_bNitroActivated = bActivated;
}
// Update doors
if ( CClientVehicleManager::HasDoors ( GetModel() ) )
{
for ( unsigned char i = 0; i < 6; ++i )
{
CDoor* pDoor = m_pVehicle->GetDoor ( i );
if ( pDoor )
m_fDoorOpenRatio [ i ] = pDoor->GetAngleOpenRatio ();
}
}
// Update landing gear state if this is a plane and we have no driver / pilot
if ( this->HasLandingGear() && m_pDriver == NULL )
{
m_pVehicle->UpdateLandingGearPosition();
}
}
}
void CClientVehicle::StreamIn ( bool bInstantly )
{
// We need to create now?
if ( bInstantly )
{
// Request its model blocking
if ( m_pModelRequester->RequestBlocking ( m_usModel, "CClientVehicle::StreamIn - bInstantly" ) )
{
// Create us
Create ();
}
else NotifyUnableToCreate ();
}
else
{
// Request its model.
if ( m_pModelRequester->Request ( m_usModel, this ) )
{
// If it got loaded immediately, create the vehicle now.
// Otherwise we create it when the model loaded callback calls us
Create ();
}
else NotifyUnableToCreate ();
}
}
void CClientVehicle::StreamOut ( void )
{
// Destroy the vehicle.
Destroy ();
// Make sure we don't have any model requests
// pending in the model request manager. If we
// had and don't do this it could create us when
// we're not streamed in.
m_pModelRequester->Cancel ( this, true );
}
bool CClientVehicle::DoCheckHasLandingGear ( void )
{
return ( m_usModel == VT_ANDROM ||
m_usModel == VT_AT400 ||
m_usModel == VT_NEVADA ||
m_usModel == VT_RUSTLER ||
m_usModel == VT_SHAMAL ||
m_usModel == VT_HYDRA ||
m_usModel == VT_STUNT );
}
void CClientVehicle::Create ( void )
{
// If the vehicle doesn't exist
if ( !m_pVehicle )
{
#ifdef MTA_DEBUG
g_pCore->GetConsole ()->Printf ( "CClientVehicle::Create %d", GetModel() );
#endif
// Check again that the limit isn't reached. We are required to do so because
// we load async. The streamer isn't always aware of our limits.
if ( CClientVehicleManager::IsVehicleLimitReached () )
{
// Tell the streamer we could not create it
NotifyUnableToCreate ();
return;
}
// Add a reference to the vehicle model we're creating.
m_pModelInfo->ModelAddRef ( BLOCKING, "CClientVehicle::Create" );
// Might want to make this settable by users? Could just leave it like this, don't mind.
// Doesn't appear to work with trucks - only cars - stored string is up to 8 chars, will be reset after
// each vehicle spawned of this model type (i.e. after AddVehicle below)
if ( !m_strRegPlate.empty () )
m_pModelInfo->SetCustomCarPlateText ( m_strRegPlate.c_str () );
// Create the vehicle
if ( CClientVehicleManager::IsTrainModel ( m_usModel ) )
{
DWORD dwModels [1];
dwModels [0] = m_usModel;
m_pVehicle = g_pGame->GetPools ()->AddTrain ( &m_Matrix.vPos, dwModels, 1, m_bTrainDirection, m_ucTrackID );
}
else
{
m_pVehicle = g_pGame->GetPools ()->AddVehicle ( static_cast < eVehicleTypes > ( m_usModel ), m_ucVariation, m_ucVariation2 );
}
// Failed. Remove our reference to the vehicle model and return
if ( !m_pVehicle )
{
// Tell the streamer we could not create it
NotifyUnableToCreate ();
m_pModelInfo->RemoveRef ();
return;
}
// Put our pointer in its custom data
m_pVehicle->SetStoredPointer ( this );
// Add XRef
g_pClientGame->GetGameEntityXRefManager ()->AddEntityXRef ( this, m_pVehicle );
/*if ( DoesNeedToWaitForGroundToLoad() )
{
// waiting for ground to load
SetFrozenWaitingForGroundToLoad ( true, false );
}*/
// Jump straight to the target position if we have one
if ( HasTargetPosition () )
{
GetTargetPosition ( m_Matrix.vPos );
}
// Jump straight to the target rotation if we have one
if ( HasTargetRotation () )
{
CVector vecTemp = m_interp.rot.vecTarget;
ConvertDegreesToRadians ( vecTemp );
g_pMultiplayer->ConvertEulerAnglesToMatrix ( m_Matrix, ( 2 * PI ) - vecTemp.fX, ( 2 * PI ) - vecTemp.fY, ( 2 * PI ) - vecTemp.fZ );
}
// Got any settings to restore?
m_pVehicle->SetMatrix ( &m_Matrix );
m_matFrozen = m_Matrix;
SetMoveSpeed ( m_vecMoveSpeed );
SetTurnSpeed ( m_vecTurnSpeed );
m_pVehicle->SetVisible ( m_bVisible );
m_pVehicle->SetUsesCollision ( m_bIsCollisionEnabled );
m_pVehicle->SetEngineBroken ( m_bEngineBroken );
if ( m_tSirenBeaconInfo.m_bOverrideSirens )
{
GiveVehicleSirens( m_tSirenBeaconInfo.m_ucSirenType, m_tSirenBeaconInfo.m_ucSirenCount );
for ( unsigned char i = 0; i < m_tSirenBeaconInfo.m_ucSirenCount; i++ )
{
m_pVehicle->SetVehicleSirenPosition( i, m_tSirenBeaconInfo.m_tSirenInfo[i].m_vecSirenPositions );
m_pVehicle->SetVehicleSirenMinimumAlpha( i, m_tSirenBeaconInfo.m_tSirenInfo[i].m_dwMinSirenAlpha );
m_pVehicle->SetVehicleSirenColour( i, m_tSirenBeaconInfo.m_tSirenInfo[i].m_RGBBeaconColour );
}
SetVehicleFlags ( m_tSirenBeaconInfo.m_b360Flag, m_tSirenBeaconInfo.m_bUseRandomiser, m_tSirenBeaconInfo.m_bDoLOSCheck, m_tSirenBeaconInfo.m_bSirenSilent );
}
m_pVehicle->SetSirenOrAlarmActive ( m_bSireneOrAlarmActive );
SetLandingGearDown ( m_bLandingGearDown );
_SetAdjustablePropertyValue ( m_usAdjustablePropertyValue );
m_pVehicle->SetSwingingDoorsAllowed ( m_bSwingingDoorsAllowed );
m_pVehicle->LockDoors ( m_bDoorsLocked );
m_pVehicle->SetDoorsUndamageable ( m_bDoorsUndamageable );
m_pVehicle->SetCanShootPetrolTank ( m_bCanShootPetrolTank );
m_pVehicle->SetTaxiLightOn ( m_bTaxiLightOn );
m_pVehicle->SetCanBeTargettedByHeatSeekingMissiles ( m_bCanBeTargettedByHeatSeekingMissiles );
CalcAndUpdateTyresCanBurstFlag ();
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN )
{
m_pVehicle->SetDerailed ( m_bIsDerailed );
m_pVehicle->SetDerailable ( m_bIsDerailable );
m_pVehicle->SetTrainDirection ( m_bTrainDirection );
m_pVehicle->SetTrainSpeed ( m_fTrainSpeed );
if ( m_ucTrackID >= 0 )
m_pVehicle->SetRailTrack ( m_ucTrackID );
if ( m_fTrainPosition >= 0 && !m_bIsDerailed )
m_pVehicle->SetTrainPosition ( m_fTrainPosition, true );
// Set matrix once more (to ensure that the rotation has been set properly)
if ( m_bIsDerailed )
m_pVehicle->SetMatrix ( &m_Matrix );
if ( m_bChainEngine )
SetIsChainEngine ( true );
// Train carriages
if ( m_pNextLink && !m_bIsDerailed && !m_pNextLink->IsDerailed () )
{
m_pVehicle->SetNextTrainCarriage ( m_pNextLink->m_pVehicle );
m_pNextLink->SetTrainTrack ( GetTrainTrack () );
if ( m_pNextLink->GetGameVehicle () )
{
SetTrainPosition ( m_pNextLink->GetTrainPosition () - m_pVehicle->GetDistanceToCarriage ( m_pNextLink->GetGameVehicle () ), false );
m_pVehicle->AttachTrainCarriage ( m_pNextLink->GetGameVehicle () );
}
}
if ( m_pPreviousLink && !m_bIsDerailed && !m_pPreviousLink->IsDerailed () )
{
m_pVehicle->SetPreviousTrainCarriage ( m_pPreviousLink->m_pVehicle );
this->SetTrainTrack ( m_pPreviousLink->GetTrainTrack () );
if ( m_pPreviousLink->GetGameVehicle () )
m_pPreviousLink->GetGameVehicle ()->AttachTrainCarriage ( m_pVehicle );
}
}
m_pVehicle->SetOverrideLights ( m_ucOverrideLights );
m_pVehicle->SetRemap ( static_cast < unsigned int > ( m_ucPaintjob ) );
m_pVehicle->SetBodyDirtLevel ( m_fDirtLevel );
m_pVehicle->SetEngineOn ( m_bEngineOn );
m_pVehicle->SetAreaCode ( m_ucInterior );
m_pVehicle->SetSmokeTrailEnabled ( m_bSmokeTrail );
m_pVehicle->SetGravity ( &m_vecGravity );
m_pVehicle->SetHeadLightColor ( m_HeadLightColor );
if ( IsNitroInstalled() )
{
m_pVehicle->SetNitroCount ( m_cNitroCount );
m_pVehicle->SetNitroLevel ( m_fNitroLevel );
}
if ( m_eVehicleType == CLIENTVEHICLE_HELI )
{
m_pVehicle->SetHeliRotorSpeed ( m_fHeliRotorSpeed );
m_pVehicle->SetHeliSearchLightVisible ( m_bHeliSearchLightVisible );
}
m_pVehicle->SetUnderwater ( IsBelowWater () );
// HACK: temp fix until windows are fixed using setAlpha
if ( m_bAlphaChanged )
m_pVehicle->SetAlpha ( m_ucAlpha );
m_pVehicle->SetHealth ( m_fHealth );
if ( m_bBlown || m_fHealth == 0.0f ) m_bBlowNextFrame = true;
CalcAndUpdateCanBeDamagedFlag ();
if ( IsLocalEntity() && !m_bColorSaved )
{
// On first create of local vehicle, save color chosen by GTA
GetColor();
m_bColorSaved = true;
}
// Restore the color
m_pVehicle->SetColor ( m_Color.GetRGBColor ( 0 ), m_Color.GetRGBColor ( 1 ), m_Color.GetRGBColor ( 2 ), m_Color.GetRGBColor ( 3 ), 0 );
// Restore turret rotation
if ( m_eVehicleType == CLIENTVEHICLE_CAR ||
m_eVehicleType == CLIENTVEHICLE_PLANE ||
m_eVehicleType == CLIENTVEHICLE_QUADBIKE )
{
m_pVehicle->SetTurretRotation ( m_fTurretHorizontal, m_fTurretVertical );
}
// Does this car have a damage model?
if ( HasDamageModel () )
{
// Set the damage model doors
CDamageManager* pDamageManager = m_pVehicle->GetDamageManager ();
for ( int i = 0; i < MAX_DOORS; i++ )
pDamageManager->SetDoorStatus ( static_cast < eDoors > ( i ), m_ucDoorStates [i] );
for ( int i = 0; i < MAX_PANELS; i++ )
pDamageManager->SetPanelStatus ( static_cast < ePanels > ( i ), m_ucPanelStates [i] );
for ( int i = 0; i < MAX_LIGHTS; i++ )
pDamageManager->SetLightStatus ( static_cast < eLights > ( i ), m_ucLightStates [i] );
}
for ( int i = 0; i < MAX_WHEELS; i++ )
SetWheelStatus ( i, m_ucWheelStates [i], true );
// Eventually warp driver back in
if ( m_pDriver ) m_pDriver->WarpIntoVehicle ( this, 0 );
// Warp the passengers back in
for ( unsigned int i = 0; i < 8; i++ )
{
if ( m_pPassengers [i] )
{
m_pPassengers [i]->WarpIntoVehicle ( this, i + 1 );
if ( m_pPassengers [i] )
m_pPassengers [i]->StreamIn ( true );
}
}
// Reattach a towed vehicle?
if ( m_pTowedVehicle )
{
// Make sure that the trailer is streamed in
if ( !m_pTowedVehicle->GetGameVehicle () )
{
m_pTowedVehicle->StreamIn ( true );
}
// Attach him
if ( m_pTowedVehicle->GetGameVehicle () )
{
InternalSetTowLink ( m_pTowedVehicle );
}
}
// Reattach if we're being towed
if ( m_pTowedByVehicle && m_pTowedByVehicle->GetGameVehicle () )
{
m_pTowedByVehicle->InternalSetTowLink ( this );
}
// Reattach to an entity + any entities attached to this
ReattachEntities ();
// Give it a tap so it doesn't stick in the air if movespeed is standing still
if ( m_vecMoveSpeed.fX < 0.01f && m_vecMoveSpeed.fX > -0.01f &&
m_vecMoveSpeed.fY < 0.01f && m_vecMoveSpeed.fY > -0.01f &&
m_vecMoveSpeed.fZ < 0.01f && m_vecMoveSpeed.fZ > -0.01f )
{
m_vecMoveSpeed = CVector ( 0.0f, 0.0f, 0.01f );
m_pVehicle->SetMoveSpeed ( &m_vecMoveSpeed );
}
// Validate
m_pManager->RestoreEntity ( this );
// Set the frozen matrix to our position
m_matFrozen = m_Matrix;
// Reset the interpolation
ResetInterpolation ();
ResetDoorInterpolation ();
for ( unsigned char i = 0; i < 6; ++i )
SetDoorOpenRatio ( i, m_fDoorOpenRatio [ i ], 0, true );
// Re-apply handling entry
if ( m_pHandlingEntry )
{
m_pVehicle->SetHandlingData ( m_pHandlingEntry );
if ( m_bHasCustomHandling )
ApplyHandling ();
}
// Re-add all the upgrades - Has to be applied after handling *shrugs*
if ( m_pUpgrades )
m_pUpgrades->ReAddAll ();
if ( m_ComponentData.empty ( ) )
{
// grab our map of components
std::map < SString, SVehicleFrame > componentMap = m_pVehicle->GetComponentMap ( );
// get our beginning
std::map < SString, SVehicleFrame >::iterator iter = componentMap.begin ( );
// loop through all the components.... we don't care about the RwFrame we just want the names.
for ( ; iter != componentMap.end () ; iter++ )
{
SVehicleComponentData vehicleComponentData;
// Grab our start position
GetComponentPosition ( (*iter).first, vehicleComponentData.m_vecComponentPosition );
GetComponentRotation ( (*iter).first, vehicleComponentData.m_vecComponentRotation );
// copy it into our original positions
vehicleComponentData.m_vecOriginalComponentPosition = vehicleComponentData.m_vecComponentPosition;
vehicleComponentData.m_vecOriginalComponentRotation = vehicleComponentData.m_vecComponentRotation;
// insert it into our component data list
m_ComponentData.insert ( std::pair < SString, SVehicleComponentData > ( (*iter).first, vehicleComponentData ) );
// # prefix means hidden by default.
if ( (*iter).first[0] == '#' )
{
SetComponentVisible ( (*iter).first, false );
}
}
}
// Grab our component data
std::map < SString, SVehicleComponentData > ::iterator iter = m_ComponentData.begin ();
// Loop through our component data
for ( ; iter != m_ComponentData.end () ; iter++ )
{
// store our string in a temporary variable
SString strTemp = (*iter).first;
// get our poisition and rotation and store it into
//GetComponentPosition ( strTemp, (*iter).second.m_vecComponentPosition );
//GetComponentRotation ( strTemp, (*iter).second.m_vecComponentRotation );
// is our position changed?
if ( (*iter).second.m_bPositionChanged )
{
// Make sure it's different
if ( (*iter).second.m_vecOriginalComponentPosition != (*iter).second.m_vecComponentPosition )
{
// apply our new position
SetComponentPosition( strTemp, (*iter).second.m_vecComponentPosition );
}
}
// is our position changed?
if ( (*iter).second.m_bRotationChanged )
{
// Make sure it's different
if ( (*iter).second.m_vecOriginalComponentRotation != (*iter).second.m_vecComponentRotation )
{
// apple our new position
SetComponentRotation( strTemp, (*iter).second.m_vecComponentRotation );
}
}
// set our visibility
SetComponentVisible ( strTemp, (*iter).second.m_bVisible );
}
// store our spawn position in case we fall through the map
m_matCreate = m_Matrix;
// Tell the streamer we've created this object
NotifyCreate ();
}
}
void CClientVehicle::Destroy ( void )
{
// If the vehicle exists
if ( m_pVehicle )
{
#ifdef MTA_DEBUG
g_pCore->GetConsole ()->Printf ( "CClientVehicle::Destroy %d", GetModel() );
#endif
// Invalidate
m_pManager->InvalidateEntity ( this );
// Store anything we allow GTA to change
m_pVehicle->GetMatrix ( &m_Matrix );
m_pVehicle->GetMoveSpeed ( &m_vecMoveSpeed );
m_pVehicle->GetTurnSpeed ( &m_vecTurnSpeed );
m_fHealth = GetHealth ();
m_bSireneOrAlarmActive = m_pVehicle->IsSirenOrAlarmActive () ? true:false;
m_bLandingGearDown = IsLandingGearDown ();
m_usAdjustablePropertyValue = m_pVehicle->GetAdjustablePropertyValue ();
m_bEngineOn = m_pVehicle->IsEngineOn ();
m_bIsOnGround = IsOnGround ();
m_fHeliRotorSpeed = GetHeliRotorSpeed ();
m_bHeliSearchLightVisible = IsHeliSearchLightVisible ();
m_pHandlingEntry = m_pVehicle->GetHandlingData();
if ( m_eVehicleType == CLIENTVEHICLE_CAR ||
m_eVehicleType == CLIENTVEHICLE_PLANE ||
m_eVehicleType == CLIENTVEHICLE_QUADBIKE )
{
m_pVehicle->GetTurretRotation ( &m_fTurretHorizontal, &m_fTurretVertical );
}
// This vehicle has a damage model?
if ( HasDamageModel () )
{
// Grab the damage model
CDamageManager* pDamageManager = m_pVehicle->GetDamageManager ();
for ( int i = 0; i < MAX_DOORS; i++ )
m_ucDoorStates [i] = pDamageManager->GetDoorStatus ( static_cast < eDoors > ( i ) );
for ( int i = 0; i < MAX_PANELS; i++ )
m_ucPanelStates [i] = pDamageManager->GetPanelStatus ( static_cast < ePanels > ( i ) );
for ( int i = 0; i < MAX_LIGHTS; i++ )
m_ucLightStates [i] = pDamageManager->GetLightStatus ( static_cast < eLights > ( i ) );
}
for ( int i = 0; i < MAX_WHEELS; i++ )
m_ucWheelStates [i] = GetWheelStatus ( i );
// Remove the driver from the vehicle
CClientPed* pPed = GetOccupant ( 0 );
if ( pPed )
{
// Only remove him physically. Don't let the ped update us
pPed->InternalRemoveFromVehicle ( m_pVehicle );
}
// Remove all the passengers physically
for ( unsigned int i = 0; i < 8; i++ )
{
if ( m_pPassengers [i] )
{
m_pPassengers [i]->InternalRemoveFromVehicle ( m_pVehicle );
}
}
// Do we have any occupying players? (that could be working on entering this vehicle)
if ( m_pOccupyingDriver && m_pOccupyingDriver->m_pOccupyingVehicle == this )
{
if ( m_pOccupyingDriver->IsGettingIntoVehicle () || m_pOccupyingDriver->IsGettingOutOfVehicle () )
{
m_pOccupyingDriver->RemoveFromVehicle ();
}
}
for ( unsigned int i = 0; i < 8; i++ )
{
if ( m_pOccupyingPassengers [i] && m_pOccupyingPassengers [i]->m_pOccupyingVehicle == this )
{
if ( m_pOccupyingPassengers [i]->IsGettingIntoVehicle () || m_pOccupyingPassengers [i]->IsGettingOutOfVehicle () )
{
m_pOccupyingPassengers [i]->RemoveFromVehicle ();
}
}
}
if ( GetTowedVehicle () )
{
// Force the trailer to stream out
GetTowedVehicle ()->StreamOut ();
}
if ( GetVehicleType () == CLIENTVEHICLE_TRAIN )
{
m_bIsDerailed = IsDerailed ();
m_ucTrackID = m_pVehicle->GetRailTrack ();
m_fTrainPosition = m_pVehicle->GetTrainPosition ();
m_fTrainSpeed = m_pVehicle->GetTrainSpeed ();
if ( m_pVehicle->IsChainEngine () )
{
// Devolve chain engine state to next link (temporarily)
if ( m_pNextLink && m_pNextLink->GetGameVehicle () )
m_pNextLink->SetIsChainEngine ( true, true );
else if ( m_pPreviousLink && m_pPreviousLink->GetGameVehicle () )
m_pPreviousLink->SetIsChainEngine ( true, true );
}
// Unlink from chain
if ( m_pNextLink && m_pNextLink->GetGameVehicle () )
m_pNextLink->GetGameVehicle ()->SetPreviousTrainCarriage ( NULL );
if ( m_pPreviousLink && m_pPreviousLink->GetGameVehicle () )
m_pPreviousLink->GetGameVehicle ()->SetNextTrainCarriage ( NULL );
}
// Remove XRef
g_pClientGame->GetGameEntityXRefManager ()->RemoveEntityXRef ( this, m_pVehicle );
// Destroy the vehicle
g_pGame->GetPools ()->RemoveVehicle ( m_pVehicle );
m_pVehicle = NULL;
// Remove reference to its model
m_pModelInfo->RemoveRef ();
// reset our fall through map count
m_ucFellThroughMapCount = 1;
NotifyDestroy ();
}
}
void CClientVehicle::ReCreate ( void )
{
// Recreate the vehicle if it exists
if ( m_pVehicle )
{
Destroy ();
Create ();
}
}
void CClientVehicle::ModelRequestCallback ( CModelInfo* pModelInfo )
{
// Create the vehicle. The model is now loaded.
Create ();
}
void CClientVehicle::NotifyCreate ( void )
{
m_pVehicleManager->OnCreation ( this );
CClientStreamElement::NotifyCreate ();
}
void CClientVehicle::NotifyDestroy ( void )
{
m_pVehicleManager->OnDestruction ( this );
}
CClientVehicle* CClientVehicle::GetTowedVehicle ( void )
{
if ( m_pVehicle )
{
CVehicle* pGameVehicle = m_pVehicle->GetTowedVehicle ();
if ( pGameVehicle ) return m_pVehicleManager->Get ( pGameVehicle, false );
}
return m_pTowedVehicle;
}
CClientVehicle* CClientVehicle::GetRealTowedVehicle ( void )
{
if ( m_pVehicle )
{
CVehicle* pGameVehicle = m_pVehicle->GetTowedVehicle ();
if ( pGameVehicle ) return m_pVehicleManager->Get ( pGameVehicle, false );
// This is the only difference from ::GetTowedVehicle
return NULL;
}
return m_pTowedVehicle;
}
bool CClientVehicle::SetTowedVehicle ( CClientVehicle* pVehicle, const CVector* vecRotationDegrees )
{
// Train carriages
if ( this->GetVehicleType () == CLIENTVEHICLE_TRAIN && pVehicle == NULL )
{
if ( m_pVehicle && m_pNextLink && m_pNextLink->GetGameVehicle () )
m_pVehicle->DetachTrainCarriage ( m_pNextLink->GetGameVehicle () );
// Deattach our trailer
if ( m_pNextLink != NULL )
{
m_pNextLink->SetPreviousTrainCarriage ( NULL );
}
SetNextTrainCarriage ( NULL );
}
else if ( this->GetVehicleType () == CLIENTVEHICLE_TRAIN && pVehicle->GetVehicleType () == CLIENTVEHICLE_TRAIN )
{
if ( !m_pPreviousLink )
SetIsChainEngine ( true );
CClientVehicle* pChainEngine = GetChainEngine ();
CVehicle* pTowedGameVehicle = pVehicle->GetGameVehicle ();
SetNextTrainCarriage ( pVehicle );
pVehicle->SetTrainTrack ( pChainEngine->GetTrainTrack () );
pVehicle->SetTrainPosition ( pChainEngine->GetTrainPosition () );
pVehicle->SetTrainDirection ( pChainEngine->GetTrainDirection () );
CVector vecPosition;
pChainEngine->GetPosition ( vecPosition );
pVehicle->SetPosition ( vecPosition );
if ( m_pVehicle && pTowedGameVehicle )
{
m_pVehicle->AttachTrainCarriage ( pTowedGameVehicle );
}
return true;
}
else if ( this->GetVehicleType () == CLIENTVEHICLE_TRAIN || ( pVehicle && pVehicle->GetVehicleType () == CLIENTVEHICLE_TRAIN ) )
{
return false;
}
if ( pVehicle == m_pTowedVehicle )
return true;
// Do we already have a towed vehicle?
if ( m_pTowedVehicle && pVehicle != m_pTowedVehicle )
{
// Remove it
CVehicle * pGameVehicle = m_pTowedVehicle->GetGameVehicle ();
if ( pGameVehicle && m_pVehicle )
pGameVehicle->BreakTowLink ();
m_pTowedVehicle->m_pTowedByVehicle = NULL;
m_pTowedVehicle = NULL;
}
// Do we have a new one to set?
if ( pVehicle )
{
// Are we trying to establish a circular loop? (this would freeze everything up)
CClientVehicle* pCircTestVehicle = pVehicle;
while ( pCircTestVehicle )
{
if ( pCircTestVehicle == this )
return false;
pCircTestVehicle = pCircTestVehicle->m_pTowedVehicle;
}
pVehicle->m_pTowedByVehicle = this;
// Add it
if ( m_pVehicle )
{
CVehicle * pGameVehicle = pVehicle->GetGameVehicle ();
if ( pGameVehicle )
{
// Both vehicles are streamed in
if ( m_pVehicle->GetTowedVehicle () != pGameVehicle )
{
if ( vecRotationDegrees )
{
pVehicle->SetRotationDegrees ( *vecRotationDegrees );
}
else
{
// Apply the vehicle's rotation to the trailer
CVector vecRotationDegrees;
GetRotationDegrees ( vecRotationDegrees );
pVehicle->SetRotationDegrees ( vecRotationDegrees );
}
InternalSetTowLink ( pVehicle );
}
}
else
{
// If only the towing vehicle is streamed in, force the towed vehicle to stream in
pVehicle->StreamIn ( true );
}
}
else
{
// If the towing vehicle is not streamed in, the towed vehicle can't be streamed in,
// so we move it to the towed position.
CVector vecPosition;
pVehicle->GetPosition ( vecPosition );
pVehicle->UpdateStreamPosition ( vecPosition );
}
}
else
m_ulIllegalTowBreakTime = 0;
m_pTowedVehicle = pVehicle;
return true;
}
bool CClientVehicle::InternalSetTowLink ( CClientVehicle* pTrailer )
{
CVehicle* pGameVehicle = pTrailer->GetGameVehicle ();
if ( !pGameVehicle || !m_pVehicle )
return false;
// Get the position
CVector* pTrailerPosition = pGameVehicle->GetPosition ();
CVector* pVehiclePosition = m_pVehicle->GetPosition ();
// Get hitch and tow (world) position
CVector vecHitchPosition, vecTowBarPosition;
pGameVehicle->GetTowHitchPos ( &vecHitchPosition );
m_pVehicle->GetTowBarPos ( &vecTowBarPosition, pGameVehicle );
// Calculate the new position (rotation should be set already)
CVector vecOffset = vecHitchPosition - *pTrailerPosition;
CVector vecDest = vecTowBarPosition - vecOffset;
pTrailer->SetPosition ( vecDest );
// Apply the towed-by-vehicle's velocity to the trailer
CVector vecMoveSpeed;
this->GetMoveSpeed ( vecMoveSpeed );
pTrailer->SetMoveSpeed ( vecMoveSpeed );
// SA can attach the trailer now
pGameVehicle->SetTowLink ( m_pVehicle );
pTrailer->PlaceProperlyOnGround (); // Probably not needed
return true;
}
bool CClientVehicle::SetWinchType ( eWinchType winchType )
{
if ( GetModel () == 417 ) // Leviathan
{
if ( m_pVehicle )
{
if ( m_eWinchType == WINCH_NONE )
{
m_pVehicle->SetWinchType ( winchType );
m_eWinchType = winchType;
}
return true;
}
else
{
m_eWinchType = winchType;
return true;
}
}
return false;
}
bool CClientVehicle::PickupEntityWithWinch ( CClientEntity* pEntity )
{
if ( m_pVehicle )
{
if ( m_eWinchType != WINCH_NONE )
{
CEntity* pGameEntity = NULL;
eClientEntityType entityType = pEntity->GetType ();
switch ( entityType )
{
case CCLIENTOBJECT:
{
CClientObject* pObject = static_cast < CClientObject* > ( pEntity );
pGameEntity = pObject->GetGameObject ();
break;
}
case CCLIENTPED:
case CCLIENTPLAYER:
{
CClientPed* pModel = static_cast < CClientPed* > ( pEntity );
pGameEntity = pModel->GetGameEntity ();
break;
}
case CCLIENTVEHICLE:
{
CClientVehicle* pVehicle = static_cast < CClientVehicle* > ( pEntity );
pGameEntity = pVehicle->GetGameVehicle ();
break;
}
}
if ( pGameEntity )
{
m_pVehicle->PickupEntityWithWinch ( pGameEntity );
m_pPickedUpWinchEntity = pEntity;
return true;
}
}
}
return false;
}
bool CClientVehicle::ReleasePickedUpEntityWithWinch ( void )
{
if ( m_pVehicle )
{
if ( m_pPickedUpWinchEntity )
{
m_pVehicle->ReleasePickedUpEntityWithWinch ();
m_pPickedUpWinchEntity = NULL;
return true;
}
}
return false;
}
void CClientVehicle::SetRopeHeightForHeli ( float fRopeHeight )
{
if ( m_pVehicle )
{
m_pVehicle->SetRopeHeightForHeli ( fRopeHeight );
}
}
CClientEntity* CClientVehicle::GetPickedUpEntityWithWinch ( void )
{
CClientEntity* pEntity = m_pPickedUpWinchEntity;
if ( m_pVehicle )
{
CPhysical* pPhysical = m_pVehicle->QueryPickedUpEntityWithWinch ();
if ( pPhysical )
{
eEntityType entityType = pPhysical->GetEntityType ();
switch ( entityType )
{
case ENTITY_TYPE_VEHICLE:
{
CVehicle* pGameVehicle = dynamic_cast < CVehicle* > ( pPhysical );
CClientVehicle* pVehicle = m_pVehicleManager->Get ( pGameVehicle, false );
if ( pVehicle )
pEntity = static_cast < CClientEntity* > ( pVehicle );
break;
}
case ENTITY_TYPE_PED:
{
CPlayerPed* pPlayerPed = dynamic_cast < CPlayerPed* > ( pPhysical );
CClientPed* pModel = m_pManager->GetPedManager ()->Get ( pPlayerPed, false, false );
if ( pModel )
pEntity = static_cast < CClientEntity* > ( pModel );
break;
}
case ENTITY_TYPE_OBJECT:
{
CObject* pGameObject = dynamic_cast < CObject* > ( pPhysical );
CClientObject* pObject = m_pManager->GetObjectManager ()->Get ( pGameObject, false );
if ( pObject )
pEntity = static_cast < CClientEntity* > ( pObject );
break;
}
}
}
}
return pEntity;
}
bool CClientVehicle::SetRegPlate ( const char* szPlate )
{
if ( szPlate )
{
SString strPlateText = SStringX( szPlate ).Left( 8 );
if ( strPlateText != m_strRegPlate )
{
m_strRegPlate = strPlateText;
if ( m_pVehicle )
{
m_pVehicle->SetPlateText( m_strRegPlate );
}
return true;
}
}
return false;
}
unsigned char CClientVehicle::GetPaintjob ( void )
{
if ( m_pVehicle )
{
int iRemap = m_pVehicle->GetRemapIndex ();
return (iRemap == -1) ? 3 : iRemap;
}
return m_ucPaintjob;
}
void CClientVehicle::SetPaintjob ( unsigned char ucPaintjob )
{
if ( ucPaintjob != m_ucPaintjob && ucPaintjob <= 4 )
{
if ( m_pVehicle )
{
m_pVehicle->SetRemap ( static_cast < unsigned int > ( ucPaintjob ) );
}
m_ucPaintjob = ucPaintjob;
}
}
float CClientVehicle::GetDirtLevel ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetBodyDirtLevel ();
}
return m_fDirtLevel;
}
void CClientVehicle::SetDirtLevel ( float fDirtLevel )
{
if ( m_pVehicle )
{
m_pVehicle->SetBodyDirtLevel ( fDirtLevel );
}
m_fDirtLevel = fDirtLevel;
}
bool CClientVehicle::IsOnWater ( void )
{
if ( m_pVehicle )
{
float fWaterLevel;
CVector vecPosition, vecTemp;
GetPosition ( vecPosition );
float fDistToBaseOfModel = vecPosition.fZ - m_pVehicle->GetDistanceFromCentreOfMassToBaseOfModel();
if ( g_pGame->GetWaterManager ()->GetWaterLevel ( vecPosition, &fWaterLevel, true, &vecTemp ) )
{
if (fDistToBaseOfModel <= fWaterLevel) {
return true;
}
}
}
return false;
}
bool CClientVehicle::IsInWater ( void )
{
if ( m_pModelInfo )
{
CBoundingBox* pBoundingBox = m_pModelInfo->GetBoundingBox ();
if ( pBoundingBox )
{
CVector vecMin = pBoundingBox->vecBoundMin;
CVector vecPosition, vecTemp;
GetPosition ( vecPosition );
vecMin += vecPosition;
float fWaterLevel;
if ( g_pGame->GetWaterManager ()->GetWaterLevel ( vecPosition, &fWaterLevel, true, &vecTemp ) )
{
if ( vecPosition.fZ <= fWaterLevel )
{
return true;
}
}
}
}
return false;
}
float CClientVehicle::GetDistanceFromGround ( void )
{
CVector vecPosition;
GetPosition ( vecPosition );
float fGroundLevel = static_cast < float > ( g_pGame->GetWorld ()->FindGroundZFor3DPosition ( &vecPosition ) );
CBoundingBox* pBoundingBox = m_pModelInfo->GetBoundingBox ();
if ( pBoundingBox )
fGroundLevel -= pBoundingBox->vecBoundMin.fZ + pBoundingBox->vecBoundOffset.fZ;
return ( vecPosition.fZ - fGroundLevel );
}
bool CClientVehicle::IsOnGround ( void )
{
if ( m_pModelInfo )
{
CBoundingBox* pBoundingBox = m_pModelInfo->GetBoundingBox ();
if ( pBoundingBox )
{
CVector vecMin = pBoundingBox->vecBoundMin;
CVector vecPosition;
GetPosition ( vecPosition );
vecMin += vecPosition;
float fGroundLevel = static_cast < float > (
g_pGame->GetWorld ()->FindGroundZFor3DPosition ( &vecPosition ) );
/* Is the lowest point of the bounding box lower than 0.5 above the floor,
or is the lowest point of the bounding box higher than 0.3 below the floor */
return ( ( fGroundLevel > vecMin.fZ && ( fGroundLevel - vecMin.fZ ) < 0.5f ) ||
( vecMin.fZ > fGroundLevel && ( vecMin.fZ - fGroundLevel ) < 0.3f ) );
}
}
return m_bIsOnGround;
}
void CClientVehicle::LockSteering ( bool bLock )
{
// STATUS_TRAIN_MOVING or STATUS_PLAYER_DISABLED will do. STATUS_TRAIN_NOT_MOVING is neater but will screw up planes (turns off the engine).
eEntityStatus Status = m_pVehicle->GetEntityStatus ();
if ( bLock && Status != STATUS_TRAIN_MOVING ) {
m_NormalStatus = Status;
m_pVehicle->SetEntityStatus ( STATUS_TRAIN_MOVING );
} else if ( !bLock && Status == STATUS_TRAIN_MOVING ) {
m_pVehicle->SetEntityStatus ( m_NormalStatus );
}
return;
}
bool CClientVehicle::IsSmokeTrailEnabled ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->IsSmokeTrailEnabled ();
}
return m_bSmokeTrail;
}
void CClientVehicle::SetSmokeTrailEnabled ( bool bEnabled )
{
if ( m_pVehicle )
{
m_pVehicle->SetSmokeTrailEnabled ( bEnabled );
}
m_bSmokeTrail = bEnabled;
}
void CClientVehicle::ResetInterpolation ( void )
{
if ( HasTargetPosition () )
SetPosition ( m_interp.pos.vecTarget );
if ( HasTargetRotation () )
SetRotationDegrees ( m_interp.rot.vecTarget );
m_interp.pos.ulFinishTime = 0;
m_interp.rot.ulFinishTime = 0;
}
void CClientVehicle::Interpolate ( void )
{
// Interpolate it if: It has a driver and it's not local and we're not syncing it or
// It has no driver and we're not syncing it.
if ( ( m_pDriver && !m_pDriver->IsLocalPlayer () && !static_cast < CDeathmatchVehicle* > ( this ) ->IsSyncing () ) ||
( !m_pDriver && !static_cast < CDeathmatchVehicle* > ( this ) ->IsSyncing () ) )
{
UpdateTargetPosition ();
UpdateTargetRotation ();
}
else
{
// Otherwize make sure we have no interpolation stuff stored
RemoveTargetPosition ();
RemoveTargetRotation ();
}
}
void CClientVehicle::GetInitialDoorStates ( SFixedArray < unsigned char, MAX_DOORS >& ucOutDoorStates )
{
switch ( m_usModel )
{
case VT_BAGGAGE:
case VT_BANDITO:
case VT_BFINJECT:
case VT_CADDY:
case VT_DOZER:
case VT_FORKLIFT:
case VT_KART:
case VT_MOWER:
case VT_QUAD:
case VT_RCBANDIT:
case VT_RCCAM:
case VT_RCGOBLIN:
case VT_RCRAIDER:
case VT_RCTIGER:
case VT_TRACTOR:
case VT_VORTEX:
memset ( &ucOutDoorStates[0], DT_DOOR_MISSING, MAX_DOORS );
// Keep the bonet and boot intact
ucOutDoorStates [ 0 ] = ucOutDoorStates [ 1 ] = DT_DOOR_INTACT;
break;
default:
memset ( &ucOutDoorStates[0], DT_DOOR_INTACT, MAX_DOORS );
}
}
void CClientVehicle::SetTargetPosition ( const CVector& vecTargetPosition, unsigned long ulDelay, bool bValidVelocityZ, float fVelocityZ )
{
// Are we streamed in?
if ( m_pVehicle )
{
UpdateTargetPosition ();
UpdateUnderFloorFix ( vecTargetPosition, bValidVelocityZ, fVelocityZ );
unsigned long ulTime = CClientTime::GetTime ();
CVector vecLocalPosition;
GetPosition ( vecLocalPosition );
#ifdef MTA_DEBUG
m_interp.pos.vecStart = vecLocalPosition;
#endif
m_interp.pos.vecTarget = vecTargetPosition;
// Calculate the relative error
m_interp.pos.vecError = vecTargetPosition - vecLocalPosition;
// Extrapolation
const SVehExtrapolateSettings& vehExtrapolate = g_pClientGame->GetVehExtrapolateSettings ();
if ( vehExtrapolate.bEnabled )
{
// Base amount to account for something
int iExtrapolateMs = vehExtrapolate.iBaseMs;
if ( CClientPlayer* pPlayerDriver = DynamicCast < CClientPlayer > ( (CClientEntity*)m_pDriver ) )
iExtrapolateMs += pPlayerDriver->GetLatency () * vehExtrapolate.iScalePercent / 110;
// Limit amount
iExtrapolateMs = Clamp ( 0, iExtrapolateMs, vehExtrapolate.iMaxMs );
CVector vecVelocity;
GetMoveSpeed ( vecVelocity );
vecVelocity *= 50.f * iExtrapolateMs * (1/1000.f);
m_interp.pos.vecError += vecVelocity;
}
// Apply the error over 400ms (i.e. 1/4 per 100ms )
m_interp.pos.vecError *= Lerp < const float > ( 0.25f, UnlerpClamped( 100, ulDelay, 400 ), 1.0f );
// Get the interpolation interval
m_interp.pos.ulStartTime = ulTime;
m_interp.pos.ulFinishTime = ulTime + ulDelay;
// Initialize the interpolation
m_interp.pos.fLastAlpha = 0.0f;
}
else
{
// Update our position now
SetPosition ( vecTargetPosition );
}
}
void CClientVehicle::RemoveTargetPosition ( void )
{
m_interp.pos.ulFinishTime = 0;
}
void CClientVehicle::SetTargetRotation ( const CVector& vecRotation, unsigned long ulDelay )
{
// Are we streamed in?
if ( m_pVehicle )
{
UpdateTargetRotation ();
unsigned long ulTime = CClientTime::GetTime ();
CVector vecLocalRotation;
GetRotationDegrees ( vecLocalRotation );
#ifdef MTA_DEBUG
m_interp.rot.vecStart = vecLocalRotation;
#endif
m_interp.rot.vecTarget = vecRotation;
// Get the error
m_interp.rot.vecError.fX = GetOffsetDegrees ( vecLocalRotation.fX, vecRotation.fX );
m_interp.rot.vecError.fY = GetOffsetDegrees ( vecLocalRotation.fY, vecRotation.fY );
m_interp.rot.vecError.fZ = GetOffsetDegrees ( vecLocalRotation.fZ, vecRotation.fZ );
// Apply the error over 250ms (i.e. 2/5 per 100ms )
m_interp.rot.vecError *= Lerp < const float > ( 0.40f, UnlerpClamped( 100, ulDelay, 400 ), 1.0f );
// Get the interpolation interval
m_interp.rot.ulStartTime = ulTime;
m_interp.rot.ulFinishTime = ulTime + ulDelay;
// Initialize the interpolation
m_interp.rot.fLastAlpha = 0.0f;
}
else
{
// Update our rotation now
SetRotationDegrees ( vecRotation );
}
}
void CClientVehicle::RemoveTargetRotation ( void )
{
m_interp.rot.ulFinishTime = 0;
}
void CClientVehicle::UpdateTargetPosition ( void )
{
if ( HasTargetPosition () )
{
// Grab the current game position
CVector vecCurrentPosition;
GetPosition ( vecCurrentPosition );
// Get the factor of time spent from the interpolation start
// to the current time.
unsigned long ulCurrentTime = CClientTime::GetTime ();
float fAlpha = SharedUtil::Unlerp ( m_interp.pos.ulStartTime,
ulCurrentTime,
m_interp.pos.ulFinishTime );
// Don't let it overcompensate the error too much
fAlpha = SharedUtil::Clamp ( 0.0f, fAlpha, 1.5f );
// Get the current error portion to compensate
float fCurrentAlpha = fAlpha - m_interp.pos.fLastAlpha;
m_interp.pos.fLastAlpha = fAlpha;
// Apply the error compensation
CVector vecCompensation = SharedUtil::Lerp ( CVector (), fCurrentAlpha, m_interp.pos.vecError );
// If we finished compensating the error, finish it for the next pulse
if ( fAlpha == 1.5f )
{
m_interp.pos.ulFinishTime = 0;
}
CVector vecNewPosition = vecCurrentPosition + vecCompensation;
// Check if the distance to interpolate is too far.
CVector vecVelocity;
GetMoveSpeed ( vecVelocity );
float fThreshold = ( VEHICLE_INTERPOLATION_WARP_THRESHOLD + VEHICLE_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED * vecVelocity.Length () ) * g_pGame->GetGameSpeed () * TICK_RATE / 100;
// There is a reason to have this condition this way: To prevent NaNs generating new NaNs after interpolating (Comparing with NaNs always results to false).
if ( ! ( ( vecCurrentPosition - m_interp.pos.vecTarget ).Length () <= fThreshold ) )
{
// Abort all interpolation
m_interp.pos.ulFinishTime = 0;
vecNewPosition = m_interp.pos.vecTarget;
if ( HasTargetRotation () )
SetRotationDegrees ( m_interp.rot.vecTarget );
m_interp.rot.ulFinishTime = 0;
}
SetPosition ( vecNewPosition, false );
if ( !m_bIsCollisionEnabled )
{
if ( m_eVehicleType != CLIENTVEHICLE_HELI && m_eVehicleType != CLIENTVEHICLE_BOAT )
{
// Ghostmode upwards movement compensation
CVector MoveSpeed;
m_pVehicle->GetMoveSpeed ( &MoveSpeed );
float SpeedXY = CVector( MoveSpeed.fX, MoveSpeed.fY, 0 ).Length ();
if ( MoveSpeed.fZ > 0.00 && MoveSpeed.fZ < 0.02 && MoveSpeed.fZ > SpeedXY )
MoveSpeed.fZ = SpeedXY;
m_pVehicle->SetMoveSpeed ( &MoveSpeed );
}
}
#ifdef MTA_DEBUG
if ( g_pClientGame->IsShowingInterpolation () &&
g_pClientGame->GetLocalPlayer ()->GetOccupiedVehicle () == this )
{
// DEBUG
SString strBuffer ( "-== Vehicle interpolation ==-\n"
"vecStart: %f %f %f\n"
"vecTarget: %f %f %f\n"
"Position: %f %f %f\n"
"Error: %f %f %f\n"
"Alpha: %f\n"
"Interpolating: %s\n",
m_interp.pos.vecStart.fX, m_interp.pos.vecStart.fY, m_interp.pos.vecStart.fZ,
m_interp.pos.vecTarget.fX, m_interp.pos.vecTarget.fY, m_interp.pos.vecTarget.fZ,
vecNewPosition.fX, vecNewPosition.fY, vecNewPosition.fZ,
m_interp.pos.vecError.fX, m_interp.pos.vecError.fY, m_interp.pos.vecError.fZ,
fAlpha, ( m_interp.pos.ulFinishTime == 0 ? "no" : "yes" ) );
g_pClientGame->GetManager ()->GetDisplayManager ()->DrawText2D ( strBuffer, CVector ( 0.45f, 0.05f, 0 ), 1.0f, 0xFFFFFFFF );
}
#endif
// Update our contact players
CVector vecPlayerPosition;
CVector vecOffset;
list < CClientPed * > ::iterator iter = m_Contacts.begin ();
for ( ; iter != m_Contacts.end () ; iter++ )
{
CClientPed * pModel = *iter;
pModel->GetPosition ( vecPlayerPosition );
vecOffset = vecPlayerPosition - vecCurrentPosition;
vecPlayerPosition = vecNewPosition + vecOffset;
pModel->SetPosition ( vecPlayerPosition );
}
}
}
void CClientVehicle::UpdateTargetRotation ( void )
{
// Do we have a rotation to move towards? and are we streamed in?
if ( HasTargetRotation () )
{
// Grab the current game rotation
CVector vecCurrentRotation;
GetRotationDegrees ( vecCurrentRotation );
// Get the factor of time spent from the interpolation start
// to the current time.
unsigned long ulCurrentTime = CClientTime::GetTime ();
float fAlpha = SharedUtil::Unlerp ( m_interp.rot.ulStartTime,
ulCurrentTime,
m_interp.rot.ulFinishTime );
// Don't let it to overcompensate the error
fAlpha = SharedUtil::Clamp ( 0.0f, fAlpha, 1.0f );
// Get the current error portion to compensate
float fCurrentAlpha = fAlpha - m_interp.rot.fLastAlpha;
m_interp.rot.fLastAlpha = fAlpha;
CVector vecCompensation = SharedUtil::Lerp ( CVector (), fCurrentAlpha, m_interp.rot.vecError );
// If we finished compensating the error, finish it for the next pulse
if ( fAlpha == 1.0f )
{
m_interp.rot.ulFinishTime = 0;
}
SetRotationDegrees ( vecCurrentRotation + vecCompensation, false );
}
}
// Cars under road fix hack
void CClientVehicle::UpdateUnderFloorFix ( const CVector& vecTargetPosition, bool bValidVelocityZ, float fVelocityZ )
{
CVector vecLocalPosition;
GetPosition ( vecLocalPosition );
bool bForceLocalZ = false;
if ( bValidVelocityZ && m_eVehicleType != CLIENTVEHICLE_HELI && m_eVehicleType != CLIENTVEHICLE_PLANE )
{
// If remote z higher by too much and remote not doing any z movement, warp local z coord
float fDeltaZ = vecTargetPosition.fZ - vecLocalPosition.fZ;
if ( fDeltaZ > 0.4f && fDeltaZ < 10.0f )
{
if ( fabsf ( fVelocityZ ) < 0.01f )
{
bForceLocalZ = true;
}
}
}
// Only force z coord if needed for at least two consecutive calls
if ( !bForceLocalZ )
m_uiForceLocalZCounter = 0;
else
if ( m_uiForceLocalZCounter++ > 1 )
{
vecLocalPosition.fZ = vecTargetPosition.fZ;
SetPosition ( vecLocalPosition );
}
}
bool CClientVehicle::IsEnterable ( void )
{
if ( m_pVehicle )
{
// Server vehicle?
if ( !IsLocalEntity () )
{
if ( GetHealth () > 0.0f )
{
if ( !IsInWater() || (GetVehicleType() == CLIENTVEHICLE_BOAT ||
m_usModel == 447 /* sea sparrow */
|| m_usModel == 417 /* levithan */
|| m_usModel == 460 /* skimmer */ ) )
{
return true;
}
}
}
}
return false;
}
bool CClientVehicle::HasRadio ( void )
{
if ( m_eVehicleType != CLIENTVEHICLE_BMX ) return true;
return false;
}
bool CClientVehicle::HasPoliceRadio ( void )
{
switch ( m_usModel )
{
case VT_COPCARLA:
case VT_COPCARSF:
case VT_COPCARVG:
case VT_COPCARRU:
case VT_POLMAV:
case VT_COPBIKE:
case VT_SWATVAN:
return true;
break;
default:
break;
}
return false;
}
void CClientVehicle::RemoveAllProjectiles ( void )
{
CClientProjectile * pProjectile = NULL;
list < CClientProjectile* > ::iterator iter = m_Projectiles.begin ();
for ( ; iter != m_Projectiles.end () ; iter++ )
{
pProjectile = *iter;
pProjectile->m_pCreator = NULL;
g_pClientGame->GetElementDeleter ()->Delete ( pProjectile );
}
m_Projectiles.clear ();
}
void CClientVehicle::SetGravity ( const CVector& vecGravity )
{
if ( m_pVehicle )
m_pVehicle->SetGravity ( &vecGravity );
m_vecGravity = vecGravity;
}
SColor CClientVehicle::GetHeadLightColor ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetHeadLightColor ();
}
return m_HeadLightColor;
}
int CClientVehicle::GetCurrentGear ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetCurrentGear ();
}
return 0;
}
void CClientVehicle::SetHeadLightColor ( const SColor color )
{
if ( m_pVehicle )
{
m_pVehicle->SetHeadLightColor ( color );
}
m_HeadLightColor = color;
}
//
// Below here is basically awful.
// But there you go.
//
#if OCCUPY_DEBUG_INFO
#define INFO(x) g_pCore->GetConsole ()->Printf x
#define WARN(x) g_pCore->GetConsole ()->Printf x
#else
#define INFO(x) {}
#define WARN(x) {}
#endif
std::string GetPlayerName ( CClientPed* pClientPed )
{
if ( !pClientPed )
return "null";
if ( IS_PLAYER ( pClientPed ) )
{
CClientPlayer* pPlayer = static_cast < CClientPlayer * > ( pClientPed );
return pPlayer->GetNick ();
}
return "ped";
}
//
// Make a ped become an occupied driver/passenger
// Static function
//
void CClientVehicle::SetPedOccupiedVehicle ( CClientPed* pClientPed, CClientVehicle* pVehicle, unsigned int uiSeat, unsigned char ucDoor )
{
INFO (( "SetPedOccupiedVehicle:%s in vehicle:0x%08x seat:%d door:%u", GetPlayerName( pClientPed ).c_str (), pVehicle, uiSeat, ucDoor ));
if ( !pClientPed || !pVehicle )
return;
// Clear ped from any current occupied seat in this vehicle
if ( pClientPed->m_pOccupiedVehicle == pVehicle )
{
if ( pVehicle->m_pDriver == pClientPed )
pVehicle->m_pDriver = NULL;
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pPassengers ) ; i++ )
if ( pVehicle->m_pPassengers[i] == pClientPed )
pVehicle->m_pPassengers[i] = NULL;
}
// Vehicle vars
if ( uiSeat == 0 )
{
if ( pVehicle->m_pDriver && pVehicle->m_pDriver != pClientPed )
{
WARN (( "Emergency occupied driver eject by %s on %s\n", GetPlayerName( pClientPed ).c_str (), GetPlayerName( pVehicle->m_pDriver ).c_str () ));
UnpairPedAndVehicle ( pVehicle->m_pDriver, pVehicle );
}
pVehicle->m_pDriver = pClientPed;
}
else
{
assert ( uiSeat <= NUMELMS(pVehicle->m_pPassengers) );
if ( pVehicle->m_pPassengers [uiSeat-1] && pVehicle->m_pPassengers [uiSeat-1] != pClientPed )
{
WARN (( "Emergency occupied passenger eject by %s on %s\n", GetPlayerName( pClientPed ).c_str (), GetPlayerName( pVehicle->m_pPassengers [uiSeat-1] ).c_str () ));
UnpairPedAndVehicle ( pVehicle->m_pPassengers [uiSeat-1], pVehicle );
}
pVehicle->m_pPassengers [uiSeat-1] = pClientPed;
}
// Ped vars
pClientPed->m_pOccupiedVehicle = pVehicle;
pClientPed->m_uiOccupiedVehicleSeat = uiSeat;
if ( ucDoor != 0xFF )
pVehicle->AllowDoorRatioSetting ( ucDoor, true );
else if ( uiSeat < 4 )
pVehicle->AllowDoorRatioSetting ( uiSeat + 2, true );
// Checks
ValidatePedAndVehiclePair ( pClientPed, pVehicle );
}
//
// Make a ped become an occupying driver/passenger
// Static function
//
void CClientVehicle::SetPedOccupyingVehicle ( CClientPed* pClientPed, CClientVehicle* pVehicle, unsigned int uiSeat, unsigned char ucDoor )
{
INFO (( "SetPedOccupyingVehicle:%s in vehicle:0x%08x seat:%d door:%u", GetPlayerName( pClientPed ).c_str (), pVehicle, uiSeat, ucDoor ));
if ( !pClientPed || !pVehicle )
return;
// Clear ped from any current occupying seat in this vehicle
if ( pClientPed->m_pOccupyingVehicle == pVehicle )
{
if ( pVehicle->m_pOccupyingDriver == pClientPed )
pVehicle->m_pOccupyingDriver = NULL;
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pOccupyingPassengers ) ; i++ )
if ( pVehicle->m_pOccupyingPassengers[i] == pClientPed )
pVehicle->m_pOccupyingPassengers[i] = NULL;
}
// Vehicle vars
if ( uiSeat == 0 )
{
if ( pVehicle->m_pOccupyingDriver && pVehicle->m_pOccupyingDriver != pClientPed )
{
WARN (( "Emergency occupying driver eject by %s on %s\n", GetPlayerName( pClientPed ).c_str (), GetPlayerName( pVehicle->m_pOccupyingDriver ).c_str () ));
UnpairPedAndVehicle ( pVehicle->m_pOccupyingDriver, pVehicle );
}
pVehicle->m_pOccupyingDriver = pClientPed;
}
else
{
assert ( uiSeat <= NUMELMS(pVehicle->m_pOccupyingPassengers) );
if ( pVehicle->m_pOccupyingPassengers [uiSeat-1] && pVehicle->m_pOccupyingPassengers [uiSeat-1] != pClientPed )
{
WARN (( "Emergency occupying passenger eject by %s on %s\n", GetPlayerName( pClientPed ).c_str (), GetPlayerName( pVehicle->m_pOccupyingPassengers [uiSeat-1] ).c_str () ));
UnpairPedAndVehicle ( pVehicle->m_pOccupyingPassengers [uiSeat-1], pVehicle );
}
pVehicle->m_pOccupyingPassengers [uiSeat-1] = pClientPed;
}
// Ped vars
pClientPed->m_pOccupyingVehicle = pVehicle;
// if ( uiSeat >= 0 && uiSeat < 8 )
// pClientPed->m_uiOccupyingSeat = uiSeat;
if ( ucDoor != 0xFF )
pVehicle->AllowDoorRatioSetting ( ucDoor, false );
// Checks
ValidatePedAndVehiclePair ( pClientPed, pVehicle );
}
//
// Check ped <> vehicle pointers
// Static function
//
void CClientVehicle::ValidatePedAndVehiclePair( CClientPed* pClientPed, CClientVehicle* pVehicle )
{
#if MTA_DEBUG
// Occupied
// Vehicle vars
if ( pVehicle->m_pDriver )
assert ( pVehicle->m_pDriver->m_pOccupiedVehicle == pVehicle );
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pPassengers ) ; i++ )
if ( pVehicle->m_pPassengers[i] )
assert ( pVehicle->m_pPassengers[i]->m_pOccupiedVehicle == pVehicle );
// Ped vars
if ( pClientPed->m_pOccupiedVehicle )
{
// Make sure refed once by vehicle
int iCount = 0;
if ( pClientPed->m_pOccupiedVehicle->m_pDriver == pClientPed )
iCount++;
for ( int i = 0 ; i < NUMELMS ( pClientPed->m_pOccupiedVehicle->m_pPassengers ) ; i++ )
if ( pClientPed->m_pOccupiedVehicle->m_pPassengers[i] == pClientPed )
iCount++;
assert ( iCount == 1 );
}
// Occupying
// Vehicle vars
if ( pVehicle->m_pOccupyingDriver )
assert ( pVehicle->m_pOccupyingDriver->m_pOccupyingVehicle == pVehicle );
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pOccupyingPassengers ) ; i++ )
if ( pVehicle->m_pOccupyingPassengers[i] )
assert ( pVehicle->m_pOccupyingPassengers[i]->m_pOccupyingVehicle == pVehicle );
// Ped vars
if ( pClientPed->m_pOccupyingVehicle )
{
// Make sure refed once by vehicle
int iCount = 0;
if ( pClientPed->m_pOccupyingVehicle->m_pOccupyingDriver == pClientPed )
iCount++;
for ( int i = 0 ; i < NUMELMS ( pClientPed->m_pOccupyingVehicle->m_pOccupyingPassengers ) ; i++ )
if ( pClientPed->m_pOccupyingVehicle->m_pOccupyingPassengers[i] == pClientPed )
iCount++;
assert ( iCount == 1 );
}
#endif
}
//
// Make sure there is no association between a ped and a vehicle
// Static function
//
void CClientVehicle::UnpairPedAndVehicle( CClientPed* pClientPed, CClientVehicle* pVehicle )
{
if ( !pClientPed || !pVehicle )
return;
// Checks
ValidatePedAndVehiclePair ( pClientPed, pVehicle );
// Occupied
// Vehicle vars
if ( pVehicle->m_pDriver == pClientPed )
{
INFO (( "UnpairPedAndVehicle: m_pDriver:%s from vehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), pVehicle ));
pVehicle->m_pDriver = NULL;
}
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pPassengers ) ; i++ )
if ( pVehicle->m_pPassengers[i] == pClientPed )
{
INFO (( "UnpairPedAndVehicle: m_pPassenger:%s seat:%d from vehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), i + 1, pVehicle ));
pVehicle->m_pPassengers[i] = NULL;
}
// Ped vars
if ( pClientPed->m_pOccupiedVehicle == pVehicle )
{
INFO (( "UnpairPedAndVehicle: pClientPed:%s from m_pOccupiedVehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), pVehicle ));
if ( pClientPed->m_ucLeavingDoor != 0xFF )
{
pVehicle->AllowDoorRatioSetting ( pClientPed->m_ucLeavingDoor, true );
pClientPed->m_ucLeavingDoor = 0xFF;
}
pClientPed->m_pOccupiedVehicle = NULL;
pClientPed->m_uiOccupiedVehicleSeat = 0xFF;
}
// Occupying
// Vehicle vars
if ( pVehicle->m_pOccupyingDriver == pClientPed )
{
INFO (( "UnpairPedAndVehicle: m_pOccupyingDriver:%s from vehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), pVehicle ));
pVehicle->m_pOccupyingDriver = NULL;
}
for ( int i = 0 ; i < NUMELMS ( pVehicle->m_pOccupyingPassengers ) ; i++ )
if ( pVehicle->m_pOccupyingPassengers[i] == pClientPed )
{
INFO (( "UnpairPedAndVehicle: m_pOccupyingPassenger:%s seat:%d from vehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), i + 1, pVehicle ));
pVehicle->m_pOccupyingPassengers[i] = NULL;
}
// Ped vars
if ( pClientPed->m_pOccupyingVehicle == pVehicle )
{
INFO (( "UnpairPedAndVehicle: pClientPed:%s from m_pOccupyingVehicle:0x%08x", GetPlayerName( pClientPed ).c_str (), pVehicle ));
pClientPed->m_pOccupyingVehicle = NULL;
//pClientPed->m_uiOccupyingSeat = 0xFF;
}
}
//
// Make sure there is no association between a ped and its vehicle
// Static function
//
void CClientVehicle::UnpairPedAndVehicle( CClientPed* pClientPed )
{
UnpairPedAndVehicle ( pClientPed, pClientPed->GetOccupiedVehicle () );
UnpairPedAndVehicle ( pClientPed, pClientPed->m_pOccupyingVehicle );
UnpairPedAndVehicle ( pClientPed, pClientPed->GetRealOccupiedVehicle () );
if ( pClientPed->m_pOccupiedVehicle )
{
WARN (( "*** Unexpected m_pOccupiedVehicle:0x%08x for %s\n", pClientPed->m_pOccupiedVehicle, GetPlayerName( pClientPed ).c_str () ));
pClientPed->m_pOccupiedVehicle = NULL;
}
if ( pClientPed->m_pOccupyingVehicle )
{
WARN (( "*** Unexpected m_pOccupyingVehicle:0x%08x for %s\n", pClientPed->m_pOccupyingVehicle, GetPlayerName( pClientPed ).c_str () ));
pClientPed->m_pOccupyingVehicle = NULL;
}
}
void CClientVehicle::ApplyHandling ( void )
{
if ( m_pVehicle )
m_pVehicle->RecalculateHandling ();
m_bHasCustomHandling = true;
}
CHandlingEntry* CClientVehicle::GetHandlingData ( void )
{
if ( m_pVehicle )
{
return m_pVehicle->GetHandlingData ();
}
else if ( m_pHandlingEntry )
{
return m_pHandlingEntry;
}
return NULL;
}
CSphere CClientVehicle::GetWorldBoundingSphere ( void )
{
CSphere sphere;
CModelInfo* pModelInfo = g_pGame->GetModelInfo ( GetModel () );
if ( pModelInfo )
{
CBoundingBox* pBoundingBox = pModelInfo->GetBoundingBox ();
if ( pBoundingBox )
{
sphere.vecPosition = pBoundingBox->vecBoundOffset;
sphere.fRadius = pBoundingBox->fRadius;
}
}
sphere.vecPosition += GetStreamPosition ();
return sphere;
}
// Currently, this should only be called if the local player is, or was just in the vehicle
void CClientVehicle::HandleWaitingForGroundToLoad ( void )
{
// Check if near any MTA objects
bool bNearObject = false;
CVector vecPosition;
GetPosition ( vecPosition );
CClientEntityResult result;
GetClientSpatialDatabase ()->SphereQuery ( result, CSphere ( vecPosition + CVector ( 0, 0, -3 ), 5 ) );
for ( CClientEntityResult::const_iterator it = result.begin () ; it != result.end (); ++it )
{
if ( (*it)->GetType () == CCLIENTOBJECT )
{
bNearObject = true;
break;
}
}
if ( !bNearObject )
{
// If not near any MTA objects, then don't bother waiting
SetFrozenWaitingForGroundToLoad ( false, true );
#ifdef ASYNC_LOADING_DEBUG_OUTPUTA
OutputDebugLine ( "[AsyncLoading] FreezeUntilCollisionLoaded - Early stop" );
#endif
return;
}
// Reset position
CVector vecTemp;
m_pVehicle->SetMatrix ( &m_matFrozen );
m_pVehicle->SetMoveSpeed ( &vecTemp );
m_pVehicle->SetTurnSpeed ( &vecTemp );
m_vecMoveSpeedMeters = vecTemp;
m_vecMoveSpeed = vecTemp;
m_vecTurnSpeed = vecTemp;
// Load load load
if ( GetModelInfo () )
g_pGame->GetStreaming()->LoadAllRequestedModels ( false, "CClientVehicle::HandleWaitingForGroundToLoad" );
// Start out with a fairly big radius to check, and shrink it down over time
float fUseRadius = 50.0f * ( 1.f - Max ( 0.f, m_fObjectsAroundTolerance ) );
// Gather up some flags
CClientObjectManager* pObjectManager = g_pClientGame->GetObjectManager ();
bool bASync = g_pGame->IsASyncLoadingEnabled ();
bool bMTAObjLimit = pObjectManager->IsObjectLimitReached ();
bool bHasModel = GetModelInfo () != NULL;
#ifndef ASYNC_LOADING_DEBUG_OUTPUTA
bool bMTALoaded = pObjectManager->ObjectsAroundPointLoaded ( vecPosition, fUseRadius, m_usDimension );
#else
SString strAround;
bool bMTALoaded = pObjectManager->ObjectsAroundPointLoaded ( vecPosition, fUseRadius, m_usDimension, &strAround );
#endif
#ifdef ASYNC_LOADING_DEBUG_OUTPUTA
SString status = SString ( "%2.2f,%2.2f,%2.2f bASync:%d bHasModel:%d bMTALoaded:%d bMTAObjLimit:%d m_fGroundCheckTolerance:%2.2f m_fObjectsAroundTolerance:%2.2f fUseRadius:%2.1f"
,vecPosition.fX, vecPosition.fY, vecPosition.fZ
,bASync, bHasModel, bMTALoaded, bMTAObjLimit, m_fGroundCheckTolerance, m_fObjectsAroundTolerance, fUseRadius );
#endif
// See if ground is ready
if ( ( !bHasModel || !bMTALoaded ) && m_fObjectsAroundTolerance < 1.f )
{
m_fGroundCheckTolerance = 0.f;
m_fObjectsAroundTolerance = Min ( 1.f, m_fObjectsAroundTolerance + 0.01f );
#ifdef ASYNC_LOADING_DEBUG_OUTPUTA
status += ( " FreezeUntilCollisionLoaded - wait" );
#endif
}
else
{
// Models should be loaded, but sometimes the collision is still not ready
// Do a ground distance check to make sure.
// Make the check tolerance larger with each passing frame
m_fGroundCheckTolerance = Min ( 1.f, m_fGroundCheckTolerance + 0.01f );
float fDist = GetDistanceFromGround ();
float fUseDist = fDist * ( 1.f - m_fGroundCheckTolerance );
if ( fUseDist > -0.2f && fUseDist < 1.5f )
SetFrozenWaitingForGroundToLoad ( false, true );
#ifdef ASYNC_LOADING_DEBUG_OUTPUTA
status += ( SString ( " GetDistanceFromGround: fDist:%2.2f fUseDist:%2.2f", fDist, fUseDist ) );
#endif
// Stop waiting after 3 frames, if the object limit has not been reached. (bASync should always be false here)
if ( m_fGroundCheckTolerance > 0.03f /*&& !bMTAObjLimit*/ && !bASync )
SetFrozenWaitingForGroundToLoad ( false, true );
}
#ifdef ASYNC_LOADING_DEBUG_OUTPUTA
OutputDebugLine ( SStringX ( "[AsyncLoading] " ) + status );
g_pCore->GetGraphics ()->DrawText ( 10, 220, -1, 1, status );
std::vector < SString > lineList;
strAround.Split ( "\n", lineList );
for ( unsigned int i = 0 ; i < lineList.size () ; i++ )
g_pCore->GetGraphics ()->DrawText ( 10, 230 + i * 10, -1, 1, lineList[i] );
#endif
}
bool CClientVehicle::GiveVehicleSirens ( unsigned char ucSirenType, unsigned char ucSirenCount )
{
m_tSirenBeaconInfo.m_bOverrideSirens = true;
m_tSirenBeaconInfo.m_ucSirenType = ucSirenType;
m_tSirenBeaconInfo.m_ucSirenCount = ucSirenCount;
if ( m_pVehicle )
{
m_pVehicle->GiveVehicleSirens ( ucSirenType, ucSirenCount );
}
return true;
}
void CClientVehicle::SetVehicleSirenPosition ( unsigned char ucSirenID, CVector vecPos )
{
m_tSirenBeaconInfo.m_tSirenInfo[ucSirenID].m_vecSirenPositions = vecPos;
if ( m_pVehicle )
{
m_pVehicle->SetVehicleSirenPosition ( ucSirenID, vecPos );
}
}
void CClientVehicle::SetVehicleSirenMinimumAlpha( unsigned char ucSirenID, DWORD dwPercentage )
{
m_tSirenBeaconInfo.m_tSirenInfo[ucSirenID].m_dwMinSirenAlpha = dwPercentage;
if ( m_pVehicle )
{
m_pVehicle->SetVehicleSirenMinimumAlpha ( ucSirenID, dwPercentage );
}
}
void CClientVehicle::SetVehicleSirenColour ( unsigned char ucSirenID, SColor tVehicleSirenColour )
{
m_tSirenBeaconInfo.m_tSirenInfo[ucSirenID].m_RGBBeaconColour = tVehicleSirenColour;
if ( m_pVehicle )
{
m_pVehicle->SetVehicleSirenColour ( ucSirenID, tVehicleSirenColour );
}
}
void CClientVehicle::SetVehicleFlags ( bool bEnable360, bool bEnableRandomiser, bool bEnableLOSCheck, bool bEnableSilent )
{
m_tSirenBeaconInfo.m_b360Flag = bEnable360;
m_tSirenBeaconInfo.m_bDoLOSCheck = bEnableLOSCheck;
m_tSirenBeaconInfo.m_bUseRandomiser = bEnableRandomiser;
m_tSirenBeaconInfo.m_bSirenSilent = bEnableSilent;
if ( m_pVehicle )
{
m_pVehicle->SetVehicleFlags ( bEnable360, bEnableRandomiser, bEnableLOSCheck, bEnableSilent );
}
}
void CClientVehicle::RemoveVehicleSirens ( void )
{
if ( m_pVehicle )
{
m_pVehicle->RemoveVehicleSirens ( );
}
m_tSirenBeaconInfo.m_bOverrideSirens = false;
SetSirenOrAlarmActive ( false );
for ( unsigned char i = 0; i < 7; i++ )
{
SetVehicleSirenPosition( i, CVector ( 0, 0, 0 ) );
SetVehicleSirenMinimumAlpha( i, 0 );
SetVehicleSirenColour( i, SColor ( ) );
}
m_tSirenBeaconInfo.m_ucSirenCount = 0;
}
bool CClientVehicle::SetComponentPosition ( SString vehicleComponent, CVector vecPosition )
{
if ( m_pVehicle )
{
// set our position on the model
if ( m_pVehicle->SetComponentPosition ( vehicleComponent, vecPosition ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_vecComponentPosition = vecPosition;
m_ComponentData[vehicleComponent].m_bPositionChanged = true;
return true;
}
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_vecComponentPosition = vecPosition;
m_ComponentData[vehicleComponent].m_bPositionChanged = true;
return true;
}
}
return false;
}
bool CClientVehicle::GetComponentPosition ( SString vehicleComponent, CVector &vecPosition )
{
if ( m_pVehicle )
{
// fill our position from the actual position
return m_pVehicle->GetComponentPosition ( vehicleComponent, vecPosition );
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// fill our position from the cached position
vecPosition = m_ComponentData[vehicleComponent].m_vecComponentPosition;
return true;
}
}
return false;
}
bool CClientVehicle::SetComponentRotation ( SString vehicleComponent, CVector vecRotation )
{
if ( m_pVehicle )
{
// convert degrees to radians so users don't need to use radians
CVector vecTemp = vecRotation;
ConvertDegreesToRadians ( vecTemp );
// set our rotation on the model
if ( m_pVehicle->SetComponentRotation ( vehicleComponent, vecTemp ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_vecComponentRotation = vecRotation;
m_ComponentData[vehicleComponent].m_bRotationChanged = true;
return true;
}
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_vecComponentRotation = vecRotation;
m_ComponentData[vehicleComponent].m_bRotationChanged = true;
return true;
}
}
return false;
}
bool CClientVehicle::GetComponentRotation ( SString vehicleComponent, CVector &vecRotation )
{
if ( m_pVehicle )
{
// fill our rotation from the actual rotation
bool bResult = m_pVehicle->GetComponentRotation ( vehicleComponent, vecRotation );
// convert to degrees... none of our functions use radians.
ConvertRadiansToDegrees ( vecRotation );
return bResult;
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// fill our rotation from the cached rotation
vecRotation = m_ComponentData[vehicleComponent].m_vecComponentRotation;
return true;
}
}
return false;
}
bool CClientVehicle::ResetComponentRotation ( SString vehicleComponent )
{
// set our rotation on the model
if ( SetComponentRotation ( vehicleComponent, m_ComponentData[vehicleComponent].m_vecOriginalComponentRotation ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_bRotationChanged = false;
return true;
}
return false;
}
bool CClientVehicle::ResetComponentPosition ( SString vehicleComponent )
{
// set our position on the model
if ( SetComponentPosition ( vehicleComponent, m_ComponentData[vehicleComponent].m_vecOriginalComponentPosition ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_bPositionChanged = false;
return true;
}
return false;
}
bool CClientVehicle::SetComponentVisible ( SString vehicleComponent, bool bVisible )
{
// Check if wheel invisibility override is in operation due to setting of wheel states
if ( bVisible && GetWheelMissing( UCHAR_INVALID_INDEX, vehicleComponent ) )
bVisible = false;
if ( m_pVehicle )
{
if ( m_pVehicle->SetComponentVisible ( vehicleComponent, bVisible ) )
{
// update our cache
m_ComponentData[vehicleComponent].m_bVisible = bVisible;
// set our visibility on the model
m_pVehicle->SetComponentVisible ( vehicleComponent, bVisible );
return true;
}
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// store our visible variable to the cached data
m_ComponentData[vehicleComponent].m_bVisible = bVisible;
return true;
}
}
return false;
}
bool CClientVehicle::GetComponentVisible ( SString vehicleComponent, bool &bVisible )
{
if ( m_pVehicle )
{
// fill our visible variable from the actual position
return m_pVehicle->GetComponentVisible ( vehicleComponent, bVisible );
}
else
{
if ( m_ComponentData.find ( vehicleComponent ) != m_ComponentData.end ( ) )
{
// fill our visible variable from the cached data
bVisible = m_ComponentData[vehicleComponent].m_bVisible;
return true;
}
}
return false;
}
bool CClientVehicle::DoesSupportUpgrade ( SString strFrameName )
{
if ( m_pVehicle != NULL )
{
return m_pVehicle->DoesSupportUpgrade ( strFrameName );
}
return true;
}
bool CClientVehicle::OnVehicleFallThroughMap ( )
{
// if we have fallen through the map a small number of times
if ( m_ucFellThroughMapCount <= 2 )
{
// make sure we haven't moved much if at all
if ( IsFrozen ( ) == false &&
DistanceBetweenPoints2D ( m_matCreate.GetPosition ( ), m_Matrix.GetPosition ( ) ) < 3 )
{
// increase our fell through map count
m_ucFellThroughMapCount++;
// warp us to our initial position of creation
SetPosition ( m_matCreate.GetPosition ( ) );
// warp us to our initial position of creation
SetRotationRadians ( m_matCreate.GetRotation ( ) );
// handled
return true;
}
}
// unhandled
return false;
}
bool CClientVehicle::DoesNeedToWaitForGroundToLoad ( )
{
if ( !g_pGame->IsASyncLoadingEnabled ( ) )
return false;
// Let CClientPed handle it if our driver is the local player
if ( m_pDriver == g_pClientGame->GetLocalPlayer ( ) )
return false;
// If we're in water we won't need to wait for the ground to load
if ( m_LastSyncedData != NULL && m_LastSyncedData->bIsInWater == true )
return false;
// Check for MTA objects around our position
CVector vecPosition;
GetPosition ( vecPosition );
CClientObjectManager* pObjectManager = g_pClientGame->GetObjectManager ( );
return !pObjectManager->ObjectsAroundPointLoaded ( vecPosition, 50.0f, m_usDimension );
}
void CClientVehicle::SetNitroLevel ( float fNitroLevel )
{
if ( m_pVehicle )
{
m_pVehicle->SetNitroLevel ( fNitroLevel );
}
m_fNitroLevel = fNitroLevel;
}
float CClientVehicle::GetNitroLevel ( )
{
if ( m_pVehicle )
{
return m_pVehicle->GetNitroLevel ( );
}
return m_fNitroLevel;
}
void CClientVehicle::SetNitroCount ( char cNitroCount )
{
if ( m_pVehicle )
{
m_pVehicle->SetNitroCount ( cNitroCount );
}
m_cNitroCount = cNitroCount;
}
char CClientVehicle::GetNitroCount ( )
{
if ( m_pVehicle )
{
return m_pVehicle->GetNitroCount ( );
}
return m_cNitroCount;
}
| gpl-3.0 |
ChrisLynch42/RLiferayTool | lib/r_liferay_lib/read_service.rb | 1588 | require_relative 'column'
require_relative 'xml_utility'
module RLiferayLib
class ReadService
attr_reader :service_xml_file, :entities
def initialize(service_xml_file)
self.service_xml_file=service_xml_file
self.entities = Hash.new()
read_xml
end
private
attr_writer :service_xml_file, :entities
def read_xml
xml_utility = XMLUtility.new(self.service_xml_file)
entity_nodes = xml_utility.xml_content.xpath('/service-builder/entity')
entity_nodes.each { | entity_node |
entity_name = entity_node.attr('name')
self.entities[entity_name] = Hash.new()
self.entities[entity_name]['name'] = entity_name
self.entities[entity_name]['primary_key'] = ''
self.entities[entity_name]['columns'] = Hash.new()
read_columns(entity_name, entity_node)
}
end
def read_columns(entity_name, entity_node)
column_nodes = entity_node.xpath('./column')
column_nodes.each { | column_node|
column_name = column_node.attr('name')
if column_node.attr("primary") == 'true'
self.entities[entity_name]['primary_key'] = column_name
elsif !IGNORE_COLUMNS.include?(column_name)
self.entities[entity_name]['columns'][column_name] = Column.new(column_name, column_node.attr('type'))
end
}
end
IGNORE_COLUMNS = {
'groupId' => 'long',
'companyId' => 'long',
'userId' => 'long',
'userName' => 'String',
'createDate' => 'Date',
'modifiedDate' => 'Date'
}
end
end | gpl-3.0 |
erapetti/Formularios | api/controllers/Mis_cargosController.js | 855 | /**
* Mis_CargosController
*
* @description :: Server-side logic for managing mis_cargos
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
load: function(param,resolve,reject) {
var ahora = new Date();
DenominacionesCargos.misCargos(param.config.ci,ahora.fecha_ymd_toString(),'2099-01-01',function(err,cargos) {
if (err) {
return reject(err);
} else {
param.m.options = Array();
cargos.forEach(function(cargo){
if (cargo.TipoCargoId > 1) {
param.m.options.push(cargo);
}
});
return resolve(undefined);
}
});
},
modedit: function() {
return {nombre:"cargo", etiqueta:"Cargo", texto1:undefined, texto2:undefined, ayuda:"Texto que se muestra a la derecha", validador:"novacio", opcional:"on"};
},
};
| gpl-3.0 |
amba178/MetPlus_PETS | spec/controllers/company_people_controller_spec.rb | 90 | require 'rails_helper'
RSpec.describe CompanyPeopleController, type: :controller do
end
| gpl-3.0 |
Duceux/Arty | include/arty/core/number.hpp | 2868 | #ifndef NUMBER_HPP
#define NUMBER_HPP
#include <cassert>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <limits>
#include <string>
#include <utility>
namespace arty {
namespace details {
constexpr int64_t INTMAX = std::numeric_limits<int64_t>::max();
constexpr int64_t INTMIN = std::numeric_limits<int64_t>::min();
bool addIsSafe(int64_t a, int64_t b);
bool subIsSafe(int64_t a, int64_t b);
bool multIsSafe(int64_t a, int64_t b);
int64_t gcd(int64_t l, int64_t r);
} // namespace details
class number {
public:
// CONSTRUCTORS
number() : number(0) {}
number(int i) : _den(i), _num(1) {}
number(float f) : number(static_cast<double>(f)) {}
number(double d) : number(static_cast<int64_t>(d * 1000000.), 1000000) {}
number(int64_t dec, int64_t num) : _den(dec), _num(num) { reduce(); }
// CAST
explicit operator double() const;
explicit operator float() const;
explicit operator int() const;
explicit operator std::string() const;
// COMPARISONS
bool operator==(number const& o) const;
bool operator<(number const& o) const;
bool operator>(number const& o) const;
bool operator>=(number const& o) const;
bool operator<=(number const& o) const;
bool operator!=(number const& o) const;
// OPERATORS
number operator-() const;
number& operator+=(number const& other);
number& operator-=(number const& other);
number& operator*=(number const& other);
number& operator/=(number const& other);
// INCR
number& operator++();
number operator++(int);
number& operator--();
number operator--(int);
// IRR
static number sqrt(number const& num, number const& prec);
static number sqr(number const& n);
static number pow(number const& b, number const& p, number const& pre);
static number pow(number const& b, uint16_t p);
bool isInt() const;
bool isInf() const;
bool isDec() const;
static number inf();
static number max();
static number min();
static number eps();
static number und();
private:
void reduce();
void reducePrecision();
std::pair<int64_t, number> split() const;
friend std::ostream& operator<<(std::ostream& os, number const& n) {
return os << static_cast<std::string>(n);
}
private:
int64_t _den;
int64_t _num;
};
// OPERATORS
inline const number operator+(number l, number const& r) {
l += r;
return l;
}
inline const number operator-(number l, number const& r) {
l -= r;
return l;
}
inline const number operator*(number l, number const& r) {
l *= r;
return l;
}
inline const number operator/(number l, number const& r) {
l /= r;
return l;
}
constexpr double PI = 3.14159265358979323846;
static inline number sqrt(number const& n) { return number::sqrt(n, 4); }
static inline number pow(number const& n, number const& p) {
return number::pow(n, p, 1);
}
} // namespace arty
#endif // NUMBER_HPP
| gpl-3.0 |
VaccinalBowl/distributed_ticket_booking_system | src/CampServerConnectionThread.java | 1452 | import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
@SuppressWarnings("unused")
public class CampServerConnectionThread implements Runnable {
private Socket connection;
private ObjectInputStream inputStream;
public CampServerConnectionThread(Socket socket){
this.connection=socket;
}
public void run() {
// TODO Auto-generated method stub
try {
//this.outputStream = new ObjectOutputStream( this.connection.getOutputStream());
this.inputStream = new ObjectInputStream(this.connection.getInputStream());
Packet packet = (Packet)this.inputStream.readObject();
if(packet.getPacketType().equals("BookingConfirmationPacket")){
System.out.println(packet.toString());
}else if(packet.getPacketType().equals("CancelationConfirmationPacket")){
System.out.println("Successfully Cancelled Booking"+ packet.getReservationNumber());
}else if(packet.getPacketType().equals("CancelationFailurePacket")){
System.out.println("Could not cancel that booking. Are you sure it was entered correctly?");
}else {
System.out.println("No avalilable flights with any company. Try a different day");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| gpl-3.0 |
Lizzaran/LeagueSharp-Standalones | SFXChallenger/SFXCassiopeia/Library/Extensions/NET/OtherExtensions.cs | 3486 | #region License
/*
Copyright 2014 - 2015 Nikita Bernthaler
OtherExtensions.cs is part of SFXCassiopeia.
SFXCassiopeia 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.
SFXCassiopeia 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 SFXCassiopeia. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion License
#region
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using LeagueSharp;
using SharpDX.Direct3D9;
#endregion
namespace SFXCassiopeia.Library.Extensions.NET
{
public static class OtherExtensions
{
public static bool Is24Hrs(this CultureInfo cultureInfo)
{
return cultureInfo.DateTimeFormat.ShortTimePattern.Contains("H");
}
public static bool IsNumber(this object value)
{
return value is sbyte || value is byte || value is short || value is ushort || value is int || value is uint ||
value is long || value is ulong || value is float || value is double || value is decimal;
}
public static Task<List<T>> ToListAsync<T>(this IQueryable<T> list)
{
return Task.Run(() => list.ToList());
}
/// <exception cref="Exception">A delegate callback throws an exception. </exception>
public static void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
if (@event != null)
{
@event(sender, e);
}
}
/// <exception cref="Exception">A delegate callback throws an exception. </exception>
public static void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e) where T : EventArgs
{
if (@event != null)
{
@event(sender, e);
}
}
public static Texture ToTexture(this Bitmap bitmap)
{
return Texture.FromMemory(
Drawing.Direct3DDevice, (byte[]) new ImageConverter().ConvertTo(bitmap, typeof(byte[])), bitmap.Width,
bitmap.Height, 0, Usage.None, Format.A1, Pool.Managed, Filter.Default, Filter.Default, 0);
}
/// <exception cref="Exception">The operation failed.</exception>
public static Bitmap Scale(this Bitmap bitmap, float scale)
{
var scaled = new Bitmap((int) Math.Ceiling(bitmap.Width * scale), (int) Math.Ceiling(bitmap.Height * scale));
using (var graphics = Graphics.FromImage(scaled))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(bitmap, new Rectangle(0, 0, scaled.Width, scaled.Height));
}
return scaled;
}
}
} | gpl-3.0 |
gklimek/philippides | src/main/java/org/philippides/layer/AmqpLayer.java | 2438 | package org.philippides.layer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.philippides.IBrokerContext;
import org.philippides.Layer;
import org.philippides.endpoint.ChannelSender;
import org.philippides.endpoint.Connection;
import org.philippides.frame.Content;
import org.philippides.frame.Frame;
import org.philippides.frame.Reader;
import org.philippides.util.Streams;
public class AmqpLayer implements Layer {
private static final Logger LOG = Logger.getLogger(AmqpLayer.class.getName());
private Connection connection;
private IBrokerContext brokerContext;
public AmqpLayer(IBrokerContext brokerContext) {
this.brokerContext = brokerContext;
this.connection = new Connection(this.brokerContext);
}
@Override
public boolean isDone() {
return connection.isDone();
}
@Override
public void onFrame(Frame frame) throws IOException {
Content content = new Reader().read(frame);
int channel = frame.getChannel();
connection.onContent(channel, content);
}
@Override
public boolean expectFrame() {
return connection.expectInput();
}
@Override
public List<Frame> toSend() {
List<Frame> toSend = new ArrayList<>();
connection.send(new ChannelSender() {
@Override
public void send(int remoteChannel, Content content) {
ByteArrayOutputStream frameBytes = new ByteArrayOutputStream();
try {
content.getPerformative().write(frameBytes);
if (null != content.getPayloadStream()) {
Streams.copyStream(content.getPayloadStream(), frameBytes);
}
} catch (IOException e) {
throw new IllegalStateException("Unexpected exception on wrote to bytes buffer", e);
}
byte[] bytes = frameBytes.toByteArray();
Frame frame = Frame.fromBytes(new byte[0], bytes, org.philippides.frame.Type.AMQP, remoteChannel);
toSend.add(frame);
LOG.info("Sending to channel " + remoteChannel + ": " + content);
}
});
return toSend;
}
@Override
public boolean innerLayersExpected() {
return false;
}
}
| gpl-3.0 |
magicxor/Hikkaba | Hikkaba.Models/Dto/Ban/BanEditDto.cs | 546 | using TPrimaryKey = System.Guid;
using System;
using Hikkaba.Models.Dto.Base.Current;
namespace Hikkaba.Models.Dto
{
public class BanEditDto: IBaseDto
{
public TPrimaryKey Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string LowerIpAddress { get; set; }
public string UpperIpAddress { get; set; }
public string Reason { get; set; }
public PostDto RelatedPost { get; set; }
public CategoryDto Category { get; set; }
}
} | gpl-3.0 |
HeuristNetwork/heurist | redirects/getDatabaseURL_V1.php | 1134 | <?php
/**
*
* getDatabaseURL_V1.php
* redirector to getDatabaseURL.php to provide a stable URL in case of restructuring of the codebase
*
* @package Heurist academic knowledge management system
* @link http://HeuristNetwork.org
* @copyright (C) 2005-2020 University of Sydney
* @author Artem Osmakov <artem.osmakov@sydney.edu.au>
* @author Ian Johnson <ian.johnson@sydney.edu.au>
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @version 4
*/
/*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.txt
* 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.
*/
header('Location: ../admin/setup/dbproperties/getDatabaseURL.php?'.$_SERVER['QUERY_STRING']);
exit();
?>
| gpl-3.0 |
Jmgr/actiona | actions/windows/src/code/messagebox.cpp | 4919 | /*
Actiona
Copyright (C) 2005 Jonathan Mercier-Ganady
Actiona 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.
Actiona 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/>.
Contact: jmgr@jmgr.info
*/
#include "messagebox.hpp"
#include "actiontools/code/image.hpp"
#include <QScriptValueIterator>
#include <QPushButton>
namespace Code
{
QScriptValue MessageBox::constructor(QScriptContext *context, QScriptEngine *engine)
{
auto messageBox = new MessageBox;
messageBox->setupConstructorParameters(context, engine, context->argument(0));
QScriptValueIterator it(context->argument(0));
while(it.hasNext())
{
it.next();
if(it.name() == QLatin1String("text"))
messageBox->mMessageBox->setText(it.value().toString());
else if(it.name() == QLatin1String("detailedText"))
messageBox->mMessageBox->setDetailedText(it.value().toString());
else if(it.name() == QLatin1String("informativeText"))
messageBox->mMessageBox->setInformativeText(it.value().toString());
else if(it.name() == QLatin1String("buttons"))
messageBox->mMessageBox->setStandardButtons(static_cast<QMessageBox::StandardButton>(it.value().toInt32()));
else if(it.name() == QLatin1String("icon"))
messageBox->mMessageBox->setIcon(static_cast<QMessageBox::Icon>(it.value().toInt32()));
else if(it.name() == QLatin1String("defaultButton"))
messageBox->mMessageBox->setDefaultButton(static_cast<QMessageBox::StandardButton>(it.value().toInt32()));
else if(it.name() == QLatin1String("escapeButton"))
messageBox->mMessageBox->setEscapeButton(static_cast<QMessageBox::StandardButton>(it.value().toInt32()));
else if(it.name() == QLatin1String("onClosed"))
messageBox->mOnClosed = it.value();
}
return CodeClass::constructor(messageBox, context, engine);
}
MessageBox::MessageBox()
: BaseWindow(),
mMessageBox(new QMessageBox)
{
mMessageBox->setWindowFlags(mMessageBox->windowFlags() | Qt::WindowContextHelpButtonHint);
setWidget(mMessageBox);
connect(mMessageBox, &QMessageBox::finished, this, &MessageBox::finished);
}
MessageBox::~MessageBox()
{
delete mMessageBox;
}
QScriptValue MessageBox::setText(const QString &text)
{
mMessageBox->setText(text);
return thisObject();
}
QScriptValue MessageBox::setDetailedText(const QString &detailedText)
{
mMessageBox->setDetailedText(detailedText);
return thisObject();
}
QScriptValue MessageBox::setInformativeText(const QString &informativeText)
{
mMessageBox->setInformativeText(informativeText);
return thisObject();
}
QScriptValue MessageBox::setButtons(StandardButton buttons)
{
mMessageBox->setStandardButtons(static_cast<QMessageBox::StandardButton>(buttons));
return thisObject();
}
QScriptValue MessageBox::setIcon(Icon icon)
{
mMessageBox->setIcon(static_cast<QMessageBox::Icon>(icon));
return thisObject();
}
QScriptValue MessageBox::setIconPixmap(const QScriptValue &image)
{
if(image.isUndefined() || image.isNull())
{
mMessageBox->setIconPixmap(QPixmap());
return thisObject();
}
QObject *object = image.toQObject();
if(auto otherImage = qobject_cast<Image*>(object))
{
mMessageBox->setIconPixmap(QPixmap::fromImage(otherImage->image()));
}
else
{
throwError(QStringLiteral("SetIconPixmapError"), tr("Invalid image"));
return thisObject();
}
return thisObject();
}
QScriptValue MessageBox::setDefaultButton(StandardButton button)
{
mMessageBox->setDefaultButton(static_cast<QMessageBox::StandardButton>(button));
return thisObject();
}
QScriptValue MessageBox::setEscapeButton(StandardButton button)
{
mMessageBox->setEscapeButton(static_cast<QMessageBox::StandardButton>(button));
return thisObject();
}
QScriptValue MessageBox::addCustomButton(StandardButton button, const QString &text)
{
QPushButton *addedButton = mMessageBox->addButton(static_cast<QMessageBox::StandardButton>(button));
if(!addedButton)
{
throwError(QStringLiteral("AddCustomButtonError"), tr("Add custom button failed"));
return thisObject();
}
addedButton->setText(text);
return thisObject();
}
QScriptValue MessageBox::show()
{
mMessageBox->open();
return thisObject();
}
int MessageBox::showModal()
{
return mMessageBox->exec();
}
void MessageBox::finished(int result)
{
if(mOnClosed.isValid())
mOnClosed.call(thisObject(), QScriptValueList() << result);
}
}
| gpl-3.0 |
bunkatu/GGJ16 | core/src/network/lobby/UserLeftLobby.java | 105 | package network.lobby;
public class UserLeftLobby {
public int lobby_id;
public String username;
}
| gpl-3.0 |