repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
andrassebo/mdicontainer | MDIContainer/MDIContainer.DemoClient/Entities/Person.cs | 1503 | namespace MDIContainer.DemoClient.Entities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MDIContainer.DemoClient.Bases;
public class Person : ViewModelBase
{
public event EventHandler Changed;
public Person(string name, DateTime birthDate, string address)
{
this.Name = name;
this.BirthDate = birthDate;
this.Address = address;
}
private string _name = string.Empty;
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
this.RaisePropertyChanged("Name");
}
}
private DateTime _birthDate;
public DateTime BirthDate
{
get
{
return this._birthDate;
}
set
{
this._birthDate = value;
this.RaisePropertyChanged("BirthDate");
}
}
private string _address = string.Empty;
public string Address
{
get
{
return this._address;
}
set
{
this._address = value;
this.RaisePropertyChanged("Address");
}
}
protected override void OnPropertyChanged(string propertyName)
{
var hander = this.Changed;
if (hander != null)
{
hander(this, EventArgs.Empty);
}
}
}
}
| gpl-3.0 |
w35l3y/userscripts | backup/wontfix/page2/131890.user.js | 3983 | // ==UserScript==
// @name Userscripts : Auto-Flag Spam Topics
// @namespace http://gm.wesley.eti.br
// @description Auto-flag spam topics at the forums
// @author w35l3y
// @email w35l3y@brasnet.org
// @copyright 2012+, w35l3y (http://gm.wesley.eti.br)
// @license GNU GPL
// @homepage http://gm.wesley.eti.br
// @version 1.0.0.7
// @language en
// @include http://userscripts-mirror.org/forums/*
// @grant GM_xmlhttpRequest
// @icon http://gm.wesley.eti.br/icon.php?desc=131890
// @require https://github.com/w35l3y/userscripts/raw/master/includes/Includes_XPath/63808.user.js
// @require https://github.com/w35l3y/userscripts/raw/master/includes/Includes_HttpRequest/56489.user.js
// ==/UserScript==
/**************************************************************************
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/>.
**************************************************************************/
(function recursive (topics) {
if (topics.length) {
var topic = topics.shift();
if (/^(?:[A-Z][a-z]+){2}/.test(topic.textContent) // title
&& "0" == xpath("string(./ancestor::tr[1]/td[3]/text())", topic) // number of replies
&& /[a-z]{2,}\d*[a-z]?$/.test(xpath("string(./ancestor::tr[1][td[2]/small/a[1]/text() = td[5]/small/a[1]/text()]/td[2]/small/a[1]/text())", topic)) // username
&& /#posts-(\d+)/.test(xpath("string(./ancestor::tr[1]/td[5]/small/a[2]/@href)", topic)) // post id
) {
var pid = RegExp.$1;
HttpRequest.open({
method : "post",
url : "http://userscripts-mirror.org/spam",
headers : {
"Referer" : topic.parentNode.href,
},
onsuccess : function (xhr) {
xpath("./ancestor::tr[1]/td[1]/img/@class", topic)[0].value = "icon grey";
var msg = xpath("string(id('post-body-" + pid + "'))", xhr.response.xml).replace(/^\s+|\s+$/g, ""),
notice = xpath("id('content')/p[@class = 'notice']", xhr.response.xml)[0],
content = xpath("id('content')")[0];
if (notice) {
content.replaceChild(notice, content.firstChild); // it works because the first child is a TextNode
}
if (!msg || /(?:[A-Z][a-z]+){4}/.test(msg)) {
window.setTimeout(recursive, 500, topics);
} else { // ops, the content message doesn't seem to be spam
HttpRequest.open({
method : "post",
url : "http://userscripts-mirror.org/spam",
headers : {
"Referer" : topic.parentNode.href,
},
onsuccess : function (xhr) {
window.setTimeout(recursive, 500, topics);
notice = xpath("id('content')/p[@class = 'notice']", xhr.response.xml)[0];
if (notice) {
content.replaceChild(notice, content.firstChild); // it works because the first child is a TextNode
}
},
}).send({
"authenticity_token" : unsafeWindow.auth_token,
"post_id" : pid,
"spam" : "false",
"commit" : "Disagree",
});
}
},
}).send({
"authenticity_token" : unsafeWindow.auth_token,
"post_id" : pid,
"spam" : "true",
"commit" : "Flag Spam",
});
} else { // next topic
recursive(topics);
}
} else {
window.setTimeout("location.reload()", 150000); // 02m30s
}
}(xpath("id('content')//tr[td[1]/img[@class = 'icon green']]/td[2]/a/text()")));
| gpl-3.0 |
PragTob/cloud9 | plugins-client/ext.filesystem/filesystem.js | 20188 | /**
* File System Module for the Cloud9 IDE
*
* @copyright 2010, Ajax.org B.V.
* @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
*/
define(function(require, exports, module) {
var ide = require("core/ide");
var ext = require("core/ext");
var util = require("core/util");
var commands = require("ext/commands/commands");
var editors = require("ext/editors/editors");
require("ext/main/main"); //Make sure apf is inited.
module.exports = ext.register("ext/filesystem/filesystem", {
name : "File System",
dev : "Ajax.org",
type : ext.GENERAL,
alone : true,
deps : [],
createFileNodeFromPath : function (path, attributes) {
var name = path.split("/").pop();
var node = apf.n("<file />")
.attr("name", name)
.attr("contenttype", util.getContentType(name))
.attr("type", "file")
.attr("path", path);
if (attributes !== undefined) {
for (var a in attributes) {
if (a.indexOf("date") >= 0)
attributes[a] = new Date(attributes[a]);
node.attr(a, attributes[a]);
}
}
return node.node();
},
createFolderNodeFromPath : function (path, attributes) {
var name = path.split("/").pop();
var node = apf.n("<folder />")
.attr("name", name)
.attr("path", path)
.attr("type", "folder");
if (attributes !== undefined) {
for (var a in attributes) {
if (a.indexOf("date") >= 0)
attributes[a] = new Date(attributes[a]);
node.attr(a, attributes[a]);
}
}
return node.node();
},
readFile : function (path, callback){
if (!this.webdav) return;
var self = this;
// in webdav.read, if ide.onLine === 0, it is calling callback immediately without content
// if we're not online, we'll add an event handler that listens to the socket connecting (or the ping or so)
if (!ide.onLine) {
var afterOnlineHandler = function () {
self.webdav.read(path, callback);
ide.removeEventListener("afteronline", afterOnlineHandler);
};
ide.addEventListener("afteronline", afterOnlineHandler);
}
else {
// otherwise just redirect it
this.webdav.read(path, callback);
}
},
saveFile : function(path, data, callback) {
if (!this.webdav)
return;
this.webdav.write(path, data, null, function(data, state, extra) {
if ((state == apf.ERROR && extra.status == 400 && extra.retries < 3) || state == apf.TIMEOUT)
return extra.tpModule.retry(extra.id);
callback(data, state, extra);
});
},
list : function(path, callback) {
if (this.webdav)
this.webdav.list(path, callback);
},
exists : function(path, callback) {
if (this.webdav)
this.webdav.exists(path, callback);
},
createFolder: function(name, tree, noRename, callback) {
if (!tree) {
tree = apf.document.activeElement;
if (!tree || tree.localName != "tree")
tree = trFiles;
}
var node = tree.selected;
if (!node && tree.xmlRoot)
node = tree.xmlRoot.selectSingleNode("folder");
if (!node)
return callback && callback();
if (node.getAttribute("type") != "folder" && node.tagName != "folder")
node = node.parentNode;
if (this.webdav) {
var prefix = name ? name : "New Folder";
var path = node.getAttribute("path");
if (!path) {
path = ide.davPrefix;
node.setAttribute("path", path);
}
var _self = this,
index = 0;
function test(exists) {
if (exists) {
name = prefix + "." + index++;
_self.exists(path + "/" + name, test);
} else {
tree.focus();
_self.webdav.exec("mkdir", [path, name], function(data) {
// @todo: in case of error, show nice alert dialog
if (!data || data instanceof Error) {
callback && callback();
throw Error;
}
// parse xml
var nodesInDirXml = apf.getXml(data);
// we expect the new created file in the directory listing
var fullFolderPath = path + "/" + name;
var folder = nodesInDirXml.selectSingleNode("//folder[@path='" + fullFolderPath + "']");
// not found? display an error
if (!folder) {
util.alert("Error", "Folder '" + name + "' could not be created",
"An error occurred while creating a new folder, please try again.");
callback && callback();
return;
}
tree.slideOpen(null, node, true, function(data, flag, extra){
// empty data means it didn't trigger <insert> binding,
// therefore the node was expanded already
if (!data)
tree.add(folder, node);
folder = apf.queryNode(node, "folder[@path='"+ fullFolderPath +"']");
tree.select(folder);
if (!noRename)
tree.startRename();
callback && callback(folder);
});
});
}
}
name = prefix;
this.exists(path + "/" + name, test);
}
},
createFile: function(filename, newFile) {
var node;
if (!newFile) {
node = trFiles.selected;
if (!node)
node = trFiles.xmlRoot.selectSingleNode("folder");
if (node.getAttribute("type") != "folder" && node.tagName != "folder")
node = node.parentNode;
}
else {
node = apf.getXml('<file newfile="1" type="file" size="" changed="1" '
+ 'name="Untitled.txt" contenttype="text/plain; charset=utf-8" '
+ 'modifieddate="" creationdate="" lockable="false" hidden="false" '
+ 'executable="false"></file>');
}
if (this.webdav) {
var prefix = filename ? filename : "Untitled";
if(!newFile)
trFiles.focus();
var _self = this,
path = node.getAttribute("path");
if (!path) {
path = ide.davPrefix;
node.setAttribute("path", path);
}
var index = 0;
var test = function(exists) {
if (exists) {
filename = prefix + "." + index++;
_self.exists(path + "/" + filename, test);
}
else {
if (!newFile) {
var file
var both = 0;
function done(){
if (both == 2) {
file = apf.xmldb.appendChild(node, file);
trFiles.select(file);
trFiles.startRename();
trFiles.slideOpen(null, node, true);
}
}
trFiles.slideOpen(null, node, true, function(){
both++;
done();
});
_self.webdav.exec("create", [path, filename], function(data) {
_self.webdav.exec("readdir", [path], function(data) {
if (!data || data instanceof Error) {
// @todo: should we display the error message in the Error object too?
return util.alert("Error", "File '" + filename + "' could not be created",
"An error occurred while creating a new file, please try again.");
}
// parse xml
var filesInDirXml = apf.getXml(data);
// we expect the new created file in the directory listing
var fullFilePath = path + "/" + filename;
var nodes = filesInDirXml.selectNodes("//file[@path='" + fullFilePath + "']");
// not found? display an error
if (nodes.length === 0) {
return util.alert("Error", "File '" + filename + "' could not be created",
"An error occurred while creating a new file, please try again.");
}
file = nodes[0];
both++;
done();
});
});
}
else {
node.setAttribute("name", filename);
node.setAttribute("path", path + "/" + filename);
editors.gotoDocument({doc: ide.createDocument(node), type:"newfile"});
}
}
};
filename = prefix;
this.exists(path + "/" + filename, test);
}
},
beforeStopRename : function(name) {
// Returning false from this function will cancel the rename. We do this
// when the name to which the file is to be renamed contains invalid
// characters
var match = name.match(/^(?:\w|[.])(?:\w|[.-])*$/);
return match !== null && match[0] == name;
},
beforeRename : function(node, name, newPath, isCopyAction, isReplaceAction) {
var path = node.getAttribute("path");
var page = tabEditors.getPage(path);
if (name)
newPath = path.replace(/^(.*\/)[^\/]+$/, "$1" + name);
else
name = newPath.match(/[^\/]+$/);
node.setAttribute("oldpath", node.getAttribute("path"));
node.setAttribute("path", newPath);
if (isCopyAction || node.getAttribute('name') != name)
apf.xmldb.setAttribute(node, "name", name);
// when this is a copy action, then we don't want this to happen
if (page && !isCopyAction)
page.setAttribute("id", newPath);
var childNodes = node.childNodes;
var length = childNodes.length;
for (var i = 0; i < length; ++i) {
var childNode = childNodes[i];
if(!childNode || childNode.nodeType != 1)
continue;
// The 'name' variable is redeclared here for some fucked up reason.
// The problem is that we are reusing that variable below. If the author
// of this would be so kind to fix this code as soon as he sees this
// comment, I would be eternally grateful. Sergi.
var name = childNode.getAttribute("name");
this.beforeRename(childNode, null, node.getAttribute("path") + "/" + name);
}
ide.dispatchEvent("updatefile", {
path: path,
newPath: newPath,
filename: name && name[0],
xmlNode: node,
replace: isReplaceAction
});
},
beforeMove: function(parent, node, tree) {
var path = node.getAttribute("path");
var page = tabEditors.getPage(path);
var newpath = parent.getAttribute("path") + "/" + node.getAttribute("name");
node.setAttribute("path", newpath);
if (page)
page.setAttribute("id", newpath);
var childNodes = node.childNodes;
var length = childNodes.length;
for (var i = 0; i < length; ++i) {
this.beforeMove(node, childNodes[i]);
}
ide.dispatchEvent("updatefile", {
path: path,
xmlNode: node
});
return true;
},
remove: function(path, callback) {
var page = tabEditors.getPage(path);
if (page)
tabEditors.remove(page);
var cb = function(data, state, extra) {
// In WebDAV, a 204 status from the DELETE verb means that the
// file was removed successfully.
if (extra && extra.status && extra.status === 204) {
ide.dispatchEvent("removefile", {
path: path
});
}
if (callback)
callback(data, state, extra);
};
davProject.remove(path, false, cb);
},
/**** Init ****/
init : function() {
commands.addCommand({
name : "open",
hint: "open a file to edit in a new tab",
commands: {
"[PATH]": {"hint": "path pointing to a file. Autocomplete with [TAB]"}
}
});
commands.addCommand({
name: "c9",
hint: "alias for 'open'",
commands: {
"[PATH]": {"hint": "path pointing to a file. Autocomplete with [TAB]"}
}
});
this.model = new apf.model();
this.model.load("<data><folder type='folder' name='" + ide.projectName +
"' path='" + ide.davPrefix + "' root='1'/></data>");
this.model.setAttribute("whitespace", false);
var dav_url = location.href.replace(location.pathname + location.hash, "") + ide.davPrefix;
this.webdav = apf.document.documentElement.appendChild(new apf.webdav({
id : "davProject",
url : dav_url,
onauthfailure: function() {
ide.dispatchEvent("authrequired");
}
}));
function openHandler(e) {
ide.send({
command: "internal-isfile",
argv: e.data.argv,
cwd: e.data.cwd,
sender: "filesystem",
extra: e.data.extra
});
return false;
}
ide.addEventListener("consolecommand.open", openHandler);
ide.addEventListener("consolecommand.c9", openHandler);
var fs = this;
ide.addEventListener("openfile", function(e){
var doc = e.doc;
var node = doc.getNode();
var editor = e.doc.$page && e.doc.$page.$editor;
// This make the tab animation nicer.
function dispatchAfterOpenFile(){
setTimeout(function(){
ide.dispatchEvent("afteropenfile", {doc: doc, node: node, editor: editor});
}, 150);
}
apf.xmldb.setAttribute(node, "loading", "true");
ide.addEventListener("afteropenfile", function(e) {
if (e.node == node) {
apf.xmldb.removeAttribute(e.node, "loading");
ide.removeEventListener("afteropenfile", arguments.callee);
}
});
if (doc.hasValue()) {
dispatchAfterOpenFile();
return;
}
// do we have a value in cache, then use that one
if (doc.cachedValue) {
doc.setValue(doc.cachedValue);
delete doc.cachedValue;
dispatchAfterOpenFile();
}
// if we're creating a new file then we'll fill the doc with nah dah
else if ((e.type && e.type === "newfile") || Number(node.getAttribute("newfile") || 0) === 1) {
doc.setValue("");
dispatchAfterOpenFile();
}
// otherwise go on loading
else {
// add a way to hook into loading of files
if (ide.dispatchEvent("readfile", {doc: doc, node: node}) === false)
return;
var path = node.getAttribute("path");
/**
* Callback function after we retrieve response from jsdav
*/
var readfileCallback = function(data, state, extra) {
// verify if the request succeeded
if (state != apf.SUCCESS) {
// 404's should give a file not found, but what about others?
// for clarity we'll console.log some info; so it'll help us debug it
// in case it would happen actually
if (extra.status !== 404) {
console.log("Opening file failed for", path, "server responded with", state, extra);
}
// now invoke filenotfound every time
// because we can't be sure about the state so force a close of the file tab
// this will prevent things like empty files, etc.
ide.dispatchEvent("filenotfound", {
node : node,
url : extra.url,
path : path
});
}
else {
//doc.addEventListener("editor.ready", function(){
// populate the document
doc.setValue(data);
// fire event
dispatchAfterOpenFile();
//});
}
};
// offline / online detection has been moved into fs.readFile instead
fs.readFile(path, readfileCallback);
}
});
ide.addEventListener("reload", function(e) {
var doc = e.doc,
node = doc.getNode(),
path = node.getAttribute("path");
/**
* This callback is executed when the file is read, we need to check
* the current state of online/offline
*/
var readfileCallback = function(data, state, extra) {
if (state == apf.OFFLINE) {
ide.addEventListener("afteronline", function(e) {
fs.readFile(path, readfileCallback);
ide.removeEventListener("afteronline", arguments.callee);
});
} else if (state != apf.SUCCESS) {
if (extra.status == 404)
ide.dispatchEvent("filenotfound", {
node : node,
url : extra.url,
path : path
});
} else {
ide.dispatchEvent("afterreload", {doc : doc, data : data});
}
};
fs.readFile(path, readfileCallback);
});
},
enable : function() {},
disable : function() {},
destroy : function(){
commands.removeCommandsByName(["open", "c9"]);
this.webdav.destroy(true, true);
this.model.destroy(true, true);
}
});
});
| gpl-3.0 |
hornetmj/CUBRID-MySQL-adapter-testcase | unit/cubrid_cci/cci_set_make.cc | 575 | #include <cas_cci.h>
#include "gtest/gtest.h"
class CCI_Set_Make : public ::testing::Test {
protected:
int conn_handle;
T_CCI_ERROR err_buf;
T_CCI_SET setval;
int ret;
virtual void SetUp () {
}
virtual void TearDown () {
}
};
TEST_F(CCI_Set_Make, Basic) {
float set_val[3] = {100.0, 200.0, 300.0};
int ind[3] = {0, 0, 0};
ret = cci_set_make (&setval,
CCI_U_TYPE_FLOAT,
sizeof (set_val) / sizeof (float),
set_val,
ind);
EXPECT_EQ(0, ret);
}
| gpl-3.0 |
devcode-it/openstamanager | modules/pagamenti/ajax/select.php | 2525 | <?php
/*
* OpenSTAManager: il software gestionale open source per l'assistenza tecnica e la fatturazione
* Copyright (C) DevCode s.r.l.
*
* 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 <https://www.gnu.org/licenses/>.
*/
include_once __DIR__.'/../../../core.php';
switch ($resource) {
/*
* Opzioni utilizzate:
* - codice_modalita_pagamento_fe
*/
case 'pagamenti':
// Filtri per banche dell'Azienda
$id_azienda = setting('Azienda predefinita');
$query = "SELECT co_pagamenti.id,
CONCAT_WS(' - ', codice_modalita_pagamento_fe, descrizione) AS descrizione,
banca_vendite.id AS id_banca_vendite,
CONCAT(banca_vendite.nome, ' - ', banca_vendite.iban) AS descrizione_banca_vendite,
banca_acquisti.id AS id_banca_acquisti,
CONCAT(banca_acquisti.nome, ' - ', banca_acquisti.iban) AS descrizione_banca_acquisti
FROM co_pagamenti
LEFT JOIN co_banche banca_vendite ON co_pagamenti.idconto_vendite = banca_vendite.id_pianodeiconti3 AND banca_vendite.id_anagrafica = ".prepare($id_azienda).' AND banca_vendite.deleted_at IS NULL AND banca_vendite.predefined = 1
LEFT JOIN co_banche banca_acquisti ON co_pagamenti.idconto_acquisti = banca_acquisti.id_pianodeiconti3 AND banca_acquisti.id_anagrafica = '.prepare($id_azienda).' AND banca_acquisti.deleted_at IS NULL AND banca_acquisti.predefined = 1
|where| GROUP BY co_pagamenti.descrizione ORDER BY co_pagamenti.descrizione ASC';
foreach ($elements as $element) {
$filter[] = 'co_pagamenti.id = '.prepare($element);
}
if (!empty($superselect['codice_modalita_pagamento_fe'])) {
$where[] = 'codice_modalita_pagamento_fe = '.prepare($superselect['codice_modalita_pagamento_fe']);
}
if (!empty($search)) {
$search_fields[] = 'descrizione LIKE '.prepare('%'.$search.'%');
}
break;
}
| gpl-3.0 |
Typeverse/buildverse-sdk | for-each-project/src/forEachProject.ts | 5845 | /*
for-each-project - process a set of project directories
Copyright (c) 2017 Justin Johansson (https://github.com/indiescripter).
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 <https://www.gnu.org/licenses/gpl.txt>.
*/
/// <reference path="../../internal/core/index.ts"/>
/// <reference path="../../internal/optional/directorySentinel.ts"/>
/// <reference path="../../internal/optional/packageManager.ts"/>
/// <reference path="scriptGenFunction.ts"/>
function clearFepSentinels(thisProjectDir: AbsoluteFsPath, sentinelName: string) {
// tslint:disable-next-line:no-shadowed-variable
function _clearFepSentinels(thisProjectDir: AbsoluteFsPath, visitedDirs: { [path: string]: boolean }) {
if (!(thisProjectDir in visitedDirs)) {
visitedDirs[thisProjectDir] = true;
DirectorySentinel.clear(thisProjectDir, sentinelName);
const pkgObj = PackageManager.readPackageJson(thisProjectDir);
const prjNode = PackageManager.projectNode(pkgObj);
const projectDirs: FsPath[] = prjNode.subprojects;
for (const projectDir of projectDirs) {
const _projectDir: AbsoluteFsPath = _path.resolve(thisProjectDir, projectDir);
_clearFepSentinels(_projectDir, visitedDirs);
}
}
}
_clearFepSentinels(thisProjectDir, {});
}
function forEachProject(
scriptGenFnName: string,
thisProjectDir: AbsoluteFsPath,
projectDirs: FsPath[],
scriptGenFn: ScriptGenFunction,
args: string[],
bChdir: boolean)
: ExitCode {
function _forEachProject(
// tslint:disable-next-line:no-shadowed-variable
sentinelName: string)
: ExitCode {
const newEnv = Object.assign({}, process.env);
newEnv[sentinelName] = String(levelNumber(process.env[sentinelName]) + 1);
for (const projectDir of projectDirs) {
// const _projectDir: AbsoluteFsPath = _path.resolve(thisProjectDir, projectDir);
let cmdLine: string;
if (scriptGenFn.length === 2) {
const scriptGenFn2: ScriptGenFunction2 = scriptGenFn as any;
cmdLine = scriptGenFn2(_path.basename(projectDir), args);
}
else if (scriptGenFn.length === 3) {
const scriptGenFn3: ScriptGenFunction3 = scriptGenFn as any;
const pkgObj: PackageObject = PackageManager.readPackageJson(projectDir) || {};
cmdLine = scriptGenFn3(projectDir, pkgObj, args);
}
else {
err(`Internal error: invalid command function arity (${scriptGenFn.length})'.`);
return EXIT_FAIL;
}
const fepSentinel = DirectorySentinel.testAndSet(projectDir, sentinelName);
if (fepSentinel) {
// Encountered a cycle in projects graph or a concurrent processing guard.
// Either way we don't have to process this directory as it's already
// happened or is happening.
continue;
}
// TODO: Revisit this logic
const cmdNeedsPackageJsonToExist: boolean =
bChdir &&
cmdLine.indexOf('npm-cli.js ') === 0 ||
cmdLine.indexOf('pnpm.js ') === 0 ||
cmdLine.indexOf('yarn.js ') === 0;
if (cmdNeedsPackageJsonToExist && !PackageManager.packageJsonExists(projectDir)) {
continue;
}
if (bChdir) {
log(`\n$ (cd ${projectDir} && ${cmdLine})`);
}
else {
log(`\n$ ${cmdLine}`);
}
let executable: string;
let execArgs: string[];
let execOptions: any;
if (Platform.isWindows()) {
executable = 'cmd';
execOptions = {
cwd: bChdir ? projectDir : undefined,
env: newEnv,
shell: true,
stdio: 'pipe'
};
execArgs = ['/d', '/s', '/c', cmdLine];
}
else {
executable = 'sh';
execOptions = {
cwd: bChdir ? projectDir : undefined,
env: newEnv,
stdio: 'inherit'
};
execArgs = ['-c', cmdLine];
}
const spawnResult = _cp.spawnSync(executable, execArgs, execOptions);
// tslint:disable-next-line:triple-equals
if (spawnResult.stdout != null) {
log(spawnResult.stdout.toString());
}
if (spawnResult.status !== EXIT_SUCCESS) {
// tslint:disable-next-line:triple-equals
if (spawnResult.stderr != null) {
err(spawnResult.stderr.toString());
}
return EXIT_FAIL;
}
}
return EXIT_SUCCESS;
}
function levelNumber(strvalue: Option<string>): number {
return Number(strvalue) || 0;
}
const sentinelName = DirectorySentinel.mkSentinelName('buildverse',
process.env.npm_lifecycle_event || '', scriptGenFnName);
const feplvl = levelNumber(process.env[sentinelName]);
if (feplvl === 0) {
// log(`BEGIN ****** ${thisProjectDir} :
// ${projectsKey} : ${scriptGenFnName} : ${process.env.npm_lifecycle_event}\n`);
// Do this at start out in case it failed last time round at end.
clearFepSentinels(thisProjectDir, sentinelName);
}
const exitCode = _forEachProject(sentinelName);
if (feplvl === 0) {
// log(`\nEND ******** ${thisProjectDir} :
// ${projectsKey} : ${scriptGenFnName} : ${process.env.npm_lifecycle_event}`);
clearFepSentinels(thisProjectDir, sentinelName);
}
return exitCode;
}
| gpl-3.0 |
patagonaa/AmbientLight.NET | src/AmbientLightNet/AmbientLightNet.Service/Properties/AssemblyInfo.cs | 1535 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("AmbientLightNet.Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AmbientLightNet.Service")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("b861287d-b449-4ee7-8a47-0af65edcb710")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-3.0 |
physalix-enrollment/physalix | Campaign/src/main/java/hsa/awp/campaign/facade/CampaignFacade.java | 15424 | /*
* Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer,
* Rico Lieback, Sebastian Gabriel, Lothar Gesslein,
* Alexander Rampp, Kai Weidner
*
* This file is part of the Physalix Enrollment System
*
* Foobar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package hsa.awp.campaign.facade;
import hsa.awp.campaign.dao.*;
import hsa.awp.campaign.model.*;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* Facade for accessing all domain objects in the Campaign Context.
*
* @author klassm
*/
public final class CampaignFacade implements ICampaignFacade {
/**
* {@link Campaign} Data Access Object.
*/
private ICampaignDao campaignDao;
/**
* {@link ConfirmedRegistration} Data Access Object.
*/
private IConfirmedRegistrationDao confirmedRegistrationDao;
/**
* {@link ConfirmProcedure} Data Access Object.
*/
private IConfirmProcedureDao confirmProcedureDao;
/**
* {@link DrawProcedure} Data Access Object.
*/
private IDrawProcedureDao drawProcedureDao;
/**
* {@link FifoProcedure} Data Access Object.
*/
private IFifoProcedureDao fifoProcedureDao;
/**
* {@link PriorityList} Data Access Object.
*/
private IPriorityListDao priorityListDao;
/**
* {@link PriorityListItem} Data Access Object.
*/
private IPriorityListItemDao priorityListItemDao;
/**
* {@link Procedure} Data Access Object.
*/
private IProcedureDao procedureDao;
@Transactional
@Override
public long countConfirmedRegistrationsByEventId(long eventId) {
return confirmedRegistrationDao.countItemsByEventId(eventId);
}
@Transactional
@Override
public long countConfirmedRegistrationsByProcedure(Procedure procedure) {
return confirmedRegistrationDao.countItemsByProcedure(procedure);
}
@Transactional
@Override
public long countConfirmedRegistrationsByParticipantIdAndCampaignId(Long participantId, Long campaignId) {
return confirmedRegistrationDao.countItemsByParticipantIdAndCampaignId(participantId, campaignId);
}
@Transactional
@Override
public List<Campaign> findActiveCampaigns() {
return campaignDao.findActive();
}
@Transactional
@Override
public List<Campaign> findActiveCampaignSince(Calendar since) {
if (since == null) {
return campaignDao.findActive();
}
if (since.compareTo(Calendar.getInstance()) > 0) {
throw new IllegalArgumentException("since data has to be before now.");
}
return campaignDao.findActiveSince(since);
}
@Transactional
@Override
public List<Procedure> findActiveProcedureSince(Calendar since) {
if (since == null) {
return procedureDao.findActive();
}
if (since.compareTo(Calendar.getInstance()) > 0) {
throw new IllegalArgumentException("since data has to be before now.");
}
return procedureDao.findActiveSince(since);
}
@Transactional
@Override
public List<ConfirmedRegistration> findConfirmedRegistrationsByCampaign(Campaign campaign) {
return confirmedRegistrationDao.findByCampaign(campaign);
}
@Transactional
@Override
public List<ConfirmedRegistration> findConfirmedRegistrationsByEvent(Long eventId) {
return confirmedRegistrationDao.findItemsByEventId(eventId);
}
@Transactional
@Override
public List<ConfirmedRegistration> findConfirmedRegistrationsByParticipantId(Long participantId) {
return confirmedRegistrationDao.findItemsByParticipantId(participantId);
}
@Transactional
@Override
public boolean hasParticipantConfirmedRegistrationInEvent(Long participantId, Long eventId) {
return confirmedRegistrationDao.hasParticipantConfirmedRegistrationInEvent(participantId, eventId);
}
@Transactional
@Override
public List<PriorityListItem> findPriorityListItemsByEventId(Long eventId) {
return priorityListItemDao.findItemsByEventId(eventId);
}
@Transactional
@Override
public List<PriorityList> findPriorityListsByUserAndProcedure(Long userId, Procedure procedure) {
return priorityListDao.findByUserAndProcedure(userId, procedure);
}
@Transactional
@Override
public List<Campaign> getAllCampaigns() {
return campaignDao.findAll();
}
@Override
@Transactional
public List<ConfirmedRegistration> getAllConfirmedRegistrations() {
return confirmedRegistrationDao.findAll();
}
@Override
@Transactional
public List<FifoProcedure> getAllFifoProcedures() {
return fifoProcedureDao.findAll();
}
@Override
@Transactional
public List<PriorityList> getAllPriorityLists() {
return priorityListDao.findAll();
}
@Override
@Transactional
public List<Procedure> getAllProcedures() {
return procedureDao.findAll();
}
@Override
@Transactional
public List<Procedure> getAllUnusedProcedures() {
return procedureDao.findUnused();
}
@Transactional
@Override
public Campaign getCampaignById(Long id) {
return campaignDao.findById(id);
}
@Transactional
@Override
public Campaign getCampaignByNameAndMandator(String name, Long mandatorId) {
return campaignDao.findByNameAndMandator(name, mandatorId);
}
@Transactional
@Override
public List<Campaign> getCampaignsByEventId(Long id) {
return campaignDao.findCampaignsByEventId(id);
}
@Transactional
@Override
public ConfirmedRegistration getConfirmedRegistrationById(Long id) {
return confirmedRegistrationDao.findById(id);
}
@Transactional
@Override
public List<ConfirmedRegistration> getConfirmedRegistrationsByProcedure(Procedure p) {
return confirmedRegistrationDao.findByProcedure(p);
}
@Transactional
@Override
public ConfirmProcedure getConfirmProcedureById(Long id) {
return confirmProcedureDao.findById(id);
}
@Transactional
@Override
public DrawProcedure getDrawProcedureById(Long id) {
return drawProcedureDao.findById(id);
}
@Transactional
@Override
public FifoProcedure getFifoProcedureById(Long id) {
return fifoProcedureDao.findById(id);
}
@Transactional
@Override
public PriorityList getPriorityListById(Long id) {
return priorityListDao.findById(id);
}
@Transactional
@Override
public void removeCampaign(Campaign campaign) {
campaignDao.remove(campaign);
}
@Transactional
@Override
public void removeConfirmedRegistration(ConfirmedRegistration confirmedRegistration) {
confirmedRegistrationDao.remove(confirmedRegistration);
}
@Transactional
@Override
public void removeConfirmProcedure(ConfirmProcedure c) {
confirmProcedureDao.remove(c);
}
@Transactional
@Override
public void removeDrawProcedure(DrawProcedure d) {
if (d == null) {
throw new IllegalArgumentException("no procedure given");
}
d = drawProcedureDao.findById(d.getId());
// remove all PriorityLists from the DrawProcedure
for (PriorityList prio : new LinkedList<PriorityList>(d.getPriorityLists())) {
removePriorityList(prio);
}
// remove set Procedures in ConfirmedRegistrations
for (ConfirmedRegistration conf : confirmedRegistrationDao.findByProcedure(d)) {
conf.setProcedure(null);
updateConfirmedRegistration(conf);
}
Campaign campaign = d.getCampaign();
if (campaign != null) {
campaign.removeProcedure(d);
updateCampaign(campaign);
}
drawProcedureDao.remove(d);
}
@Transactional
@Override
public void removeFifoProcedure(FifoProcedure f) {
if (f == null) {
throw new IllegalArgumentException("no procedure given");
}
f = fifoProcedureDao.findById(f.getId());
// remove set Procedures in ConfirmedRegistrations
for (ConfirmedRegistration conf : confirmedRegistrationDao.findByProcedure(f)) {
conf.setProcedure(null);
}
Campaign campaign = f.getCampaign();
if (campaign != null) {
campaign.removeProcedure(f);
updateCampaign(campaign);
}
fifoProcedureDao.remove(f);
}
@Transactional
@Override
public void removePriorityList(PriorityList item) {
if (item == null) {
throw new IllegalArgumentException("no PriorityList given");
}
DrawProcedure proc = updateDrawProcedure(item.getProcedure());
if (proc != null) {
int size = proc.getPriorityLists().size();
proc.getPriorityLists().remove(item);
if (size - 1 != proc.getPriorityLists().size()) {
throw new IllegalStateException("could not remove priority list from procedure");
}
drawProcedureDao.merge(proc);
}
priorityListDao.remove(item);
}
@Transactional
@Override
public void removePriorityListItem(PriorityListItem item) {
priorityListItemDao.remove(item);
}
@Transactional
@Override
public Campaign saveCampaign(Campaign c) {
return campaignDao.persist(c);
}
@Transactional
@Override
public ConfirmedRegistration saveConfirmedRegistration(ConfirmedRegistration c) {
return confirmedRegistrationDao.persist(c);
}
@Transactional
@Override
public ConfirmProcedure saveConfirmProcedure(ConfirmProcedure c) {
return confirmProcedureDao.persist(c);
}
@Transactional
@Override
public DrawProcedure saveDrawProcedure(DrawProcedure d) {
return drawProcedureDao.persist(d);
}
@Transactional
@Override
public FifoProcedure saveFifoProcedure(FifoProcedure f) {
return fifoProcedureDao.persist(f);
}
@Transactional
@Override
public PriorityList savePriorityList(PriorityList prioList) {
return priorityListDao.persist(prioList);
}
@Transactional
@Override
public PriorityListItem savePriorityListItem(PriorityListItem item) {
return priorityListItemDao.persist(item);
}
@Transactional
@Override
public Procedure saveProcedure(Procedure proc) {
return procedureDao.persist(proc);
}
@Transactional
@Override
public Campaign updateCampaign(Campaign campaign) {
return campaignDao.merge(campaign);
}
@Transactional
@Override
public ConfirmedRegistration updateConfirmedRegistration(ConfirmedRegistration c) {
return confirmedRegistrationDao.merge(c);
}
@Transactional
@Override
public ConfirmProcedure updateConfirmProcedure(ConfirmProcedure c) {
return confirmProcedureDao.merge(c);
}
@Transactional
@Override
public DrawProcedure updateDrawProcedure(DrawProcedure d) {
return drawProcedureDao.merge(d);
}
@Transactional
@Override
public FifoProcedure updateFifoProcedure(FifoProcedure f) {
return fifoProcedureDao.merge(f);
}
@Transactional
@Override
public PriorityList updatePriorityList(PriorityList prioList) {
return priorityListDao.merge(prioList);
}
@Transactional
@Override
public PriorityListItem updatePriorityListItem(PriorityListItem item) {
return priorityListItemDao.merge(item);
}
@Transactional
@Override
public Procedure updateProcedure(Procedure procedure) {
return procedureDao.merge(procedure);
}
@Transactional
@Override
public List<ConfirmedRegistration> findConfirmedRegistrationsByParticipantIdAndProcedure(Long participantId, Procedure procedure) {
return confirmedRegistrationDao.findItemsByParticipantIdAndProcedure(participantId, procedure);
}
@Transactional
@Override
public void removePriorityListsAssociatedWithDrawProcedure(DrawProcedure procedure) {
procedure = getDrawProcedureById(procedure.getId());
Collection<PriorityList> lists = new LinkedList<PriorityList>(procedure.getPriorityLists());
for (PriorityList list : lists) {
removePriorityList(list);
}
}
/**
* Sets the CampaignDao.
*
* @param dao campaignDao
*/
public void setCampaignDao(ICampaignDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
campaignDao = dao;
}
/**
* Sets the {@link ConfirmProcedure} dao.
*
* @param dao Data Access Object to set.
*/
public void setConfirmProcedureDao(IConfirmProcedureDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.confirmProcedureDao = dao;
}
/**
* Sets the {@link FifoProcedure} dao.
*
* @param dao Data Access Object to set.
*/
public void setConfirmedRegistrationDao(IConfirmedRegistrationDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.confirmedRegistrationDao = dao;
}
/**
* Sets the {@link DrawProcedure} dao.
*
* @param dao Data Access Object to set.
*/
public void setDrawProcedureDao(IDrawProcedureDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.drawProcedureDao = dao;
}
/**
* Sets the {@link FifoProcedure} dao.
*
* @param dao Data Access Object to set.
*/
public void setFifoProcedureDao(IFifoProcedureDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.fifoProcedureDao = dao;
}
/**
* Sets the {@link PriorityList} dao.
*
* @param dao Data Access Object to set.
*/
public void setPriorityListDao(IPriorityListDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.priorityListDao = dao;
}
/**
* Setter for priorityListItemDao.
*
* @param priorityListItemDao the priorityListItemDao to set
*/
public void setPriorityListItemDao(IPriorityListItemDao priorityListItemDao) {
this.priorityListItemDao = priorityListItemDao;
}
/**
* Sets the {@link Procedure} dao.
*
* @param dao Data Access Object to set.
*/
public void setProcedureDao(IProcedureDao dao) {
if (dao == null) {
throw new IllegalArgumentException("no dao given");
}
this.procedureDao = dao;
}
@Override
@Transactional
public List<Campaign> findCampaignsByMandatorId(Long mandatorId) {
return campaignDao.findByMandator(mandatorId);
}
@Override
@Transactional
public List<Procedure> findProceduresByMandatorId(Long mandatorId) {
return procedureDao.findByMandator(mandatorId);
}
@Override
@Transactional
public List<Campaign> getActiveCampaignsByMandatorId(Long mandator) {
return campaignDao.findActiveByMandator(mandator);
}
@Override
@Transactional
public List<Procedure> getAllUnusedProceduresByMandator(Long mandator) {
return procedureDao.findUnusedByMandator(mandator);
}
@Override
@Transactional
public List<ConfirmedRegistration> findConfirmedRegistrationsByParticipantIdAndMandator(Long id, Long activeMandator) {
return confirmedRegistrationDao.findItemsByParticipantIdAndMandator(id, activeMandator);
}
}
| gpl-3.0 |
lukas2005/Device-Mod-Apps | src/main/java/io/github/lukas2005/DeviceModApps/swing/SwingWrapper.java | 8207 | package io.github.lukas2005.DeviceModApps.swing;
import com.teamdev.jxbrowser.chromium.BrowserKeyEvent.KeyCode;
import com.teamdev.jxbrowser.chromium.BrowserMouseEvent.MouseButtonType;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* @author lukas2005
*/
public class SwingWrapper {
public int width = 0;
public int height = 0;
public int renderWidth;
public int renderHeight;
public JFrame frame;
public JPanel panel;
public Component c;
protected BufferedImage img;
//private BufferedImage imgOld;
protected Graphics g;
protected Thread paintThread;
protected Minecraft mc = Minecraft.getMinecraft();
protected TextureManager txt = mc.getTextureManager();
public SwingWrapper(int width, int height, int renderWidth, int renderHeight, Component c) {
//if (!SwingUtils.initialized) throw new IllegalStateException("SwingUtils not initalized!");
//if (!c.isLightweight()) throw new IllegalArgumentException("Heavyweight components are not currently supported!");
frame = new JFrame();
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(0, 0));
frame.setContentPane(panel);
this.width = width;
this.height = height;
this.renderWidth = renderWidth;
this.renderHeight = renderHeight;
this.c = c;
img = new BufferedImage(renderWidth, renderHeight, BufferedImage.TYPE_INT_RGB);
g = img.createGraphics();
panel.add(c, BorderLayout.CENTER);
frame.setState(JFrame.NORMAL);
frame.setVisible(true);
new Thread(() -> {
try {
Thread.sleep(500);
frame.setState(JFrame.ICONIFIED);
} catch (InterruptedException ignored) {
}
}).start();
if (c.getName() == null) c.setName("Component");
paintThread = new ComponentPaintingThread(renderWidth, renderHeight, this);
paintThread.start();
}
public SwingWrapper(int width, int height, Component c) {
this(width, height, width, height, c);
}
@Override
protected void finalize() throws Throwable {
dispose();
}
/**
* call when this object is no longer needed
*/
public void dispose() {
paintThread.interrupt();
panel.remove(this.c);
frame.remove(panel);
frame.setVisible(false);
frame = null;
panel = null;
c = null;
}
public void handleMouseClick(int xPosition, int yPosition, int mouseX, int mouseY, int mouseButton) {
if (mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + this.width && mouseY < yPosition + this.height) {
Point p = new Point(Math.round(SwingUtils.map(mouseX - xPosition, 0, width, 0, c.getWidth())), Math.round(SwingUtils.map(mouseY - yPosition, 0, height, 0, c.getHeight())));
Point globalP = p.getLocation();
SwingUtilities.convertPointToScreen(globalP, c);
if (!(c instanceof BrowserView)) {
SwingUtils.click(c, p.x, p.y, mouseButton);
} else {
BrowserView view = (BrowserView) c;
MouseButtonType buttonType = MouseButtonType.PRIMARY;
switch (mouseButton) {
case 1:
buttonType = MouseButtonType.SECONDARY;
break;
case 2:
buttonType = MouseButtonType.MIDDLE;
break;
}
SwingUtils.forwardMouseClickEvent(view.getBrowser(), buttonType, p.x, p.y, globalP.x, globalP.y);
}
}
}
public void handleMouseScroll(int xPosition, int yPosition, int mouseX, int mouseY, boolean direction) {
if (mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + this.width && mouseY < yPosition + this.height) {
Point p = new Point(Math.round(SwingUtils.map(mouseX - xPosition, 0, width, 0, c.getWidth())), Math.round(SwingUtils.map(mouseY - yPosition, 0, height, 0, c.getHeight())));
if (c instanceof BrowserView) {
BrowserView view = (BrowserView) c;
SwingUtils.forwardMouseScrollEvent(view.getBrowser(), direction ? 5 : -5, p.x, p.y);
}
}
}
public void handleMouseDrag(int xPosition, int yPosition, int mouseX, int mouseY, int mouseButton) {
if (mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + this.width && mouseY < yPosition + this.height) {
Point p = new Point(Math.round(SwingUtils.map(mouseX - xPosition, 0, width, 0, c.getWidth())), Math.round(SwingUtils.map(mouseY - yPosition, 0, height, 0, c.getHeight())));
Point globalP = p.getLocation();
SwingUtilities.convertPointToScreen(globalP, c);
if (!(c instanceof BrowserView)) {
SwingUtils.click(c, p.x, p.y, mouseButton);
} else {
BrowserView view = (BrowserView) c;
MouseButtonType buttonType = MouseButtonType.PRIMARY;
switch (mouseButton) {
case 1:
buttonType = MouseButtonType.SECONDARY;
break;
case 2:
buttonType = MouseButtonType.MIDDLE;
break;
}
SwingUtils.forwardMouseDragEvent(view.getBrowser(), buttonType, p.x, p.y, globalP.x, globalP.y);
}
}
}
public void handleMouseRelease(int xPosition, int yPosition, int mouseX, int mouseY, int mouseButton) {
if (mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + this.width && mouseY < yPosition + this.height) {
Point p = new Point(Math.round(SwingUtils.map(mouseX - xPosition, 0, width, 0, c.getWidth())), Math.round(SwingUtils.map(mouseY - yPosition, 0, height, 0, c.getHeight())));
Point globalP = p.getLocation();
SwingUtilities.convertPointToScreen(globalP, c);
if (!(c instanceof BrowserView)) {
SwingUtils.click(c, p.x, p.y, mouseButton);
} else {
BrowserView view = (BrowserView) c;
MouseButtonType buttonType = MouseButtonType.PRIMARY;
switch (mouseButton) {
case 1:
buttonType = MouseButtonType.SECONDARY;
break;
case 2:
buttonType = MouseButtonType.MIDDLE;
break;
}
SwingUtils.forwardMouseReleaseEvent(view.getBrowser(), buttonType, p.x, p.y, globalP.x, globalP.y);
}
}
}
public void handleKeyTyped(char key, int code) {
if (c instanceof BrowserView) {
BrowserView view = (BrowserView) c;
switch (code) {
case (Keyboard.KEY_BACK):
SwingUtils.forwardKeyTypedEvent(view.getBrowser(), KeyCode.VK_BACK);
break;
default:
SwingUtils.forwardKeyTypedEvent(view.getBrowser(), key);
break;
}
}
}
ResourceLocation rc;
boolean isTheSameOld = true;
int lastMouseX = 0;
int lastMouseY = 0;
public void render(int x, int y, int mouseX, int mouseY) {
rc = txt.getDynamicTextureLocation(c.toString(), new DynamicTexture(img));
if (!frame.isVisible()) frame.setVisible(true);
if (rc != null) {
mc.getRenderManager().renderEngine.bindTexture(rc);
drawRectWithFullTexture(x, y, width, height);
txt.deleteTexture(rc);
}
if (mouseX >= x && mouseY >= y && mouseX < x + this.width && mouseY < y + this.height) {
if (mouseX != lastMouseX && mouseY != lastMouseY) {
if (c instanceof BrowserView) {
Point p = new Point(Math.round(SwingUtils.map(mouseX - x, 0, width, 0, c.getWidth())), Math.round(SwingUtils.map(mouseY - y, 0, height, 0, c.getHeight())));
Point globalP = p.getLocation();
SwingUtilities.convertPointToScreen(globalP, c);
BrowserView view = (BrowserView) c;
SwingUtils.forwardMouseMoveEvent(view.getBrowser(), p.x, p.y, globalP.x, globalP.y);
}
}
}
lastMouseX = mouseX;
lastMouseY = mouseY;
}
private static void drawRectWithFullTexture(double x, double y, int width, int height) {
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.begin(7, DefaultVertexFormats.POSITION_TEX);
buffer.pos(x, y + height, 0).tex(0, 1).endVertex();
buffer.pos(x + width, y + height, 0).tex(1, 1).endVertex();
buffer.pos(x + width, y, 0).tex(1, 0).endVertex();
buffer.pos(x, y, 0).tex(0, 0).endVertex();
tessellator.draw();
}
}
//2005920 | gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/test/tuning/TuningMemberFieldQuery.java | 2416 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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.db4o.test.tuning;
import com.db4o.*;
import com.db4o.query.*;
import com.db4o.test.*;
/**
* Original performance on Carls machine with Skype on:
* Querying 10000 objects for member identity: 500ms
* @author root_rosenberger
*
*/
public class TuningMemberFieldQuery {
static final int COUNT = 2;
TMFMember member;
public TuningMemberFieldQuery(){
}
public TuningMemberFieldQuery(TMFMember member){
this.member = member;
}
public void configure() {
Db4o.configure().objectClass(this).objectField("member").indexed(true);
Db4o.configure().objectClass(TMFMember.class).objectField("name").indexed(true);
}
public void store(){
for (int i = 0; i < COUNT; i++) {
Test.store(new TuningMemberFieldQuery(new TMFMember("" + i)));
}
}
public void test(){
Query q = Test.query();
q.constrain(TuningMemberFieldQuery.class);
q.descend("member").descend("name").constrain("1");
long start = System.currentTimeMillis();
ObjectSet objectSet = q.execute();
long stop = System.currentTimeMillis();
Test.ensure(objectSet.size() == 1);
TuningMemberFieldQuery tmf = (TuningMemberFieldQuery)objectSet.next();
Test.ensure(tmf.member.name.equals("1"));
long duration = stop - start;
System.out.println("Querying " + COUNT + " objects for member identity: " + duration + "ms");
}
public static class TMFMember{
String name;
public TMFMember(){
}
public TMFMember(String name){
this.name = name;
}
}
}
| gpl-3.0 |
pandigresik/OpenSID | donjo-app/views/line/table.php | 9794 | <script type="text/javascript">
$(function()
{
var keyword = <?= $keyword?> ;
$( "#cari" ).autocomplete(
{
source: keyword,
maxShowItems: 10,
});
});
</script>
<div class="content-wrapper">
<section class="content-header">
<h1>Pengaturan Tipe Garis</h1>
<ol class="breadcrumb">
<li><a href="<?= site_url('hom_sid')?>"><i class="fa fa-home"></i> Home</a></li>
<li class="active">Pengaturan Tipe Garis</li>
</ol>
</section>
<section class="content" id="maincontent">
<form id="mainform" name="mainform" method="post">
<div class="row">
<div class="col-md-3">
<?php $this->load->view('plan/nav.php')?>
</div>
<div class="col-md-9">
<div class="box box-info">
<div class="box-header with-border">
<a href="<?=site_url("line/form")?>" class="btn btn-social btn-flat btn-success btn-sm btn-sm visible-xs-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block" title="Tambah Data Baru">
<i class="fa fa-plus"></i>Tambah Jenis Garis Baru
</a>
<?php if ($this->CI->cek_hak_akses('h')): ?>
<a href="#confirm-delete" title="Hapus Data" onclick="deleteAllBox('mainform', '<?=site_url("line/delete_all/$p/$o")?>')" class="btn btn-social btn-flat btn-danger btn-sm visible-xs-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block hapus-terpilih"><i class='fa fa-trash-o'></i> Hapus Data Terpilih</a>
<?php endif; ?>
<a href="<?= site_url("{$this->controller}/clear") ?>" class="btn btn-social btn-flat bg-purple btn-sm visible-xs-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block"><i class="fa fa-refresh"></i>Bersihkan Filter</a>
</div>
<div class="box-body">
<div class="row">
<div class="col-sm-12">
<div class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<form id="mainform" name="mainform" method="post">
<div class="row">
<div class="col-sm-6">
<select class="form-control input-sm " name="filter" onchange="formAction('mainform', '<?=site_url('line/filter')?>')">
<option value="">Semua</option>
<option value="1" <?php if ($filter==1): ?>selected<?php endif ?>>Aktif</option>
<option value="2" <?php if ($filter==2): ?>selected<?php endif ?>>Tidak Aktif</option>
</select>
</div>
<div class="col-sm-6">
<div class="box-tools">
<div class="input-group input-group-sm pull-right">
<input name="cari" id="cari" class="form-control" placeholder="Cari..." type="text" value="<?=html_escape($cari)?>" onkeypress="if (event.keyCode == 13):$('#'+'mainform').attr('action', '<?=site_url("line/search")?>');$('#'+'mainform').submit();endif">
<div class="input-group-btn">
<button type="submit" class="btn btn-default" onclick="$('#'+'mainform').attr('action', '<?=site_url("line/search")?>');$('#'+'mainform').submit();"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped dataTable table-hover">
<thead class="bg-gray disabled color-palette">
<tr>
<th><input type="checkbox" id="checkall"/></th>
<th>No</th>
<th>Aksi</th>
<?php if ($o==2): ?>
<th><a href="<?= site_url("line/index/$p/1")?>">Jenis <i class='fa fa-sort-asc fa-sm'></i></a></th>
<?php elseif ($o==1): ?>
<th><a href="<?= site_url("line/index/$p/2")?>">Jenis <i class='fa fa-sort-desc fa-sm'></i></a></th>
<?php else: ?>
<th><a href="<?= site_url("line/index/$p/1")?>">Jenis <i class='fa fa-sort fa-sm'></i></a></th>
<?php endif; ?>
<?php if ($o==4): ?>
<th nowrap><a href="<?= site_url("line/index/$p/3")?>">Aktif <i class='fa fa-sort-asc fa-sm'></i></a></th>
<?php elseif ($o==3): ?>
<th nowrap><a href="<?= site_url("line/index/$p/4")?>">Aktif <i class='fa fa-sort-desc fa-sm'></i></a></th>
<?php else: ?>
<th nowrap><a href="<?= site_url("line/index/$p/3")?>">Aktif <i class='fa fa-sort fa-sm'></i></a></th>
<?php endif; ?>
<th>Warna</th>
</tr>
</thead>
<tbody>
<?php foreach ($main as $data): ?>
<tr>
<td><input type="checkbox" name="id_cb[]" value="<?=$data['id']?>" /></td>
<td><?=$data['no']?></td>
<td nowrap>
<a href="<?= site_url("line/form/$p/$o/$data[id]")?>" class="btn btn-warning btn-flat btn-sm" title="Ubah"><i class="fa fa-edit"></i></a>
<a href="<?= site_url("line/sub_line/$data[id]")?>" class="btn bg-purple btn-flat btn-sm" title="Rincian <?= $data['nama'] ?>"><i class="fa fa-bars"></i></a>
<a href="<?= site_url("line/ajax_add_sub_line/$data[id]")?>" class="btn bg-olive btn-flat btn-sm" title="Tambah Kategori <?= $data['nama']?>" data-remote="false" data-toggle="modal" data-target="#modalBox" data-title="Tambah Kategori <?= $data['nama']?>"><i class="fa fa-plus"></i></a>
<?php if ($data['enabled'] == '2'): ?>
<a href="<?= site_url('line/line_lock/'.$data['id'])?>" class="btn bg-navy btn-flat btn-sm" title="Aktifkan"><i class="fa fa-lock"> </i></a>
<?php elseif ($data['enabled'] == '1'): ?>
<a href="<?= site_url('line/line_unlock/'.$data['id'])?>" class="btn bg-navy btn-flat btn-sm" title="Non Aktifkan"><i class="fa fa-unlock"></i></a>
<?php endif ?>
<a href="#" data-href="<?= site_url("line/delete/$p/$o/$data[id]")?>" class="btn bg-maroon btn-flat btn-sm" title="Hapus" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash-o"></i></a>
</td>
<td width="60%"><?= $data['nama']?></td>
<td><?= $data['aktif']?></td>
<td><div style="background-color:<?= $data['color']?>"> <div></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</form>
<div class="row">
<div class="col-sm-6">
<div class="dataTables_length">
<form id="paging" action="<?= site_url("line")?>" method="post" class="form-horizontal">
<label>
Tampilkan
<select name="per_page" class="form-control input-sm" onchange="$('#paging').submit()">
<option value="20" <?php selected($per_page, 20); ?> >20</option>
<option value="50" <?php selected($per_page, 50); ?> >50</option>
<option value="100" <?php selected($per_page, 100); ?> >100</option>
</select>
Dari
<strong><?= $paging->num_rows?></strong>
Total Data
</label>
</form>
</div>
</div>
<div class="col-sm-6">
<div class="dataTables_paginate paging_simple_numbers">
<ul class="pagination">
<?php if ($paging->start_link): ?>
<li><a href="<?=site_url("line/index/$paging->start_link/$o")?>" aria-label="First"><span aria-hidden="true">Awal</span></a></li>
<?php endif; ?>
<?php if ($paging->prev): ?>
<li><a href="<?=site_url("line/index/$paging->prev/$o")?>" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
<?php endif; ?>
<?php for ($i=$paging->start_link;$i<=$paging->end_link;$i++): ?>
<li <?=jecho($p, $i, "class='active'")?>><a href="<?= site_url("line/index/$i/$o")?>"><?= $i?></a></li>
<?php endfor; ?>
<?php if ($paging->next): ?>
<li><a href="<?=site_url("line/index/$paging->next/$o")?>" aria-label="Next"><span aria-hidden="true">»</span></a></li>
<?php endif; ?>
<?php if ($paging->end_link): ?>
<li><a href="<?=site_url("line/index/$paging->end_link/$o")?>" aria-label="Last"><span aria-hidden="true">Akhir</span></a></li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</section>
</div>
<?php $this->load->view('global/confirm_delete');?>
| gpl-3.0 |
polycat/polycat.github.io | nbody/js/body.js | 3564 | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['util'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('util'));
} else {
// Browser globals (root is window)
root.Body = factory(root.Util);
}
} (this, function (Util) {
function Body(id) {
this.id = id;
this.coord = [0, 0, 0];
this.velocity = [0, 0, 0];
this.acceleration = [0, 0, 0];
this.mass = 0.0;
}
Body.prototype.setCoord = function (coord) {
this.coord = coord.slice();
return this;
}
Body.prototype.setRandomCoord = function (min, max) {
return this.setCoord(Util.getRandomVector(min, max));
}
Body.prototype.setVelocity = function (velocity) {
this.velocity = velocity.slice();
return this;
}
Body.prototype.setRandomVelocity = function (min, max) {
return this.setVelocity(Util.getRandomVector(min, max));
}
Body.prototype.setMass = function (mass) {
this.mass = mass;
return this;
}
Body.prototype.setRandomMass = function (min, max) {
return this.setMass(Util.getRandomInRange(min, max));
}
Body.prototype.computeAcceleration = function (otherBody) {
var G = 6.673e-11;
var dx = otherBody.coord[0] - this.coord[0];
var dy = otherBody.coord[1] - this.coord[1];
var dz = otherBody.coord[2]- this.coord[2];
var dist = Math.sqrt(dx*dx + dy*dy + dz*dz) + 1e-12; // avoid zero distance
var temp = G*otherBody.mass/(dist*dist*dist);
return [temp*dx, temp*dy, temp*dz];
}
Body.prototype.addAccountFrom = function (otherBody) {
return this.addAcceleration(this.computeAcceleration(otherBody));
}
Body.prototype.addAcceleration = function (acceleration) {
Util.addVectors(this.acceleration, acceleration);
return this;
}
Body.prototype.resetAcceleration = function () {
this.acceleration = [0, 0, 0];
return this;
}
Body.prototype.prepareForUpdate = function () {
return this.resetAcceleration();
}
Body.prototype.update = function (delta) {
// r = r0 + v0*t + a*t*t/2
var coordUpd = [0, 0, 0];
coordUpd[0] = this.velocity[0]*delta + this.acceleration[0]*delta*delta*0.5;
coordUpd[1] = this.velocity[1]*delta + this.acceleration[1]*delta*delta*0.5;
coordUpd[2] = this.velocity[2]*delta + this.acceleration[2]*delta*delta*0.5;
Util.addVectors(this.coord, coordUpd);
// v = v0 + a*t;
var velUpd = [0, 0, 0];
velUpd[0] = this.acceleration[0]*delta;
velUpd[1] = this.acceleration[1]*delta;
velUpd[2] = this.acceleration[2]*delta;
Util.addVectors(this.velocity, velUpd);
return this;
}
function generateRandomBodies(numOfBodies, minMass, maxMass) {
var bodies = [];
for (var i = 0; i < numOfBodies; i++) {
var body = new Body(i);
body.setRandomCoord(-10, 10);
body.setRandomVelocity(-0.5, 0.5);
body.setRandomMass(minMass, maxMass);
bodies.push(body);
}
return bodies;
}
function updateBodies(bodies, delta) {
bodies.forEach( function (body) {
body.prepareForUpdate();
bodies.forEach( function (otherBody) {
if (body !== otherBody) {
body.addAccountFrom(otherBody);
}
});
});
bodies.forEach( function (body) {
body.update(delta);
});
}
return {
Body: Body,
generateRandomBodies: generateRandomBodies,
updateBodies: updateBodies
}
}));
| gpl-3.0 |
okdevdo/UserLib | ConSources/ConsoleDirListControl.cpp | 3082 | /******************************************************************************
This file is part of ConSources, which is part of UserLib.
Copyright (C) 1995-2014 Oliver Kreis (okdev10@arcor.de)
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This 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 "CON_PCH.H"
#include "ConsoleDirListControl.h"
#include "Console.h"
CConsoleDirListControl::CConsoleDirListControl(CConstPointer name, CConsole* pConsole):
CConsoleListControl(name, pConsole),
m_Path()
{
}
CConsoleDirListControl::CConsoleDirListControl(CConstPointer name, CConstPointer title, CConsole* pConsole):
CConsoleListControl(name, title, pConsole),
m_Path()
{
}
CConsoleDirListControl::CConsoleDirListControl(CConstPointer path, CAbstractConsoleControlCallback* callback, CConstPointer name, CConstPointer title, CConsole* pConsole):
CConsoleListControl(callback, name, title, pConsole),
m_Path(__FILE__LINE__ path)
{
}
CConsoleDirListControl::CConsoleDirListControl(word taborder, CConstPointer path, CAbstractConsoleControlCallback* callback, CConstPointer name, CConstPointer title, CConsole* pConsole):
CConsoleListControl(taborder, callback, name, title, pConsole),
m_Path(__FILE__LINE__ path)
{
}
CConsoleDirListControl::~CConsoleDirListControl(void)
{
}
void CConsoleDirListControl::CreateListe()
{
try
{
CStringBuffer tmp(m_Path.get_Directory());
m_DirIter.Open(m_Path);
if ( !tmp.IsEmpty() )
AddListItem(CStringBuffer(__FILE__LINE__ _T("..")));
while ( m_DirIter )
{
if ( m_DirIter.is_SubDir() && (!(m_DirIter.is_Hidden())) && (!(m_DirIter.is_System())) )
AddListItem(m_DirIter.get_Name());
++m_DirIter;
}
m_DirIter.Close();
if ( m_Created )
{
m_ScrollBarVInfo.SetScrollBarInfo(GetListItemCount(), m_ScreenBufferSize.Y - 2);
DrawVerticalScrollBar();
m_ScrollPos = 0;
m_HighlightPos = 0;
}
}
catch ( CDirectoryIteratorException* )
{
}
}
void CConsoleDirListControl::Create(COORD pos, COORD size)
{
m_Color = m_Console->GetDefaultColor();
m_HighLightColor = m_Console->GetDefaultHighlightedColor();
m_hasBorder = true;
m_BorderStyle = singleborderstyle;
m_hasTitle = true;
m_TitleStyle = controltitlebarstyle;
m_hasScrollbar = true;
m_ScrollBarStyle = verticalscrollbarstyle;
CreateListe();
m_ScrollBarVInfo.SetScrollBarInfo(GetListItemCount(), size.Y - 2);
CConsoleListControl::Create(pos, size);
}
| gpl-3.0 |
registrobr/whmcs-registrobr-epp | registrobr/PhpWhois/whois.ro.php | 3183 | <?php
/*
Whois.php PHP classes to conduct whois queries
Copyright (C)1999,2005 easyDNS Technologies Inc. & Mark Jeftovic
Maintained by David Saez
For the most recent version of this package visit:
http://www.phpwhois.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 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
BUG
- date on ro could be given as "mail date" (ex: updated field)
- multiple person for one role, ex: news.ro
- seems the only role listed is registrant
*/
if (!defined('__RO_HANDLER__'))
define('__RO_HANDLER__', 1);
require_once('whois.parser.php');
class ro_handler
{
function parse($data_str, $query)
{
$translate = array(
'fax-no' => 'fax',
'e-mail' => 'email',
'nic-hdl' => 'handle',
'person' => 'name',
'address' => 'address.',
'domain-name' => '',
'updated' => 'changed',
'registration-date' => 'created',
'domain-status' => 'status',
'nameserver' => 'nserver'
);
$contacts = array(
'admin-contact' => 'admin',
'technical-contact' => 'tech',
'zone-contact' => 'zone',
'billing-contact' => 'billing'
);
$extra = array(
'postal code:' => 'address.pcode'
);
$reg = generic_parser_a($data_str['rawdata'], $translate, $contacts, 'domain','Ymd');
if (isset($reg['domain']['description']))
{
$reg['owner'] = get_contact($reg['domain']['description'],$extra);
unset($reg['domain']['description']);
foreach($reg as $key => $item)
{
if (isset($item['address']))
{
$data = $item['address'];
unset($reg[$key]['address']);
$reg[$key] = array_merge($reg[$key],get_contact($data,$extra));
}
}
$reg['registered'] = 'yes';
}
else
$reg['registered'] = 'no';
$r['regrinfo'] = $reg;
$r['regyinfo'] = array(
'referrer' => 'http://www.nic.ro',
'registrar' => 'nic.ro'
);
return $r;
}
}
?> | gpl-3.0 |
kalenpw/LibreLife | app/src/main/java/com/kalenpw/librelife/Settings.java | 1007 | package com.kalenpw.librelife;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by kalenpw on 6/14/17.
*/
public class Settings {
static private Context _Context;
static public int NUMBER_OF_PLAYERS;
static public int INITIAL_LIFE_TOTAL;
public static void defaultSettings(){
}
/**
* Sets the context for this class used to for getDefaultSharedPreferences
* @param Context value - the context to be set
*/
public static void setContext(Context value){
_Context = value;
}
/**
* Updates the apps settings
*/
public static void updateSettings(){
String numberOfPlayersString;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(_Context);
numberOfPlayersString = preferences.getString("number_of_players", "-1");
NUMBER_OF_PLAYERS = Integer.parseInt(numberOfPlayersString);
}
}
| gpl-3.0 |
dkatsios/JSOptimizer | JSOptimizer/JMETALHOME/jmetal/problems/ProblemFactory.java | 3424 | // ProblemFactory.java
//
// Author:
// Antonio J. Nebro <antonio@lcc.uma.es>
// Juan J. Durillo <durillo@lcc.uma.es>
//
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// 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/>.
package jmetal.problems;
import jmetal.core.Problem;
import jmetal.util.Configuration;
import jmetal.util.JMException;
import java.lang.reflect.Constructor;
/**
* This class represents a factory for problems
*/
public class ProblemFactory {
/**
* Creates an object representing a problem
* @param name Name of the problem
* @param params Parameters characterizing the problem
* @return The object representing the problem
* @throws JMException
*/
public Problem getProblem(String name, Object [] params) throws JMException {
// Params are the arguments
// The number of argument must correspond with the problem constructor params
String base = "jmetal.problems.";
if (name.equals("TSP") || name.equals("OneMax"))
base += "singleObjective." ;
else if (name.equals("mQAP"))
base += "mqap." ;
else if (name.substring(0,name.length()-1).equalsIgnoreCase("DTLZ"))
base += "DTLZ.";
else if (name.substring(0,name.length()-1).equalsIgnoreCase("WFG"))
base += "WFG.";
else if (name.substring(0,name.length()-1).equalsIgnoreCase("UF"))
base += "cec2009Competition.";
else if (name.substring(0,name.length()-2).equalsIgnoreCase("UF"))
base += "cec2009Competition.";
else if (name.substring(0,name.length()-1).equalsIgnoreCase("ZDT"))
base += "ZDT.";
else if (name.substring(0,name.length()-3).equalsIgnoreCase("ZZJ07"))
base += "ZZJ07.";
else if (name.substring(0,name.length()-3).equalsIgnoreCase("LZ09"))
base += "LZ09.";
else if (name.substring(0,name.length()-4).equalsIgnoreCase("ZZJ07"))
base += "ZZJ07.";
else if (name.substring(0,name.length()-3).equalsIgnoreCase("LZ06"))
base += "LZ06.";
try {
Class problemClass = Class.forName(base+name);
Constructor [] constructors = problemClass.getConstructors();
int i = 0;
//find the constructor
while ((i < constructors.length) &&
(constructors[i].getParameterTypes().length!=params.length)) {
i++;
}
// constructors[i] is the selected one constructor
Problem problem = (Problem)constructors[i].newInstance(params);
return problem;
}// try
catch(Exception e) {
Configuration.logger_.severe("ProblemFactory.getProblem: " +
"Problem '"+ name + "' does not exist. " +
"Please, check the problem names in jmetal/problems") ;
e.printStackTrace();
throw new JMException("Exception in " + name + ".getProblem()") ;
} // catch
}
}
| gpl-3.0 |
CraftMyWebsite/CMW | admin/donnees/stats.php | 140 | <?php
if($_Joueur_['rang'] == 1) {
$lectureStats = new Lire('modele/config/config.yml');
$lectureStats = $lectureStats->GetTableau();
}
?> | gpl-3.0 |
SmartPromoter/SPromoter-Mobile | SPromoterMobile/Models/Credenciais/API_Credenciais.cs | 421 | //
// API_Credenciais.cs
//
// Author:
// leonardcolusso <>
//
// Copyright (c) 2017
//
using System;
namespace SPromoterMobile.Models.Credenciais
{
[Preserve(AllMembers = true)]
public static class API_Credenciais
{
//TODO: Set links
public static readonly string urlGetInstancia = "";
public static readonly string customMailUserDomain = "@smartpromoter.trade";
}
}
| gpl-3.0 |
matthenning/ciliatus | database/migrations/2017_02_04_161606_create_action_sequence_intentions_table.php | 1162 | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateActionSequenceIntentionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('action_sequence_intentions', function (Blueprint $table) {
$table->uuid('id');
$table->primary('id');
$table->string('name');
$table->uuid('action_sequence_id');
$table->string('type');
$table->string('intention');
$table->integer('minimum_timeout_minutes')->nullable();
$table->time('timeframe_start')->nullable();
$table->time('timeframe_end')->nullable();
$table->timestamp('last_start_at')->nullable()->default(null);
$table->timestamp('last_finished_at')->nullable()->default(null);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('action_sequence_intentions');
}
}
| gpl-3.0 |
frenchtasticeu/coeur | framework/js/customizer-reset.js | 964 | /* global jQuery, _ZoomCustomizerReset, ajaxurl, wp */
jQuery(function ($) {
var $container = $('#customize-header-actions');
var $button = $('<input type="submit" name="zoom-reset" id="zoom-reset" class="button-secondary button">')
.attr('value', _ZoomCustomizerReset.reset)
.css({
'float': 'right',
'margin-right': '10px',
'margin-top': '9px'
});
$button.on('click', function (event) {
event.preventDefault();
var data = {
wp_customize: 'on',
action: 'customizer_reset',
nonce: _ZoomCustomizerReset.nonce.reset
};
var r = confirm(_ZoomCustomizerReset.confirm);
if (!r) return;
$button.attr('disabled', 'disabled');
$.post(ajaxurl, data, function () {
wp.customize.state('saved').set(true);
location.reload();
});
});
$container.append($button);
}); | gpl-3.0 |
eberhardtm/phpwebsitetest | mod/properties/class/Contact.php | 15433 | <?php
namespace Properties;
/**
* See docs/AUTHORS and docs/COPYRIGHT for relevant info.
*
* 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 General Public License for more details.
*
*
* @version $Id$
* @author Matthew McNaney <mcnaney at gmail dot com>
* @package
* @license http://opensource.org/licenses/gpl-3.0.html
*/
class Contact {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public $phone;
public $email_address;
public $company_name;
public $company_address;
public $company_url;
public $times_available;
public $last_log = 0;
public $active = 1;
private $key = null;
public $errors = null;
public function __construct($id = null)
{
if (!$id) {
return;
}
$db = new \PHPWS_DB('prop_contacts');
$db->addWhere('id', (int) $id);
$db->loadObject($this);
}
public function makeKey()
{
$this->key = md5(rand());
}
public function getKey()
{
return $this->key;
}
public function form()
{
javascript('jquery');
javascriptMod('properties', 'generate');
\Layout::addStyle('properties', 'forms.css');
$form = new \PHPWS_Form('contact');
$form->addHidden('module', 'properties');
if (@$this->id) {
$form->addHidden('cid', $this->id);
$form->addSubmit('Update contact');
} else {
$form->addSubmit('Add contact');
}
if (isset($_SESSION['Contact_User']) && !\Current_User::allow('properties')) {
$form->addHidden('cop', 'save_contact');
$form->addHidden('k', $_SESSION['Contact_User']->getKey());
} else {
$form->addHidden('aop', 'save_contact');
$form->addText('username', $this->username);
$form->setLabel('username', 'User name');
$form->setSize('username', '20', '20');
$form->setRequired('username');
$form->addButton('make_password', 'Create');
$form->setId('make_password', 'make-password');
$form->addCheck('contact_contact', 1);
$form->setLabel('contact_contact', 'Send contact email');
if (!$this->id) {
$form->setMatch('contact_contact', 1);
}
}
$form->addPassword('password');
$form->setLabel('password', 'Password');
$form->addPassword('pw_check');
$form->setLabel('pw_check', 'Match');
$form->addText('first_name', $this->first_name);
$form->setLabel('first_name', 'Contact first name');
$form->setRequired('first_name');
$form->addText('last_name', $this->last_name);
$form->setLabel('last_name', 'Contact last name');
$form->setRequired('last_name');
$form->addText('phone', $this->getPhone());
$form->setLabel('phone', 'Phone number');
$form->setRequired('phone');
$form->addText('email_address', $this->email_address);
$form->setLabel('email_address', 'Email address');
$form->setRequired('email_address');
$form->setSize('email_address', 40);
$form->addText('company_name', $this->company_name);
$form->setLabel('company_name', 'Company name');
$form->setRequired('company_name');
$form->setSize('company_name', 40);
$form->addText('company_url', $this->company_url);
$form->setLabel('company_url', 'Company url');
$form->setSize('company_url', 40);
$form->addTextArea('company_address', $this->company_address);
$form->setLabel('company_address', 'Company (or renter) address');
$form->setRows('company_address', 4);
$form->setCols('company_address', 20);
$form->addTextArea('times_available', $this->times_available);
$form->setLabel('times_available',
'Days and hours available for contact');
$form->setRows('times_available', 4);
$form->setCols('times_available', 20);
$tpl = $form->getTemplate();
if (!empty($this->errors)) {
foreach ($this->errors as $key => $message) {
$new_key = strtoupper($key) . '_ERROR';
$tpl[$new_key] = $message;
}
}
return \PHPWS_Template::process($tpl, 'properties', 'edit_contact.tpl');
}
public function post()
{
$vars = array_keys(get_object_vars($this));
foreach ($_POST as $key => $value) {
if ($key == 'password') {
// new contacts must have a password
if (!$this->id) {
if (empty($_POST['password'])) {
$this->errors['password'] = 'New contacts must be given a password';
continue;
}
}
if (!empty($_POST['pw_check']) || !empty($_POST['password'])) {
if ($_POST['pw_check'] == $_POST['password']) {
$this->setPassword($_POST['password']);
} else {
$this->errors['password'] = 'Passwords must must match';
}
}
continue;
}
if ($key == 'pw_check') {
continue;
}
if (in_array($key, $vars)) {
$func = 'set' . str_replace(' ', '',
ucwords(str_replace('_', ' ', $key)));
try {
$this->$func($value);
} catch (\Exception $e) {
$this->errors[$key] = $e->getMessage();
}
}
}
return !isset($this->errors);
}
public function setUsername($username)
{
if (empty($username)) {
throw new \Exception('User name may not be blank');
}
if (strlen($username) < 3) {
throw new \Exception('User name must be more than 3 characters');
}
if (preg_match('/\W]/', $username)) {
throw new \Exception('User name may contain alphanumeric characters only');
}
// check for duplicate user names
$db = new \PHPWS_DB('prop_contacts');
$db->addWhere('username', $username);
$db->addColumn('id');
$result = $db->select('one');
if (\PHPWS_Error::isError($result)) {
\PHPWS_Error::log($result);
throw new \Exception('A database error occurred. Contact the site administrator');
}
// if an id is found (user name in use) and this is a new user OR the result id
// is not equal to the current contact id, then throw a duplicate warning
if ($result && (!$this->id || ($this->id != $result))) {
throw new \Exception('This user name is already in use, please choose another');
}
$this->username = $username;
}
public function setCompanyUrl($url)
{
if (empty($url)) {
return;
}
if (!\PHPWS_Text::isValidInput($url, 'url')) {
throw new \Exception('Improperly formatted url');
}
$this->company_url = strip_tags(trim($url));
}
public function setPassword($password)
{
$this->password = md5($password);
}
public function setFirstName($first_name)
{
if (empty($first_name)) {
throw new \Exception('First name may not be blank');
}
if (preg_match('/[^a-z\s\']/i', $first_name)) {
throw new \Exception('May only contain alphabetical characters');
}
$this->first_name = ucwords($first_name);
}
public function setLastName($last_name)
{
if (empty($last_name)) {
throw new \Exception('Last name may not be blank');
}
if (preg_match('/[^a-z\s\']/i', $last_name)) {
throw new \Exception('May only contain alphabetical characters');
}
$this->last_name = ucwords($last_name);
}
public function setPhone($phone)
{
if (empty($phone)) {
$this->phone = null;
return true;
}
$phone = trim((string) preg_replace('/[^\d]/', '', $phone));
if (strlen($phone) != 10) {
throw new \Exception('Phone number must be 10 digits');
}
$this->phone = $phone;
}
public function setEmailAddress($email_address)
{
if (empty($email_address)) {
$this->email_address = null;
return true;
}
if (!\PHPWS_Text::isValidInput($email_address, 'email')) {
throw new \Exception('Improperly formatted email');
}
$this->email_address = $email_address;
}
public function setCompanyName($company_name)
{
$this->company_name = ucwords(strip_tags($company_name));
}
public function setCompanyAddress($company_address)
{
$this->company_address = strip_tags($company_address);
}
public function setTimesAvailable($times_available)
{
$this->times_available = strip_tags($times_available);
}
public function getUsername()
{
return $this->username;
}
private function getPassword()
{
return $this->password;
}
public function getFirstName()
{
return $this->first_name;
}
public function getLastName()
{
return $this->last_name;
}
public function getPhone()
{
if (empty($this->phone)) {
return null;
}
return sprintf('(%s) %s-%s', substr($this->phone, 0, 3),
substr($this->phone, 3, 3), substr($this->phone, 6));
}
public function getEmailAddress($html = false)
{
if ($html) {
return sprintf('<a href="mailto:%s">%s</a>', $this->email_address,
$this->email_address);
} else {
return $this->email_address;
}
}
public function getCompanyName()
{
return $this->company_name;
}
public function getCompanyUrl()
{
if (!empty($this->company_url)) {
return '<a target="_blank" href="' . $this->company_url . '">' . $this->company_name . '</a>';
} else {
return $this->company_name;
}
}
public function getCompanyAddress()
{
return nl2br($this->company_address);
}
public function getTimesAvailable()
{
return nl2br($this->times_available);
}
public function save()
{
$db = new \PHPWS_DB('prop_contacts');
$result = $db->saveObject($this);
if (\PEAR::isError($result)) {
\PHPWS_Error::log($result);
throw new \Exception('Could not save contact to the database.');
}
return true;
}
public function row_tags()
{
$tpl['LAST_NAME'] = sprintf('<a href="mailto:%s">%s, %s <i class="fa fa-envelope-o"></i></a>',
$this->email_address, $this->last_name, $this->first_name);
$tpl['PHONE'] = $this->getPhone();
$tpl['COMPANY_NAME'] = $this->getCompanyUrl();
if ($this->active) {
$admin[] = \PHPWS_Text::secureLink(\Icon::show('active',
'Click to deactivate'), 'properties',
array('aop' => 'deactivate_contact', 'cid' => $this->id));
} else {
$admin[] = \PHPWS_Text::secureLink(\Icon::show('inactive',
'Click to activate'), 'properties',
array('aop' => 'activate_contact', 'cid' => $this->id));
}
$admin[] = \PHPWS_Text::secureLink(\Icon::show('add'), 'properties',
array('aop' => 'edit_property', 'cid' => $this->id));
$admin[] = \PHPWS_Text::secureLink(\Icon::show('edit'), 'properties',
array('aop' => 'edit_contact', 'cid' => $this->id));
$js['LINK'] = \Icon::show('delete');
$js['QUESTION'] = 'Are you sure you want to delete this contact and all their properties?';
$js['ADDRESS'] = 'index.php?module=properties&aop=delete_contact&cid=' . $this->id . '&authkey=' . \Current_User::getAuthKey();
$admin[] = javascript('confirm', $js);
$admin[] = \PHPWS_Text::secureLink(\Icon::show('home', 'Show properties'),
'properties',
array('aop' => 'show_properties', 'cid' => $this->id));
if ($this->last_log) {
$tpl['LAST_LOG'] = strftime('%x', $this->last_log);
} else {
$tpl['LAST_LOG'] = 'Never';
}
$tpl['ACTION'] = implode('', $admin);
return $tpl;
}
public function delete()
{
if (!$this->id) {
throw new \Exception('Missing contact id');
}
$c_db = new \PHPWS_DB('prop_contacts');
$c_db->addWhere('id', $this->id);
$result = $c_db->delete();
if (\PEAR::isError($result)) {
\PHPWS_Error::log($result);
throw new \Exception('Could not delete contact from database.');
}
$p_db = new \PHPWS_DB('properties');
$p_db->addWhere('contact_id', $this->id);
$result = $p_db->delete();
if (\PEAR::isError($result)) {
\PHPWS_Error::log($result);
throw new \Exception('Could not delete contact properties from database.');
}
$i_db = new \PHPWS_DB('prop_photo');
$i_db->addWhere('cid', $this->id);
$result = $i_db->delete();
if (\PEAR::isError($result)) {
\PHPWS_Error::log($result);
throw new \Exception('Could not delete contact photos from database.');
}
$dir = 'images/properties/c' . $this->id;
@rmdir($dir);
return true;
}
public function setActive($active)
{
$this->active = (bool) $active;
}
public function loginMenu()
{
$vars['k'] = $this->key;
$vars['cop'] = 'edit_property';
$tpl['CREATE'] = \PHPWS_Text::moduleLink('Create property',
'properties', $vars);
$vars['cop'] = 'view_properties';
$tpl['VIEW'] = \PHPWS_Text::moduleLink('View properties', 'properties',
$vars);
$vars['cop'] = 'edit_contact';
$tpl['EDIT'] = \PHPWS_Text::moduleLink('Edit my information',
'properties', $vars);
$vars['cop'] = 'logout';
$tpl['LOGOUT'] = \PHPWS_Text::moduleLink('Logout', 'properties', $vars);
$content = \PHPWS_Template::process($tpl, 'properties',
'mini_contact.tpl');
\Layout::add($content, 'properties', 'contact_login');
}
public function checkKey()
{
return @$_REQUEST['k'] == $this->key;
}
}
?> | gpl-3.0 |
annoviko/pyclustering | ccore/src/cluster/bsas.cpp | 2015 | /*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#include <pyclustering/cluster/bsas.hpp>
namespace pyclustering {
namespace clst {
bsas::bsas(const std::size_t p_amount,
const double p_threshold,
const distance_metric<point> & p_metric) :
m_threshold(p_threshold),
m_amount(p_amount),
m_metric(p_metric)
{ }
void bsas::process(const dataset & p_data, bsas_data & p_result) {
m_result_ptr = &p_result;
cluster_sequence & clusters = m_result_ptr->clusters();
representative_sequence & representatives = m_result_ptr->representatives();
clusters.push_back({ 0 });
representatives.push_back( p_data[0] );
for (std::size_t i = 1; i < p_data.size(); i++) {
auto nearest = find_nearest_cluster(p_data[i]);
if ( (nearest.m_distance > m_threshold) && (clusters.size() < m_amount) ) {
representatives.push_back(p_data[i]);
clusters.push_back({ i });
}
else {
clusters[nearest.m_index].push_back(i);
update_representative(nearest.m_index, p_data[i]);
}
}
}
bsas::nearest_cluster bsas::find_nearest_cluster(const point & p_point) const {
bsas::nearest_cluster result;
for (std::size_t i = 0; i < m_result_ptr->clusters().size(); i++) {
double distance = m_metric(p_point, m_result_ptr->representatives()[i]);
if (distance < result.m_distance) {
result.m_distance = distance;
result.m_index = i;
}
}
return result;
}
void bsas::update_representative(const std::size_t p_index, const point & p_point) {
auto len = static_cast<double>(m_result_ptr->clusters().size());
auto & rep = m_result_ptr->representatives()[p_index];
for (std::size_t dim = 0; dim < rep.size(); dim++) {
rep[dim] = ( (len - 1) * rep[dim] + p_point[dim] ) / len;
}
}
}
} | gpl-3.0 |
sunlightlabs/foia-data | new/new-more/foia-master/contacts/layer_with_manual_data.py | 475 | #!/usr/bin/env python
import yaml
import scraper
def layer_manual_data(agency_abbr):
filename = scraper.agency_yaml_filename('data', agency_abbr)
with open(filename, 'r') as f:
print(filename)
agency_data = yaml.load(f)
data = scraper.apply_manual_data(agency_abbr, agency_data)
scraper.save_agency_data(agency_abbr, data)
if __name__ == "__main__":
for agency_abbr in scraper.AGENCIES:
layer_manual_data(agency_abbr)
| gpl-3.0 |
lygaret/webcapture | backend/spec/controllers/authentication_spec.rb | 2921 | require "rails_helper"
describe API::Authentication, type: :controller do
controller(ActionController::Base) do
include API::Authentication
def unauthenticated
head status: 204
end
def authenticated
require_user!
head status: 204
end
def authenticate
initiate_session params["uid"]
render text: current_user.id, status: 201
end
def scoped
require_scope! :special
head status: 204
end
end
before do
routes.draw do
get ":controller/:action"
post ":controller/:action"
end
end
context "unauthenticated" do
it "should allow unauthenticated stuff" do
get :unauthenticated
expect(response).to have_http_status(204)
end
it "#require_user!" do
bypass_rescue
expect { get :authenticated }.to raise_error(API::UnauthorizedError)
end
it "#require_scope!" do
bypass_rescue
expect { get :scoped }.to raise_error(API::UnauthorizedError)
end
it "should allow authenticating a user" do
user = create(:user, password: "secret")
post :authenticate, uid: user.id
expect(response).to have_http_status(201)
expect(response.body).to eq(user.id.to_s)
expect(session[:user_id]).to eq(user.id.to_s)
end
end
context "authentication" do
let(:user) { create(:user, password: "secret") }
it "should allow authenticating via session" do
session[:user_id] = user.id
# should be authenticated,
# session authentication gets all scopes by default
get :scoped
expect(response).to have_http_status(204)
end
it "should allow authenticating via basic auth" do
basic_auth(user.email, "secret")
# should be authenticated
# basic authentication gets all scopes by default
# session should not include user_id, we don't want to get a session for basic auth
get :scoped
expect(response).to have_http_status(204)
expect(session.keys).to be_empty
end
it "should allow authenticating via token" do
jwt_auth(user, [:any])
# should be authenticated
# no session generated for token user
get :scoped
expect(response).to have_http_status(204)
expect(session.keys).to be_empty
end
end
context "scope" do
let :user do
create(:user, password: "secret")
end
it "should disallow if missing the named scope" do
session_auth(user, [:not_special])
bypass_rescue
expect { get :scoped }.to raise_error(API::AccessDeniedError)
end
it "should allow if I have the named scope" do
session_auth(user, [:not_special, :special])
get :scoped
expect(response).to have_http_status(204)
end
it "should allow if I have the :any scope" do
session_auth(user)
get :scoped
expect(response).to have_http_status(204)
end
end
end
| gpl-3.0 |
Starfys/ss-advent-solutions | C++/day14/advent14.1.cpp | 2340 | //Solves the first problem in the fourteenth pair of advent of code problems
//Copyright 2015 Steven Sheffey
/*
This file is part of ss-advent-solutions
ss-advent-solutions 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.
ss-advent-solutions 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 ss-advent-solutions. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
class Reindeer
{
public:
Reindeer(unsigned int initFlySpeed, unsigned int initFlyTime, unsigned int initRestTime):
m_FlySpeed(initFlySpeed), m_FlyTime(initFlyTime), m_RestTime(initRestTime),
m_RemainingFlyTime(initFlyTime), m_RemainingRestTime(0), m_DistanceFlown(0)
{
}
void act()
{
if(m_RemainingRestTime > 0)
{
--m_RemainingRestTime;
if(m_RemainingRestTime == 0)
{
m_RemainingFlyTime = m_FlyTime;
}
return;
}
if(m_RemainingFlyTime > 0)
{
m_DistanceFlown += m_FlySpeed;
--m_RemainingFlyTime;
if(m_RemainingFlyTime == 0)
{
m_RemainingRestTime = m_RestTime;
}
return;
}
}
unsigned int getDistanceFlown()
{
return m_DistanceFlown;
}
private:
unsigned int m_FlySpeed;
unsigned int m_FlyTime;
unsigned int m_RestTime;
unsigned int m_RemainingFlyTime;
unsigned int m_RemainingRestTime;
unsigned int m_DistanceFlown;
};
static const unsigned int raceTime = 2503;
int main()
{
Reindeer comet(14, 10, 127);
Reindeer dancer(16, 11, 162);
for(int curTime = 0; curTime < raceTime; ++curTime)
{
comet.act();
dancer.act();
}
printf("Comet: %u km\n"
"Dancer: %u km\n",
comet.getDistanceFlown(),
dancer.getDistanceFlown());
}
| gpl-3.0 |
vincentcasseau/hyStrath | src/lagrangian/dsmc/initialiseDsmcParcels/derived/dsmcLaserHeatingFill/dsmcLaserHeatingFill.C | 9191 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2016-2021 hyStrath
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of hyStrath, a derivative work of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
\*---------------------------------------------------------------------------*/
#include "dsmcLaserHeatingFill.H"
#include "addToRunTimeSelectionTable.H"
#include "IFstream.H"
#include "graph.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(dsmcLaserHeatingFill, 0);
addToRunTimeSelectionTable(dsmcConfiguration, dsmcLaserHeatingFill, dictionary);
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from components
dsmcLaserHeatingFill::dsmcLaserHeatingFill
(
dsmcCloud& cloud,
const dictionary& dict
// const word& name
)
:
dsmcConfiguration(cloud, dict),
r0_(0.0),
deltaT_(0.0),
centrePoint_(vector::zero)
{
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
dsmcLaserHeatingFill::~dsmcLaserHeatingFill()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void dsmcLaserHeatingFill::setInitialConfiguration()
{
Info<< nl << "Initialising particles" << endl;
// const scalar translationalTemperature
// (
// readScalar(dsmcInitialiseDict_.lookup("translationalTemperature"))
// );
//
// const scalar rotationalTemperature
// (
// readScalar(dsmcInitialiseDict_.lookup("rotationalTemperature"))
// );
//
// const scalar vibrationalTemperature
// (
// readScalar(dsmcInitialiseDict_.lookup("vibrationalTemperature"))
// );
//
// const scalar electronicTemperature
// (
// readScalar(dsmcInitialiseDict_.lookup("electronicTemperature"))
// );
const vector velocity(dsmcInitialiseDict_.lookup("velocity"));
r0_ = readScalar((dsmcInitialiseDict_.lookup("r0")));
centrePoint_ = (dsmcInitialiseDict_.lookup("centrePoint"));
deltaT_ = readScalar((dsmcInitialiseDict_.lookup("axialTemperature")));
const dictionary& numberDensitiesDict
(
dsmcInitialiseDict_.subDict("numberDensities")
);
List<word> molecules(numberDensitiesDict.toc());
Field<scalar> numberDensities(molecules.size());
forAll(molecules, i)
{
numberDensities[i] = readScalar
(
numberDensitiesDict.lookup(molecules[i])
);
}
//numberDensities /= cloud_.nParticles();
const cellZoneMesh& cellZones = mesh_.cellZones();
const word regionName(dsmcInitialiseDict_.lookup("zoneName"));
label zoneId = cellZones.findZoneID(regionName);
if(zoneId == -1)
{
FatalErrorIn("dsmcLaserHeatingFill::setInitialConfiguration()")
<< "Cannot find region: " << regionName << nl << "in: "
<< mesh_.time().system()/"dsmcInitialiseDict"
<< exit(FatalError);
}
const cellZone& zone = cellZones[zoneId];
if (zone.size())
{
Info << "Lattice in zone: " << regionName << endl;
forAll(zone, c)
{
const label& cellI = zone[c];
List<tetIndices> cellTets = polyMeshTetDecomposition::cellTetIndices
(
mesh_,
cellI
);
const scalar& cellCentreI = mag(mesh_.cellCentres()[cellI] - centrePoint_);
const scalar& cellCentreY = mesh_.cellCentres()[cellI].y();
scalar cellTemperature = deltaT_*exp(-1.0*pow(cellCentreY/r0_,2.0));
const scalar& cellCentreX = mesh_.cellCentres()[cellI].x();
cellTemperature *= (0.0218 - cellCentreX)/0.0036;
forAll(cellTets, tetI)
{
const tetIndices& cellTetIs = cellTets[tetI];
tetPointRef tet = cellTetIs.tet(mesh_);
scalar tetVolume = tet.mag();
forAll(molecules, i)
{
const word& moleculeName(molecules[i]);
label typeId(findIndex(cloud_.typeIdList(), moleculeName));
if (typeId == -1)
{
FatalErrorIn("Foam::dsmcCloud<dsmcParcel>::initialise")
<< "typeId " << moleculeName << "not defined." << nl
<< abort(FatalError);
}
const dsmcParcel::constantProperties& cP = cloud_.constProps(typeId);
scalar numberDensity = numberDensities[i];
// Calculate the number of particles required
scalar particlesRequired = numberDensity*tetVolume;
particlesRequired /= cloud_.nParticles(cellI);
// Only integer numbers of particles can be inserted
label nParticlesToInsert = label(particlesRequired);
// Add another particle with a probability proportional to the
// remainder of taking the integer part of particlesRequired
if
(
(particlesRequired - nParticlesToInsert)
> rndGen_.sample01<scalar>()
)
{
nParticlesToInsert++;
}
for (label pI = 0; pI < nParticlesToInsert; pI++)
{
point p = tet.randomPoint(rndGen_);
vector U = cloud_.equipartitionLinearVelocity
(
cellTemperature,
cP.mass()
);
scalar ERot = cloud_.equipartitionRotationalEnergy
(
cellTemperature,
cP.rotationalDegreesOfFreedom()
);
labelList vibLevel = cloud_.equipartitionVibrationalEnergyLevel
(
cellTemperature,
cP.nVibrationalModes(),
typeId
);
label ELevel = cloud_.equipartitionElectronicLevel
(
cellTemperature,
cP.electronicDegeneracyList(),
cP.electronicEnergyList()
);
U += velocity;
label newParcel = -1;
label classification = 0;
const scalar& RWF = cloud_.coordSystem().RWF(cellI);
cloud_.addNewParcel
(
p,
U,
RWF,
ERot,
ELevel,
cellI,
cellTetIs.face(),
cellTetIs.tetPt(),
typeId,
newParcel,
classification,
vibLevel
);
}
}
}
}
}
// Initialise the sigmaTcRMax_ field to the product of the cross section of
// the most abundant species and the most probable thermal speed (Bird,
// p222-223)
label mostAbundantType(findMax(numberDensities));
const dsmcParcel::constantProperties& cP = cloud_.constProps
(
mostAbundantType
);
forAll(zone, c)
{
const label& cellI = zone[c];
const scalar& cellCentreI = mag(mesh_.cellCentres()[cellI] - centrePoint_);
scalar cellTemperature = deltaT_*exp(-1.0*sqr(cellCentreI/r0_));
cloud_.sigmaTcRMax().primitiveFieldRef()[cellI] = cP.sigmaT()*cloud_.maxwellianMostProbableSpeed
(
cellTemperature,
cP.mass()
);
}
cloud_.sigmaTcRMax().correctBoundaryConditions();
}
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
redpen-cc/redpen-wordpress-plugin | js/plugin.js | 7008 | function RedPenPlugin(proxyUrl) {
var pub = this;
var $ = jQuery;
var ed = pub.editor = new RedPenEditor();
var title = $('.redpen-title');
var manualLanguage;
if (window.redpen) {
redpen.setBaseUrl(proxyUrl);
initRedPens().then(populateLanguages);
}
else {
title.text('Server is not available. Make sure the correct URL is configured in Settings > Writing > RedPen Server');
}
var lastXhr;
$(document).ajaxSend(function(event, jqxhr, settings) {
if (settings.url == proxyUrl + 'rest/document/validate/json') {
if (lastXhr) lastXhr.abort();
lastXhr = jqxhr;
}
});
pub.validate = function() {
ed.clearErrors();
var text = ed.getDocumentText();
var container = $('.redpen-error-list');
chooseLanguage(text, function(langKey) {
if (!manualLanguage) $('#redpen-language').val(langKey);
pub.renderConfiguration(pub.redpens[langKey]);
var config = prepareConfigForValidation(langKey);
var args = {config:config, document:text, format:'json2'};
redpen.validateJSON(args, function(result) {
container.empty();
var index = 0;
var cursorPos = ed.getCursorPos();
$.each(result.errors, function(i, error) {
$.each(error.errors, function(j, suberror) {
suberror.index = ++index;
var errorNodes = ed.highlightError(suberror);
var message = $('<li class="redpen-error-message"></li>').text(suberror.message)
.appendTo(container)
.on('click', function() {ed.showErrorInText(suberror, errorNodes);});
$('<div class="redpen-error-validator"></div>')
.text(suberror.validator)
.appendTo(message);
});
});
ed.setCursorPos(cursorPos);
title.text('found ' + container.children().length + ' errors');
});
});
};
function chooseLanguage(text, callback) {
if (manualLanguage) callback(manualLanguage);
else redpen.detectLanguage(text, callback);
}
function initRedPens() {
if (localStorage.redpens) {
pub.redpens = JSON.parse(localStorage.redpens);
return $.Deferred().resolve(pub.redpens);
}
else {
return loadDefaultConfiguration();
}
}
function loadDefaultConfiguration() {
var deferred = $.Deferred();
redpen.getRedPens(function (result) {
pub.redpens = result.redpens;
onConfigurationChange();
deferred.resolve(pub.redpens);
});
return deferred;
}
function onConfigurationChange() {
localStorage.redpens = JSON.stringify(pub.redpens);
if (pub.validate) pub.validate();
}
function populateLanguages() {
var select = $('#redpen-language').empty();
$.each(pub.redpens, function(lang) {
select.append('<option>' + lang + '</option>');
});
select.on('change', function() {
manualLanguage = select.val();
onConfigurationChange();
});
}
pub._prepareConfigForValidation = prepareConfigForValidation;
function prepareConfigForValidation(langKey) {
var validators = {};
var config = pub.redpens[langKey];
$.each(config.validators, function(name, options) {
if (!options.disabled)
validators[name] = options;
});
return {lang: config.lang, validators: validators, symbols: config.symbols};
}
pub.resetConfiguration = function() {
loadDefaultConfiguration();
};
pub.autoValidate = function(what, switchSelector) {
var lastText, lastKeyUp;
function validateOnKeyUp() {
clearTimeout(lastKeyUp);
lastKeyUp = setTimeout(function() {
var text = ed.getDocumentText();
if (text != lastText) {
pub.validate();
lastText = text;
}
}, 500);
}
ed.switchTo(what);
ed.onChange(validateOnKeyUp);
$(switchSelector).on('click', function() {
ed.switchTo(what);
pub.validate();
});
return pub;
};
pub.renderConfiguration = function(config) {
var validatorContainer = $('.redpen-validators').empty();
var symbolContainer = $('.redpen-symboltable tbody').empty();
$.each(config.validators || [], function(name, options) {
var element = $('<li><label><input type="checkbox" value="' + name + '">' + name + '</label></li>').appendTo(validatorContainer);
var checkbox = element.find(':checkbox').on('change', function() {
config.validators[name].disabled = !this.checked;
onConfigurationChange();
});
checkbox.attr('checked', !options.disabled);
$.each(options.languages || [], function(i, lang) {
element.append('<i> ' + lang + '</i>');
});
var properties = $('<ul class="redpen-validator-properties"></ul>').appendTo(element);
$.each(options.properties || [], function(key, value) {
$('<li></li>').text(key + '=' + value).appendTo(properties);
});
if ($.isEmptyObject(options.properties)) {
$('<li></li>').text('+').appendTo(properties);
}
properties.children().on('click', function() {editValidatorProperties(name, options, $(this))});
});
$.each(config.symbols || [], function(name, options) {
var row = $('<tr></tr>').appendTo(symbolContainer);
$('<td></td>').text(name).appendTo(row);
$('<td class="redpen-symbol-value"></td>').text(options.value).appendTo(row);
$('<td class="redpen-symbol-invalid"></td>').text(options.invalid_chars).appendTo(row);
$('<td><input type="checkbox" name="' + name + '" value="before_space" ' + (options.before_space ? 'checked' : '') + '></td>').appendTo(row);
$('<td><input type="checkbox" name="' + name + '" value="after_space" ' + (options.after_space ? 'checked' : '') + '></td>').appendTo(row);
row.find(':checkbox').on('change', function() {
config.symbols[name][this.value] = this.checked;
onConfigurationChange();
});
row.find('.redpen-symbol-value').on('click', function() {editSymbol(name, 'value', options, $(this))});
row.find('.redpen-symbol-invalid').on('click', function() {editSymbol(name, 'invalid_chars', options, $(this))});
});
};
function editValidatorProperties(name, options, propertyElement) {
var keyvalue = propertyElement.text();
keyvalue = prompt(name, keyvalue.indexOf('=') > 0 ? keyvalue : '');
if (keyvalue === null) return;
keyvalue = keyvalue.trim();
var parts = keyvalue.split('=', 2);
if (parts.length != 2) {
alert(keyvalue + ': invalid property, must be in "key=value" form');
}
else {
options.properties[parts[0]] = parts[1];
propertyElement.text(keyvalue);
onConfigurationChange();
}
}
function editSymbol(name, key, options, propertyElement) {
var value = propertyElement.text();
value = prompt(name, value);
if (value === null) return;
value = value.trim();
options[key] = value;
propertyElement.text(value);
onConfigurationChange();
}
}
| gpl-3.0 |
force4win/JSFBootstrap | MavenJSFBootstrap/src/com/alv/base/classes/PercentItem.java | 1364 | package com.alv.base.classes;
import java.io.Serializable;
public class PercentItem implements Serializable {
private static final long serialVersionUID = -533697522712282382L;
private String encabezado;
private String label;
private String value;
private String totalValue;
private String unitOfValue;
@SuppressWarnings("unused")
private PercentItem(){}
public PercentItem(String encabezado, String label, String value, String totalValue, String unitOfValue){
this.encabezado = encabezado;
this.label = label;
this.value = value;
this.totalValue = totalValue;
this.unitOfValue = unitOfValue;
}
public String getEncabezado() {
return encabezado;
}
public void setEncabezado(String encabezado) {
this.encabezado = encabezado;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getTotalValue() {
return totalValue;
}
public void setTotalValue(String totalValue) {
this.totalValue = totalValue;
}
public String getUnitOfValue() {
return unitOfValue;
}
public void setUnitOfValue(String unitOfValue) {
this.unitOfValue = unitOfValue;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| gpl-3.0 |
cdeil/gammalib | test/test_GXml.py | 1736 | # ==========================================================================
# This module performs unit tests for the GammaLib xml module.
#
# Copyright (C) 2012 Juergen Knoedlseder
#
# 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/>.
#
# ==========================================================================
from gammalib import *
from math import *
import os
# ================================== #
# Test class for GammaLib xml module #
# ================================== #
class Test(GPythonTestSuite):
"""
Test class for GammaLib xml module.
"""
# Constructor
def __init__(self):
"""
Constructor.
"""
# Call base class constructor
GPythonTestSuite.__init__(self)
# Return
return
# Set test functions
def set(self):
"""
Set all test functions.
"""
# Set test name
self.name("xml")
# Append tests
self.append(self.test, "XML module dummy test")
# Return
return
# Test function
def test(self):
"""
Test function.
"""
# Return
return
| gpl-3.0 |
lsaruwat/cmu_slider | saveKey.php | 806 | <?php
session_start();
include("db/connect.php"); // this connects to the cmu_slider db so we can query it
$pageTitle = "save key";
include("header.php");
if($_SESSION['permissions'] === "superuser"){
?>
<!-- Main Content Begin -->
<div class="container">
<form id="create_key">
<div class="row">
<div class="six columns">
<label for="key">Key</label>
<input type="password" name="key" id="key" class="u-full-width"/>
</div>
<div class="six columns">
<label for="key_confirm">Confirm key</label>
<input type="password" name="key_confirm" id="key_confirm" class="u-full-width"/>
</div>
</div>
<div class="row">
<input type="submit" class="u-full-width button-primary"/>
</div>
</form>
</div>
<!-- Main Content End -->
<?php
}
//endif
include("footer.php");
?>
| gpl-3.0 |
arximboldi/jpblib | jpb/signal.py | 12336 | # -*- coding: utf-8 -*-
#
# File: signal.py
# Author: Juan Pedro Bolívar Puente <raskolnikov@es.gnu.org>
# Date: 2009
# Time-stamp: <2012-01-20 20:19:01 jbo>
#
#
# Copyright (C) 2012 Juan Pedro Bolívar Puente
#
# This file is part of jpblib.
#
# jpblib 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.
#
# jpblib 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 module provides a slot-signal mechanism.
"""
from connection import *
from sender import *
from util import *
from meta import *
from proxy import *
import weakref
from functools import wraps
class Slot (Destiny):
"""
A slot is the endpoint of a connection to a signal.
"""
def __init__ (self, func = None, *a, **k):
"""
Constructor.
Parameters:
- func: The function to be invoked by this slot.
"""
super (Slot, self).__init__ (*a, **k)
self.func = func
def __call__ (self, *args, **kw):
"""
Invokes the function associated to this slot with the given
arguments.
"""
return self.func (*args, **kw)
def do_notify (self, *args, **kw):
return True, self.func (*args, **kw)
class WeakSlot (Slot):
def __init__ (self, obj = None, method = None, *a, **k):
"""
Constructor.
Parameters:
- func: The function to be invoked by this slot.
"""
super (WeakSlot, self).__init__ (*a, **k)
self.obj = weakref.ref (obj)
self.method = method
def __call__ (self, *args, **kw):
"""
Invokes the function associated to this slot with the given
arguments.
"""
return self.method (self.obj (), *args, **kw)
def do_notify (self, *args, **kw):
"""
Invokes the function associated to this slot with the given
arguments.
"""
if self.obj ():
return True, self.method (self.obj (), *args, **kw)
return False, None
class Signal (Container):
"""
This is an event emiter that can be used to remotelly invoke other
functions, as an instance of the Observer design pattern.
"""
def connect (self, slot):
"""
This method registers the Slot 'slot' into the signal. If
'slot' is not a Slot but it is a callable it wraps the
callable in a Slot. The registered slot is returned. The
signal works as a list so the new slot will be called after
all the previously connected slots.
"""
if not isinstance (slot, Slot):
slot = Slot (slot)
return super (Signal, self).connect (slot)
def disconnect (self, slot):
"""
This method disconnects the Slot 'slot' from the signal. If the
passed argument is not a Slot but a function, it disconnects
all the slots that wrap that function.
"""
if isinstance (slot, Slot):
super (Signal, self).disconnect (slot)
else:
super (Signal, self).disconnect_if (lambda x: x.func == slot)
def _notify_one (self, slot, *a, **k):
remain, ret = slot.do_notify (*a, **k)
if not remain:
super (Signal, self).disconnect (slot)
return remain, ret
def notify (self, *a, **k):
"""
Invokes with the arguments passed to this function to all the
slots that are connected to this signal.
"""
destinies = list (self._destinies)
f = self._notify_one
for x in destinies:
f (x, *a, **k)
def fold (self, folder, start = None, *a, **k):
"""
Invokes all the connected signal accumulating the result with
the given 'folder', that will be called on every new
invocation. The final result provided by the folder will be
returned after that, or 'start' if no slot was invoked.
Parameters:
- folder: Binary function that merges to values values into
one. The first parameter is the result returned by folder
in the last call.
- start: By default this is None. If 'start' is not None, it
will be treated as a slot return value that is previous to
any slot in the signal.
Note: A good idiom is to use acumulator objects as the folder
function. To do this use the unbounded method that you will
use to accumulate the values as 'folder' and pass the
acummulator instance as 'start'.
"""
destinies = list (self._destinies)
f = self._notify_one
ix = 0
if start is None:
remain = False
while not remain and ix < len (destinies):
remain, start = f (destinies [ix], *a, **k)
ix += 1
ac = start
while ix < len (destinies):
remain, acnew = f (destinies [ix], *a, **k)
if remain:
ac = folder (ac, acnew)
ix += 1
return ac
def __iadd__ (self, slot):
"""
Same as 'connect'.
"""
self.connect (slot)
return self
def __isub__ (self, slot):
"""
Same as 'disconnect'.
"""
self.disconnect (slot)
return self
def __call__ (self, *args, **kw):
"""
Same as 'notify'.
"""
return self.notify (*args, **kw)
class AutoSignalSender (Sender):
"""
This can be used to map signals to messages of a sender. The
intended usage of this is to inherit from this class when you want
an object to be both a sender.Sender and contain several signals as
attributes. Whenever you create a signal in your subclass this
will substitute it by a proxy that invoques the 'send' method of
the object whenever it is notified, using the attribute name as
message. This allows, for example, the easy creation of forwarders
that re-emit the signals if you also inherit from sender.Receiver.
"""
def __setattr__ (self, name, attr):
"""
Used to inspect every attribute of the object whe it is
set. If it is a Signal it substitutes the set signal with a
proxy.
"""
if isinstance (attr, Signal):
object.__setattr__ (self, name,
SenderSignalProxy (attr, self, name))
else:
object.__setattr__ (self, name, attr)
return attr
class AutoSignalSenderGet (Sender):
"""
Same as 'AutoSignalSender' but implemented in a different way that
may incurr in more overhead.
"""
def __getattribute__ (self, name):
"""
Used to inspect any attribute of the object at retrieval time,
returning a proxy if it was a Signal.
"""
attr = object.__getattribute__ (self, name)
if isinstance (attr, Signal):
return SenderSignalProxy (attr, self, name)
return attr
class SenderSignal (Signal):
"""
This signal is modified such that it replies all the notifications
to a given sender.Sender.
"""
def __init__ (self, sender, message):
"""
Constructor.
Parameters:
- sender: The sender.Sender instance to which this signal
should notify about its invocation.
- message: The message name that will be sent to the sender
when notified.
"""
super (SenderSignal, self).__init__ ()
self._sender = sender
self._message = message
def notify (self, *args, **kws):
"""
Behaves like Signal.notify() but also sends a message through
the registered sender after calling the slots.
"""
super (SenderSignal, self).notify (self, *args, **kws)
self._sender.send (self._message, *args, **kws)
class SenderSignalProxy (AutoProxy):
"""
This proxies a Signal adding the features of SenderSignal to it.
"""
def __init__ (self, signal, sender, message):
"""
Constructor.
Parameters:
- signal: The signal to proxy.
- sender: The sender.Sender instance to which this signal
should notify about its invocation.
- message: The message name that will be sent to the sender
when notified.
"""
super (SenderSignalProxy, self).__init__ (signal)
self._sender = sender
self._message = message
def __call__ (self, *args, **kws):
"""
Class notify.
"""
self.notify (*args, **kws)
def notify (self, *args, **kws):
"""
Invokes the notify method in the proxy but also sends the
message to the registered sender with the given arguments.
"""
self.proxied.notify (*args, **kws)
self._sender.send (self._message, *args, **kws)
@instance_decorator
def slot (obj, func):
"""
This decorator is to be used only with instance methods. When you
decorate a method with this, it will become an instance of a mixin
of connection.Trackable and Slot. Also, if the object this method
belongs to inherits from connection.Tracker, then the slot will be
automatically registered to it. This is very usefull when you want
to use a method mainly to receive signals and want tracking
capabilities so you don't have to keep reference to the signals on
your own. Still, you can use the method as normally after
decorated by this.
"""
s = mixin (Trackable, Slot) (lambda *a, **k: func (obj, *a, **k))
if isinstance (obj, Tracker):
obj.register_trackable (s)
return s
weak_slot = instance_decorator (WeakSlot)
@instance_decorator
def signal (obj, func):
"""
This decorator is to be used only with instance methods. When you
decorate a method with this, it well become into a modified
instance of a Signal. This will behave like a normal Signal but it
will call your decorated method before notifying to the slots, and
return the value returned by your method, so it can be used
transparently. Also, if the object this method belongs to is an
instance of Sender, it will automatically notify it whenever the
signal is emitted, using the name of the decorated function as the
message.
"""
sig = _ExtendedSignal ()
sig._extended_signal_obj = obj
sig._extended_signal_func = func
return wraps (func) (sig)
@instance_decorator
def signal_before (obj, func):
"""
This behaves exactly like the 'signal' decorator, but notifies the
slots before calling the function and not the other way.
TODO: Make Pickable.
"""
if isinstance (obj, Sender) and not\
isinstance (obj, AutoSignalSenderGet):
class ExtendedSignalBefore (Signal):
def notify (self, *args, **kws):
obj.send (func.__name__, *args, **kws)
Signal.notify (self, *args, **kws)
res = func (obj, *args, **kws)
return res
else:
class ExtendedSignalBefore (Signal):
def notify (self, *args, **kws):
Signal.notify (self, *args, **kws)
res = func (obj, *args, **kws)
return res
return wraps (func) (ExtendedSignalBefore ())
class _ExtendedSignal (Signal):
_extended_signal_obj = None
_extended_signal_func = nop
def notify (self, *args, **kws):
func = self._extended_signal_func
obj = self._extended_signal_obj
res = func (obj, *args, **kws)
if isinstance (obj, Sender) and not \
isinstance (obj, AutoSignalSenderGet):
obj.send (func.__name__, *args, **kws)
Signal.notify (self, *args, **kws)
return res
| gpl-3.0 |
Tigraine/EvoPaint | src/evopaint/pixel/rulebased/conditions/ExistenceCondition.java | 6243 | /*
* Copyright (C) 2010 Markus Echterhoff <tam@edu.uni-klu.ac.at>
*
* This file is part of EvoPaint.
*
* EvoPaint 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 EvoPaint. If not, see <http://www.gnu.org/licenses/>.
*/
package evopaint.pixel.rulebased.conditions;
import evopaint.gui.rulesetmanager.JConditionTargetButton;
import evopaint.gui.rulesetmanager.util.NamedObjectListCellRenderer;
import evopaint.interfaces.IRandomNumberGenerator;
import evopaint.pixel.rulebased.targeting.IConditionTarget;
import evopaint.pixel.rulebased.util.ObjectComparisonOperator;
import evopaint.pixel.rulebased.Condition;
import evopaint.pixel.rulebased.RuleBasedPixel;
import evopaint.pixel.rulebased.targeting.MetaTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedHashMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
/**
*
* @author Markus Echterhoff <tam@edu.uni-klu.ac.at>
*/
public class ExistenceCondition extends Condition {
private ObjectComparisonOperator objectComparisonOperator;
public ExistenceCondition(IConditionTarget target, ObjectComparisonOperator objectComparisonOperator) {
super(target);
this.objectComparisonOperator = objectComparisonOperator;
}
public ExistenceCondition() {
objectComparisonOperator = ObjectComparisonOperator.EQUAL;
}
public ExistenceCondition(ExistenceCondition existenceCondition) {
super(existenceCondition);
this.objectComparisonOperator = existenceCondition.objectComparisonOperator;
}
public ExistenceCondition(IRandomNumberGenerator rng) {
super(rng);
this.objectComparisonOperator = ObjectComparisonOperator.getRandom(rng);
}
public int getType() {
return Condition.EXISTENCE;
}
@Override
public int countGenes() {
return super.countGenes() + 1;
}
@Override
public void mutate(int mutatedGene, IRandomNumberGenerator rng) {
int numGenesSuper = super.countGenes();
if (mutatedGene < numGenesSuper) {
super.mutate(mutatedGene, rng);
return;
}
mutatedGene -= numGenesSuper;
if (mutatedGene == 0) {
objectComparisonOperator = ObjectComparisonOperator.getRandomOtherThan(objectComparisonOperator, rng);
return;
}
assert false; // we have an error in the mutatedGene calculation
}
@Override
public void mixWith(Condition theirCondition, float theirShare, IRandomNumberGenerator rng) {
super.mixWith(theirCondition, theirShare, rng);
ExistenceCondition c = (ExistenceCondition)theirCondition;
if (rng.nextFloat() < theirShare) {
objectComparisonOperator = c.objectComparisonOperator;
}
}
public ObjectComparisonOperator getComparisonOperator() {
return objectComparisonOperator;
}
public void setComparisonOperator(ObjectComparisonOperator comparisonOperator) {
this.objectComparisonOperator = comparisonOperator;
}
public String getName() {
return "existence";
}
public boolean isMet(RuleBasedPixel actor, RuleBasedPixel target) {
return !objectComparisonOperator.compare(target, null);
}
@Override
public String toString() {
String conditionString = new String();
conditionString += getTarget().toString();
if (getTarget() instanceof MetaTarget && ((MetaTarget)getTarget()).getDirections().size() > 1) {
if (objectComparisonOperator == ObjectComparisonOperator.NOT_EQUAL) {
conditionString += " are free spots";
} else {
conditionString += " are pixels";
}
} else {
if (objectComparisonOperator == ObjectComparisonOperator.NOT_EQUAL) {
conditionString += " is a free spot";
} else {
conditionString += " is a pixel";
}
}
return conditionString;
}
public String toHTML() {
String conditionString = new String();
conditionString += getTarget().toHTML();
if (getTarget() instanceof MetaTarget && ((MetaTarget)getTarget()).getDirections().size() > 1) {
if (objectComparisonOperator == ObjectComparisonOperator.NOT_EQUAL) {
conditionString += " are free spots";
} else {
conditionString += " are pixels";
}
} else {
if (objectComparisonOperator == ObjectComparisonOperator.NOT_EQUAL) {
conditionString += " is a free spot";
} else {
conditionString += " is a pixel";
}
}
return conditionString;
}
public LinkedHashMap<String,JComponent> addParametersGUI(LinkedHashMap<String,JComponent> parametersMap) {
JConditionTargetButton JConditionTargetButton = new JConditionTargetButton(this);
parametersMap.put("Target", JConditionTargetButton);
JComboBox comparisonComboBox = new JComboBox(ObjectComparisonOperator.createComboBoxModel());
comparisonComboBox.setRenderer(new NamedObjectListCellRenderer());
comparisonComboBox.setSelectedItem(objectComparisonOperator);
comparisonComboBox.addActionListener(new ComparisonListener());
parametersMap.put("Comparison", comparisonComboBox);
return parametersMap;
}
private class ComparisonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
setComparisonOperator((ObjectComparisonOperator) ((JComboBox) (e.getSource())).getSelectedItem());
}
}
}
| gpl-3.0 |
MikeMatt16/Abide | Abide Tag Definitions/Generated/Cache/DamageDirectionBlock.Generated.cs | 2065 | //------------------------------------------------------------------------------
// <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.Cache.Generated
{
using System;
using Abide.HaloLibrary;
using Abide.Tag;
/// <summary>
/// Represents the generated damage_direction_block tag block.
/// </summary>
public sealed class DamageDirectionBlock : Block
{
/// <summary>
/// Initializes a new instance of the <see cref="DamageDirectionBlock"/> class.
/// </summary>
public DamageDirectionBlock()
{
this.Fields.Add(new BlockField<DamageRegionBlock>("regions*", 11));
}
/// <summary>
/// Gets and returns the name of the damage_direction_block tag block.
/// </summary>
public override string BlockName
{
get
{
return "damage_direction_block";
}
}
/// <summary>
/// Gets and returns the display name of the damage_direction_block tag block.
/// </summary>
public override string DisplayName
{
get
{
return "damage_direction_block";
}
}
/// <summary>
/// Gets and returns the maximum number of elements allowed of the damage_direction_block tag block.
/// </summary>
public override int MaximumElementCount
{
get
{
return 4;
}
}
/// <summary>
/// Gets and returns the alignment of the damage_direction_block tag block.
/// </summary>
public override int Alignment
{
get
{
return 4;
}
}
}
}
| gpl-3.0 |
Axodoss/Wicken | src/main/java/com/lukasheise/wicken/engine/graphics/texture/TextureCUBE.java | 5364 | package com.lukasheise.wicken.engine.graphics.texture;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.lukasheise.wicken.engine.loader.ImageLoader;
import com.lukasheise.wicken.engine.loader.ImageLoader.Image;
import com.lukasheise.wicken.engine.resource.ResourceImpl;
import com.lukasheise.wicken.engine.system.FileSystem;
public class TextureCUBE extends ResourceImpl implements Texture {
private static final Logger logger = Logger.getLogger(Texture2D.class);
private static final String FILE_EXTENSION = ".png";
private static final String LOW_RESOLUTION = "_low";
private static final String CUBEMAP_POSX = "_posx";
private static final String CUBEMAP_NEGX = "_negx";
private static final String CUBEMAP_POSY = "_posy";
private static final String CUBEMAP_NEGY = "_negy";
private static final String CUBEMAP_POSZ = "_posz";
private static final String CUBEMAP_NEGZ = "_negz";
private int textureId;
private int textureUnit;
private int width;
private int height;
private int depth;
private List<Image> images = new ArrayList<Image>();
public TextureCUBE(String filename) {
logger.info("Creating Texture: " + filename);
this.resourceName = filename;
textureId = glGenTextures();
bind(NO_TEXTURE_UNIT);
String[] filenames = new String[] {
resourceName + CUBEMAP_POSX + LOW_RESOLUTION + FILE_EXTENSION,
resourceName + CUBEMAP_NEGX + LOW_RESOLUTION + FILE_EXTENSION,
resourceName + CUBEMAP_POSY + LOW_RESOLUTION + FILE_EXTENSION,
resourceName + CUBEMAP_NEGY + LOW_RESOLUTION + FILE_EXTENSION,
resourceName + CUBEMAP_POSZ + LOW_RESOLUTION + FILE_EXTENSION,
resourceName + CUBEMAP_NEGZ + LOW_RESOLUTION + FILE_EXTENSION
};
int[] targets = new int[] {
GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
boolean hasLowRes = true;
for (int i = 0; i < 6; i++) {
if (!FileSystem.fileExists(filenames[i])) {
hasLowRes = false;
break;
}
}
if (hasLowRes) {
for (int i = 0; i < 6; i++) {
Image image = TextureManager.getImageLoader().loadImage(filenames[i],true);
TextureManager.texImage2D(targets[i],0,image.format,image.getWidth(),image.getHeight(),0,image.format,GL_UNSIGNED_BYTE,image.data,false);
}
}
TextureManager.setTextureFilter(false);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
unbind();
}
@Override
public void bind(int textureUnit) {
this.textureUnit = textureUnit;
TextureManager.bindTexture(GL_TEXTURE_CUBE_MAP, textureUnit, textureId);
}
@Override
public void unbind() {
TextureManager.unbindTexture(GL_TEXTURE_CUBE_MAP, textureUnit);
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getDepth() {
return depth;
}
public boolean isCubemap() {
return true;
}
@Override
public void threadload() {
List<String> filenames = new ArrayList<String>();
filenames.add(resourceName + CUBEMAP_POSX + FILE_EXTENSION);
filenames.add(resourceName + CUBEMAP_NEGX + FILE_EXTENSION);
filenames.add(resourceName + CUBEMAP_POSY + FILE_EXTENSION);
filenames.add(resourceName + CUBEMAP_NEGY + FILE_EXTENSION);
filenames.add(resourceName + CUBEMAP_POSZ + FILE_EXTENSION);
filenames.add(resourceName + CUBEMAP_NEGZ + FILE_EXTENSION);
for (String filename : filenames) {
Image loadedImage = TextureManager.getImageLoader().loadImage(filename,true);
images.add(TextureManager.getImageLoader().scaleDownImage(loadedImage,TextureManager.getTextureScaleDownFactor()));
}
}
@Override
public void postload() {
bind(NO_TEXTURE_UNIT);
int[] targets = new int[] { GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z };
if (images.size() == targets.length) {
for (int i = 0; i < targets.length; i++) {
ImageLoader.Image image = images.get(i);
TextureManager.texImage2D(targets[i],0,image.format,image.getWidth(),image.getHeight(),0,image.format,GL_UNSIGNED_BYTE,image.data,true);
}
} else {
for (int i = 0; i < targets.length; i++) {
TextureManager.texImage2D(targets[i],0,GL_RGB,TextureManager.getImageLoader().getDefaultImageWidth(),TextureManager.getImageLoader().getDefaultImageHeight(),0,GL_RGB,GL_UNSIGNED_BYTE,TextureManager.getImageLoader().getDefaultImage(),false);
}
}
TextureManager.setTextureFilter(false);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
images.clear();
resourceLoaded = true;
unbind();
}
@Override
public void unload() {
super.unload();
glDeleteTextures(textureId);
}
}
| gpl-3.0 |
savageboy74/ProjectArcane | src/main/java/com/woody104/projectarcane/items/ItemHandle.java | 272 | package com.woody104.projectarcane.items;
import com.woody104.projectarcane.registry.CreativeTabRegistry;
import net.minecraft.item.Item;
public class ItemHandle extends Item {
public ItemHandle() {
super();
this.setCreativeTab(CreativeTabRegistry.arcaneTab);
}
}
| gpl-3.0 |
FabioZumbi12/RedProtect | RedProtect-Spigot/src/main/java/br/net/fabiozumbi12/RedProtect/Bukkit/commands/SubCommands/RegionHandlers/SetMinYCommand.java | 6424 | /*
* Copyright (c) 2020 - @FabioZumbi12
* Last Modified: 02/07/2020 18:59.
*
* This class is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any
* damages arising from the use of this class.
*
* Permission is granted to anyone to use this class for any purpose, including commercial plugins, and to alter it and
* redistribute it freely, subject to the following restrictions:
* 1 - The origin of this class must not be misrepresented; you must not claim that you wrote the original software. If you
* use this class in other plugins, an acknowledgment in the plugin documentation would be appreciated but is not required.
* 2 - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original class.
* 3 - This notice may not be removed or altered from any source distribution.
*
* Esta classe é fornecida "como está", sem qualquer garantia expressa ou implícita. Em nenhum caso os autores serão
* responsabilizados por quaisquer danos decorrentes do uso desta classe.
*
* É concedida permissão a qualquer pessoa para usar esta classe para qualquer finalidade, incluindo plugins pagos, e para
* alterá-lo e redistribuí-lo livremente, sujeito às seguintes restrições:
* 1 - A origem desta classe não deve ser deturpada; você não deve afirmar que escreveu a classe original. Se você usar esta
* classe em um plugin, uma confirmação de autoria na documentação do plugin será apreciada, mas não é necessária.
* 2 - Versões de origem alteradas devem ser claramente marcadas como tal e não devem ser deturpadas como sendo a
* classe original.
* 3 - Este aviso não pode ser removido ou alterado de qualquer distribuição de origem.
*/
package br.net.fabiozumbi12.RedProtect.Bukkit.commands.SubCommands.RegionHandlers;
import br.net.fabiozumbi12.RedProtect.Bukkit.RedProtect;
import br.net.fabiozumbi12.RedProtect.Bukkit.Region;
import br.net.fabiozumbi12.RedProtect.Bukkit.commands.SubCommand;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static br.net.fabiozumbi12.RedProtect.Bukkit.commands.CommandHandlers.HandleHelpPage;
public class SetMinYCommand implements SubCommand {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof ConsoleCommandSender) {
HandleHelpPage(sender, 1);
return true;
}
Player player = (Player) sender;
Region r;
//rp setminy <size>
switch (args.length) {
case 1:
r = RedProtect.get().getRegionManager().getTopRegion(player.getLocation());
if (r == null) {
RedProtect.get().getLanguageManager().sendMessage(player, "cmdmanager.region.todo.that");
return true;
}
break;
//rp setminy <size> [region]
case 2:
r = RedProtect.get().getRegionManager().getRegion(args[1], player.getWorld().getName());
if (r == null) {
RedProtect.get().getLanguageManager().sendMessage(player, RedProtect.get().getLanguageManager().get("cmdmanager.region.doesntexist") + ": " + args[1]);
return true;
}
break;
//rp setminy <size> [region] [database]
case 3:
if (Bukkit.getWorld(args[2]) == null) {
RedProtect.get().getLanguageManager().sendMessage(player, "cmdmanager.region.invalidworld");
return true;
}
r = RedProtect.get().getRegionManager().getRegion(args[2], Bukkit.getWorld(args[2]).getName());
if (r == null) {
RedProtect.get().getLanguageManager().sendMessage(player, RedProtect.get().getLanguageManager().get("cmdmanager.region.doesntexist") + ": " + args[1]);
return true;
}
break;
default:
RedProtect.get().getLanguageManager().sendCommandHelp(sender, "setminy", true);
return true;
}
String from = String.valueOf(r.getMinY());
try {
int size = Integer.parseInt(args[0]);
if ((r.getMaxY() - size) <= 1) {
RedProtect.get().getLanguageManager().sendMessage(player, "cmdmanager.region.ysiszesmatch");
return true;
}
if (!r.isLeader(player) && !r.isAdmin(player) && !RedProtect.get().getPermissionHandler().hasPerm(player, "redprotect.command.admin.setminy")) {
RedProtect.get().getLanguageManager().sendMessage(player, "playerlistener.region.cantuse");
return true;
}
r.setMinY(size);
RedProtect.get().getLanguageManager().sendMessage(player, RedProtect.get().getLanguageManager().get("cmdmanager.region.setminy.success").replace("{region}", r.getName()).replace("{fromsize}", from).replace("{size}", String.valueOf(size)));
RedProtect.get().logger.addLog("(World " + r.getWorld() + ") Player " + player.getName() + " SETMINY of region " + r.getName() + " to " + args[0]);
return true;
} catch (NumberFormatException e) {
RedProtect.get().getLanguageManager().sendMessage(player, "cmdmanager.region.invalid.number");
return true;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
List<String> tab = new ArrayList<>();
if (args.length == 1)
tab.add(sender instanceof Player ? String.valueOf(((Player) sender).getLocation().getBlockY()) : "0");
if (args.length == 3)
if (args[2].isEmpty())
tab.addAll(Bukkit.getWorlds().stream().map(World::getName).collect(Collectors.toList()));
else
tab.addAll(Bukkit.getWorlds().stream().filter(w -> w.getName().startsWith(args[1])).map(World::getName).collect(Collectors.toList()));
return tab;
}
} | gpl-3.0 |
jmacauley/OpenDRAC | Server/Database/src/main/java/com/nortel/appcore/app/drac/database/helper/DbUtilityLpcpScheduler.java | 11247 | /**
* <pre>
* The owner of the original code is Ciena Corporation.
*
* Portions created by the original owner are Copyright (C) 2004-2010
* the original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of DRAC (Dynamic Resource Allocation Controller).
*
* DRAC 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.
*
* DRAC 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/>.
* </pre>
*/
package com.nortel.appcore.app.drac.database.helper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nortel.appcore.app.drac.common.auditlogs.LogKeyEnum;
import com.nortel.appcore.app.drac.common.auditlogs.LogRecord;
import com.nortel.appcore.app.drac.common.db.DbKeys;
import com.nortel.appcore.app.drac.common.db.DbOpsHelper;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder;
import com.nortel.appcore.app.drac.common.types.Schedule;
import com.nortel.appcore.app.drac.common.types.ServiceXml;
import com.nortel.appcore.app.drac.common.types.State.SERVICE;
import com.nortel.appcore.app.drac.common.utility.event.Tl1XmlAlarmEvent;
import com.nortel.appcore.app.drac.database.dracdb.DbLightPath;
import com.nortel.appcore.app.drac.database.dracdb.DbLightPathAlarmDetails;
import com.nortel.appcore.app.drac.database.dracdb.DbLightPathAlarmSummaries;
import com.nortel.appcore.app.drac.database.dracdb.DbLightPathEdge;
import com.nortel.appcore.app.drac.database.dracdb.DbLog;
import com.nortel.appcore.app.drac.database.dracdb.DbNetworkElement;
import com.nortel.appcore.app.drac.database.dracdb.DbSchedule;
/**
* Created on Aug 22, 2005
*
* @author nguyentd
*/
public enum DbUtilityLpcpScheduler {
INSTANCE;
private final Logger log = LoggerFactory.getLogger(getClass());
public void addNewService(ServiceXml serviceXml) throws Exception {
//
DbLightPath.INSTANCE.add(serviceXml);
DbLightPathEdge.INSTANCE.add(serviceXml);
}
public void appendAlarmData(String alarmId, Element dataElement)
throws Exception {
// e.g. data = <element name=reason value=cleared by audit />";
/*
* <event duration="194854" id="00-1B-25-2D-5C-7A_0100000425-0001-0148"
* name="alarm" owner="TDEFAULT_PROXY" time="1227722945349"> <eventInfo
* notificationType="CR" occurredDate="2001-07-21" occurredTime="06-06-53"/>
* <data> <element name="description" value="AIS"/> <element name="aid"
* value="OC12-1-11-1"/> <element name="facility" value="OC12-1-11-1"/>
* <element name="serviceId" value="SERVICE-1227722874473"/> <element
* name="reason" value="cleared by audit"/> </data> <node
* id="00-1B-25-2D-5C-7A" ip="47.134.3.230" mode="SONET" port="10001"
* status="aligned" tid="OME0039" type="OME"/> </event>
*/
DbLightPathAlarmDetails.INSTANCE.appendAlarmData(alarmId, dataElement);
}
/*
* NOTE: Both old/new implementation here breaks the LPCP_PORT / NRB_PORT segregation:
* LPCP_PORT is accessing NRB_PORT schedule data.
*/
public String getActivationTypeForService(String serviceId) throws Exception {
ServiceXml aService = getServiceFromServiceId(serviceId);
String scheduleId = aService.getScheduleId();
Map<String, String> schedFilter = new HashMap<String, String>();
schedFilter.put(DbSchedule.SCHD_ID, scheduleId);
List<Schedule> listSchedules = DbSchedule.INSTANCE.retrieve(
schedFilter);
if (listSchedules == null || listSchedules.isEmpty()) {
throw new Exception("Record not found: " + scheduleId);
}
Schedule schedule = listSchedules.get(0);
return schedule.getActivationType().name();
}
public Map<String, String> getActiveAlarmFromNe(String neId) throws Exception {
Map<String, Object> filter = new HashMap<String, Object>();
filter.put(DbLightPathAlarmDetails.NEID, neId);
filter.put(DbLightPathAlarmDetails.DURATION, Long.valueOf(0));
List<Element> list = DbLightPathAlarmDetails.INSTANCE.retrieve(filter);
Map<String, String> resultMap = new HashMap<String, String>();
if (list != null) {
for (Element element : list) {
resultMap.put(
element.getAttributeValue(DbLightPathAlarmDetails.ALARMID),
element.getAttributeValue(DbLightPathAlarmDetails.TIME));
}
}
return resultMap;
}
public Tl1XmlAlarmEvent getAlarm(String alarmId) throws Exception {
Tl1XmlAlarmEvent aEvent = null;
Map<String, Object> filter = new HashMap<String, Object>();
filter.put(DbLightPathAlarmDetails.ALARMID, alarmId);
List<Element> list = DbLightPathAlarmDetails.INSTANCE.retrieve(filter);
if (list != null && !list.isEmpty()) {
Element alarmEvent = list.get(0);
aEvent = new Tl1XmlAlarmEvent(alarmEvent);
}
return aEvent;
}
public List<ServiceXml> getLiveServicesWithinTimeInterval(long fromTime,
long toTime) throws Exception {
// NOTE: The OLD implementation for this method (was named: getServices) did
// a look up of the
// services within the Schedule collection?! LPCP_PORT should be referencing LPCP_PORT
// data only
// within the Services.xml collection.
return DbLightPath.INSTANCE.getLiveServicesWithinTimeInterval(
fromTime, toTime);
}
public List<String> getNeWithActiveAlarm() throws Exception {
return DbLightPathAlarmDetails.INSTANCE.getNeWithActiveAlarm();
}
/*
* Get the next schedule with minimum endTime that is in the INPROGRESS or
* PENDING state
*
* @param @return ScheduleXML
*/
public ServiceXml getNextServiceToDelete() throws Exception {
return DbLightPath.INSTANCE.getNextServiceToDelete();
}
/*
* Get the next schedule with minimum startTime and endTime greater than
* fromTime that is in the PENDING state
*
* @param long fromTime, time in milliseconds to start the search from
*
* @return ScheduleXML
*/
public ServiceXml getNextServiceToStart(long fromTime) throws Exception {
return DbLightPath.INSTANCE.getNextServiceToStart(fromTime);
}
public ServiceXml getServiceFromCallId(String callId) throws Exception {
Map<String, Object> filter = new HashMap<String, Object>();
filter.put(DbKeys.LightPathCols.LP_CALLID, callId);
List<ServiceXml> results = DbLightPath.INSTANCE.retrieve(filter);
if (results == null || results.isEmpty()) {
throw new Exception("Record not found: " + callId);
}
return results.get(0);
}
public ServiceXml getServiceFromServiceId(String serviceId) throws Exception {
Map<String, Object> filter = new HashMap<String, Object>();
filter.put(DbKeys.LightPathCols.LP_SERVICEID, serviceId);
List<ServiceXml> results = DbLightPath.INSTANCE.retrieve(filter);
if (results == null || results.isEmpty()) {
throw new Exception("Record not found: " + serviceId);
}
return results.get(0);
}
public List<ServiceXml> getServicesFromAid(String aid, String channel,
long fromTime, String sourceNeId) throws Exception {
return DbLightPath.INSTANCE.getServicesFromAid(aid, channel, fromTime,
sourceNeId);
}
public List<ServiceXml> getServicesFromAlarm(String alarmId) throws Exception {
return DbLightPath.INSTANCE.getServicesFromAlarm(alarmId);
}
public SERVICE getServiceStatus(String id) throws Exception {
ServiceXml aService = getServiceFromServiceId(id);
SERVICE status = aService.getStatus();
return status;
}
public void insertAlarmDetail(String anEvent) throws Exception {
DbLightPathAlarmDetails.INSTANCE
.add(DbOpsHelper.xmlToElement(anEvent));
}
public void insertAlarmSummary(String neId, String anAlarm) throws Exception {
DbLightPathAlarmSummaries.INSTANCE.add(neId,
DbOpsHelper.xmlToElement(anAlarm));
}
public void updateAlarmDuration(String alarmId, long duration)
throws Exception {
DbLightPathAlarmDetails.INSTANCE
.updateAlarmDuration(alarmId, duration);
}
public void updateServiceByServiceId(String serviceId, SERVICE status)
throws Exception {
Map<String, String> data = new HashMap<String, String>();
data.put(DbKeys.LightPathCols.LP_STATUS, Integer.toString(status.ordinal()));
Map<String, String> idMap = new HashMap<String, String>();
idMap.put(DbKeys.LightPathCols.LP_SERVICEID, serviceId);
DbLightPath.INSTANCE.update(idMap, data);
}
public void updateServiceStatusByCallId(String callId, SERVICE status)
throws Exception {
Map<String, String> data = new HashMap<String, String>();
data.put(DbKeys.LightPathCols.LP_STATUS, Integer.toString(status.ordinal()));
Map<String, String> idMap = new HashMap<String, String>();
idMap.put(DbKeys.LightPathCols.LP_CALLID, callId);
DbLightPath.INSTANCE.update(idMap, data);
ServiceXml service = getServiceFromCallId(callId);
Map<String, String> details = new HashMap<String, String>();
details.put("ServiceState", status.toString());
try {
List<NetworkElementHolder> neList = DbNetworkElement.INSTANCE
.retrieveAll();
String aTid = null;
String aIp = null;
String zTid = null;
String zIp = null;
for (NetworkElementHolder h : neList) {
if (h.getId().equals(service.getAend())) {
aTid = h.getTid();
aIp = h.getIp() + ":" + h.getPort();
}
else if (h.getId().equals(service.getZend())) {
zTid = h.getTid();
zIp = h.getIp() + ":" + h.getPort();
}
}
if (aIp != null) {
details.put("A-End-Ne-IP", aIp);
}
if (aTid != null) {
details.put("A-End-Ne-TID", aTid);
}
if (zIp != null) {
details.put("Z-End-Ne-IP", zIp);
}
if (zTid != null) {
details.put("Z-End-Ne-TID", zTid);
}
}
catch (Exception e) {
log.error("Unable to provide a/z end NE record details for service "
+ service.toString(), e);
}
details.put("A-End-Ne-ID", service.getAend());
details.put("A-End-AID", service.getEndConnection(true).getSourceXcAid());
details.put("Z-End-Ne-ID", service.getZend());
details.put("Z-End-AID", service.getEndConnection(false).getTargetXcAid());
details.put("StartTimeString", service.getBeginDateTime());
details.put("EndTimeString", service.getEndDateTime());
details.put("StartTime", Long.toString(service.getStartTime()));
details.put("EndTime", Long.toString(service.getEndTime()));
details.put("User", service.getUser());
details.put("Bandwidth", service.getBandwidth());
details.put("Mps", Integer.toString(service.getMbs()));
//
details.put("FullServiceRecord", service.toString());
LogRecord lr = new LogRecord(null, null, service.getBillingGroup(),
service.getServiceId(), LogKeyEnum.KEY_SERVICE_STATE_CHANGED,
new String[] { status.toString() }, details);
DbLog.INSTANCE.addLog(lr);
}
}
| gpl-3.0 |
donpadlo/webuseorg3 | controller/server/cloud/uploadfiles.php | 1665 | <?php
// Данный код создан и распространяется по лицензии GPL v3
// Разработчики:
// Грибов Павел,
// Сергей Солодягин (solodyagin@gmail.com)
// (добавляйте себя если что-то делали)
// http://грибовы.рф
defined('WUO_ROOT') or die('Доступ запрещён'); // Запрещаем прямой вызов скрипта.
// Проверяем: может ли пользователь добавлять файлы?
$user->TestRoles('1,4') or die('Недостаточно прав');
$selectedkey = $_POST['selectedkey'];
$orig_file = $_FILES['filedata']['name'];
$dis = array(
'.htaccess'
); // Запрещённые для загрузки файлы
$rs = array(
'msg' => 'error'
); // Ответ по умолчанию, если пойдёт что-то не так
if (! in_array($orig_file, $dis)) {
$userfile_name = GetRandomId(8) . '.' . pathinfo($orig_file, PATHINFO_EXTENSION);
$src = $_FILES['filedata']['tmp_name'];
$dst = WUO_ROOT . '/files/' . $userfile_name;
$res = move_uploaded_file($src, $dst);
if ($res) {
$rs['msg'] = $userfile_name;
$sz = filesize($dst);
if ($selectedkey != '') {
$SQL = "INSERT INTO cloud_files (id, cloud_dirs_id, title, filename, dt, sz)
VALUES (null, '$selectedkey', '$orig_file', '$userfile_name', NOW(), $sz)";
$sqlcn->ExecuteSQL($SQL) or die('Не могу добавить файл! ' . mysqli_error($sqlcn->idsqlconnection));
}
}
}
jsonExit($rs);
| gpl-3.0 |
vpac-innovations/rsa | src/cmdclient/src/main/java/org/vpac/ndg/cli/smadaptor/remote/RemoteDataExport.java | 3704 | /*
* This file is part of the Raster Storage Archive (RSA).
*
* The RSA 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.
*
* The RSA is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* the RSA. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013 CRCSI - Cooperative Research Centre for Spatial Information
* http://www.crcsi.com.au/
*/
package org.vpac.ndg.cli.smadaptor.remote;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.vpac.ndg.Utils;
import org.vpac.ndg.cli.smadaptor.DataExport;
import org.vpac.ndg.exceptions.TaskException;
import org.vpac.ndg.exceptions.TaskInitialisationException;
import org.vpac.ndg.geometry.Box;
import org.vpac.ndg.geometry.Point;
import org.vpac.web.model.response.ExportResponse;
public class RemoteDataExport implements DataExport {
// public static String DATA_EXPORT_URL = "/Data/Export.xml?datasetId={datasetId}&bandId={bandId}&searchStartDate={searchStartDate}" +
// "&searchEndDate={searchEndDate&projection={projection}&topLeft.x={topleftX}&topLeft.y={topleftY}&bottomRight.x={bottomRightX}&bottomRight.y={bottomRightY}";
public static String DATA_EXPORT_URL = "/Data/Export.xml?datasetId={datasetId}";
final Logger log = LoggerFactory.getLogger(RemoteDataExport.class);
private String datasetId;
@SuppressWarnings("unused")
private Box extents;
private Date start;
private Date end;
@SuppressWarnings("unused")
private List<String> bandNamesFilter;
@SuppressWarnings("unused")
private Boolean useBilinearInterpolation;
private String baseUri;
@Autowired
protected RestTemplate restTemplate;
public String getBaseUri() {
return baseUri;
}
public void setBaseUri(String baseUri) {
this.baseUri = baseUri;
}
@Override
public void setDatasetId(String id) {
this.datasetId = id;
}
@Override
public void setExtents(String x1, String y1, String x2, String y2)
throws NumberFormatException {
Point<Double> p1;
Point<Double> p2;
p1 = new Point<Double>(Double.parseDouble(x1), Double.parseDouble(y1));
p2 = new Point<Double>(Double.parseDouble(x2), Double.parseDouble(y2));
extents = new Box(p1, p2);
}
@Override
public void setTimeRange(String start, String end) {
log.info("Temporal extents: {} / {}", start, end);
this.start = Utils.parseDate(start);
this.end = Utils.parseDate(end);
if (log.isDebugEnabled()) {
DateFormat formatter = Utils.getTimestampFormatter();
log.debug("Dates interpreted as {} / {}",
formatter.format(this.start), formatter.format(this.end));
}
}
@Override
public void setBandNamesFilter(List<String> bandNamesFilter) {
this.bandNamesFilter = bandNamesFilter;
}
@Override
public void setUseBilinearInterpolation(Boolean value) {
useBilinearInterpolation = value;
}
@Override
public String start() throws TaskInitialisationException, TaskException,
IOException {
ExportResponse response = restTemplate.postForObject(baseUri + DATA_EXPORT_URL, null, ExportResponse.class, this.datasetId);
return response.getTaskId();
}
}
| gpl-3.0 |
stenosis/roommate-app | src/roommateapp/info/io/EHandlerRFile.java | 1591 | /*
* Roommate
* Copyright (C) 2012,2013 Team Roommate (info@roommateapp.info)
*
* 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 */
package roommateapp.info.io;
/* imports */
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import roommateapp.info.droid.RoommateConfig;
/**
* Error Handler of the Roommate file parser.
*/
public class EHandlerRFile implements ErrorHandler {
public void error(SAXParseException exception) throws SAXException {
if (RoommateConfig.VERBOSE) {
System.out.println("ERROR: Roommate file parsing error");
}
}
public void fatalError(SAXParseException exception) throws SAXException {
if (RoommateConfig.VERBOSE) {
System.out.println("ERROR: Roommate file parsing FATAL error");
}
}
public void warning(SAXParseException exception) throws SAXException {
if (RoommateConfig.VERBOSE) {
System.out.println("ERROR: Roommate file parsing warning");
}
}
} | gpl-3.0 |
MineSworn/SwornGuard | src/main/java/net/t7seven7t/swornguard/io/PlayerDataCache.java | 9974 | package net.t7seven7t.swornguard.io;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import net.dmulloy2.io.FileSerialization;
import net.dmulloy2.io.IOUtil;
import net.dmulloy2.io.UUIDFetcher;
import net.dmulloy2.util.Util;
import net.t7seven7t.swornguard.SwornGuard;
import net.t7seven7t.swornguard.types.PlayerData;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
/**
* @author dmulloy2
*/
public class PlayerDataCache implements PlayerDataServiceProvider {
private final File folder;
private final String extension = ".dat";
private final String folderName = "players";
private final SwornGuard plugin;
private final ConcurrentMap<String, PlayerData> cache;
public PlayerDataCache(SwornGuard plugin) {
this.folder = new File(plugin.getDataFolder(), folderName);
if (! folder.exists())
folder.mkdirs();
this.cache = new ConcurrentHashMap<String, PlayerData>(64, 0.75F, 64);
this.plugin = plugin;
this.convertToUUID();
}
// ---- Data Getters
private final PlayerData getData(String key) {
// Check cache first
PlayerData data = cache.get(key);
if (data == null) {
// Attempt to load it
File file = new File(folder, getFileName(key));
if (file.exists()) {
data = loadData(key);
if (data == null) {
// Corrupt data :(
if (! file.renameTo(new File(folder, file.getName() + "_bad")))
file.delete();
return null;
}
// Cache it
cache.put(key, data);
}
}
return data;
}
@Override
public final PlayerData getData(UUID uniqueId) {
return getData(uniqueId.toString());
}
@Override
public final PlayerData getData(Player player) {
PlayerData data = getData(getKey(player));
// Online players should always have data
if (data == null) {
data = newData(player);
}
// Try to fetch history from Essentials
List<String> history = data.getHistory();
if (history == null && plugin.isEssentialsEnabled()) {
history = plugin.getEssentialsHandler().getHistory(player.getUniqueId());
}
// Account for name changes
String lastKnownBy = data.getLastKnownBy();
if (lastKnownBy != null && ! lastKnownBy.isEmpty()) {
if (! lastKnownBy.equals(player.getName())) {
if (history == null) {
history = new ArrayList<String>();
}
// Ensure we have the right casing
if (lastKnownBy.equalsIgnoreCase(player.getName())) {
plugin.getLogHandler().log("Corrected casing for {0}''s name.", player.getName());
history.remove(lastKnownBy);
data.setLastKnownBy(lastKnownBy = player.getName());
history.add(lastKnownBy);
} else {
// Name change!
plugin.getLogHandler().log("{0} changed their name to {1}.", lastKnownBy, player.getName());
data.setLastKnownBy(lastKnownBy = player.getName());
history.add(lastKnownBy);
}
}
} else {
data.setLastKnownBy(lastKnownBy = player.getName());
}
if (history == null) {
history = new ArrayList<String>();
history.add(player.getName());
}
data.setHistory(history);
data.setUniqueId(player.getUniqueId().toString());
// Return
return data;
}
@Override
public final PlayerData getData(OfflinePlayer player) {
// Slightly different handling for Players
if (player.isOnline())
return getData(player.getPlayer());
// Attempt to get by name
return getData(getKey(player));
}
// ---- Data Management
public final PlayerData newData(String key) {
// Construct
PlayerData data = new PlayerData();
// Cache and return
cache.put(key, data);
return data;
}
public final PlayerData newData(Player player) {
return newData(getKey(player));
}
public final PlayerData newData(OfflinePlayer player) {
return newData(getKey(player));
}
private final PlayerData loadData(String key) {
File file = new File(folder, getFileName(key));
try {
PlayerData data = FileSerialization.load(file, PlayerData.class);
data.setUniqueId(key);
return data;
} catch (Throwable ex) {
plugin.getLogHandler().log(Level.WARNING, Util.getUsefulStack(ex, "loading data for {0}", key));
return null;
}
}
public final void save() {
long start = System.currentTimeMillis();
plugin.getLogHandler().log("Saving players to disk...");
for (Entry<String, PlayerData> entry : getAllLoadedPlayerData().entrySet()) {
try {
File file = new File(folder, getFileName(entry.getKey()));
FileSerialization.save(entry.getValue(), file);
} catch (Throwable ex) {
plugin.getLogHandler().log(Level.WARNING, Util.getUsefulStack(ex, "saving data for {0}", entry.getKey()));
}
}
plugin.getLogHandler().log("Players saved. Took {0} ms.", System.currentTimeMillis() - start);
}
// Legacy
@Deprecated
public final void save(boolean cleanup) {
save();
if (cleanup)
cleanupData();
}
public final void cleanupData() {
// Get all online players into an array list
List<String> online = new ArrayList<String>();
for (Player player : Util.getOnlinePlayers())
online.add(player.getName());
// Actually cleanup the data
for (String key : getAllLoadedPlayerData().keySet())
if (! online.contains(key))
cache.remove(key);
// Clear references
online.clear();
online = null;
}
// ---- Mass Getters
@Override
public final Map<String, PlayerData> getAllLoadedPlayerData() {
return Collections.unmodifiableMap(cache);
}
@Override
public final Map<String, PlayerData> getAllPlayerData() {
Map<String, PlayerData> data = new HashMap<String, PlayerData>();
data.putAll(cache);
File[] files = folder.listFiles();
if (files == null || files.length == 0) {
return Collections.unmodifiableMap(data);
}
for (File file : files) {
if (file.getName().contains(extension)) {
String fileName = IOUtil.trimFileExtension(file, extension);
if (! isFileLoaded(fileName))
data.put(fileName, loadData(fileName));
}
}
return Collections.unmodifiableMap(data);
}
// ---- UUID Conversion
private final void convertToUUID() {
File updated = new File(folder, ".updated");
if (updated.exists()) {
return;
}
long start = System.currentTimeMillis();
plugin.getLogHandler().log("Checking for unconverted files");
Map<String, PlayerData> data = getUnconvertedData();
if (data.isEmpty()) {
try {
updated.createNewFile();
} catch (Throwable ex) { }
return;
}
plugin.getLogHandler().log("Converting {0} files!", data.size());
try {
List<String> names = new ArrayList<String>(data.keySet());
ImmutableList.Builder<List<String>> builder = ImmutableList.builder();
int namesCopied = 0;
while (namesCopied < names.size()) {
builder.add(ImmutableList.copyOf(names.subList(namesCopied, Math.min(namesCopied + 100, names.size()))));
namesCopied += 100;
}
List<UUIDFetcher> fetchers = new ArrayList<UUIDFetcher>();
for (List<String> namesList : builder.build()) {
fetchers.add(new UUIDFetcher(namesList));
}
ExecutorService e = Executors.newFixedThreadPool(3);
List<Future<Map<String, UUID>>> results = e.invokeAll(fetchers);
File archive = new File(folder.getParentFile(), "archive");
if (! archive.exists())
archive.mkdir();
for (Future<Map<String, UUID>> result : results) {
Map<String, UUID> uuids = result.get();
for (Entry<String, UUID> entry : uuids.entrySet()) {
try {
// Get and update
String name = entry.getKey();
String uniqueId = entry.getValue().toString();
PlayerData dat = data.get(name);
dat.setLastKnownBy(name);
// Archive the old file
File file = new File(folder, getFileName(name));
Files.move(file, new File(archive, file.getName()));
// Create and save new file
File newFile = new File(folder, getFileName(uniqueId));
FileSerialization.save(dat, newFile);
} catch (Throwable ex) {
plugin.getLogHandler().log(Level.WARNING, Util.getUsefulStack(ex, "converting {0}", entry.getKey()));
}
}
}
} catch (Throwable ex) {
plugin.getLogHandler().log(Level.WARNING, Util.getUsefulStack(ex, "converting to UUID-based lookups!"));
return;
}
plugin.getLogHandler().log("Successfully converted to UUID-based lookups! Took {0} ms!", System.currentTimeMillis() - start);
}
private final Map<String, PlayerData> getUnconvertedData() {
Map<String, PlayerData> data = new HashMap<String, PlayerData>();
File[] files = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
String name = file.getName();
return name.contains(extension) && name.length() != 40;
}
});
for (File file : files) {
try {
PlayerData loaded = FileSerialization.load(file, PlayerData.class);
if (loaded != null) {
String fileName = IOUtil.trimFileExtension(file, extension);
loaded.setLastKnownBy(fileName);
data.put(fileName, loaded);
}
} catch (Throwable ex) {
plugin.getLogHandler().log(Level.WARNING, Util.getUsefulStack(ex, "loading data {0}", file));
}
}
return Collections.unmodifiableMap(data);
}
// ---- Util
private final String getKey(OfflinePlayer player) {
return player.getUniqueId().toString();
}
private final String getFileName(String key) {
return key + extension;
}
private final boolean isFileLoaded(String fileName) {
return cache.keySet().contains(fileName);
}
public int getFileListSize() {
return folder.listFiles().length;
}
public int getCacheSize() {
return cache.size();
}
} | gpl-3.0 |
tectronics/smbstats | SMBStats/Settings.cs | 4041 | #region License Information (GNU GPL v3)
/*
Super Meat Boy Stats
Copyright (C) 2011 Juzz
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 License Information (GNU GPL v3)
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using IniParser;
namespace SMBStats
{
public class Settings
{
public bool AutoLoad { get; set; }
public bool AutoUpdate { get; set; }
public string LastLoadPath { get; set; }
public long SteamID { get; set; }
public string UserKey { get; set; }
private const string SettingFile = "Settings.ini";
public string SettingPath
{
get { return Path.Combine(Application.StartupPath, SettingFile); }
}
public Settings()
{
Init();
if (File.Exists(SettingFile))
{
Load();
}
else
{
Save();
}
}
public void Init()
{
AutoLoad = true;
AutoUpdate = true;
}
public void Save()
{
try
{
IniData data = new IniData();
data.Sections.AddSection("Settings");
data.Sections.GetSectionData("Settings").Keys.AddKey("AutoLoad", AutoLoad.ToString());
data.Sections.GetSectionData("Settings").Keys.AddKey("AutoUpdate", AutoUpdate.ToString());
data.Sections.GetSectionData("Settings").Keys.AddKey("LastLoadPath", LastLoadPath);
data.Sections.GetSectionData("Settings").Keys.AddKey("SteamID", SteamID.ToString());
data.Sections.GetSectionData("Settings").Keys.AddKey("UserKey", UserKey);
FileIniDataParser parser = new FileIniDataParser();
parser.SaveFile(SettingPath, data);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
public bool Load()
{
if (File.Exists(SettingFile))
{
try
{
FileIniDataParser parser = new FileIniDataParser();
IniData data = parser.LoadFile(SettingPath);
string autoLoad = data["Settings"]["AutoLoad"];
if (!string.IsNullOrEmpty(autoLoad)) AutoLoad = CheckBool(autoLoad);
string autoUpdate = data["Settings"]["AutoUpdate"];
if (!string.IsNullOrEmpty(autoUpdate)) AutoUpdate = CheckBool(autoUpdate);
LastLoadPath = data["Settings"]["LastLoadPath"];
string steamID = data["Settings"]["SteamID"];
if (!string.IsNullOrEmpty(steamID)) SteamID = Convert.ToInt64(steamID);
UserKey = data["Settings"]["UserKey"];
return true;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
return false;
}
private bool CheckBool(string text)
{
text = text.ToLowerInvariant().Trim();
return text == "true" || text == "1";
}
}
} | gpl-3.0 |
Traderain/Wolven-kit | CP77.CR2W/Types/cp77/gamedataAimAssistCommon_Record.cs | 262 | using CP77.CR2W.Reflection;
namespace CP77.CR2W.Types
{
[REDMeta]
public class gamedataAimAssistCommon_Record : gamedataTweakDBRecord
{
public gamedataAimAssistCommon_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| gpl-3.0 |
Terni/BCWLibrary | Bitcoin/Bitcoin.APIClient/Responses/GetTxOutSetInfoResponse.cs | 604 | // Copyright (c) 2014 George Kimionis
// Distributed under the GPLv3 software license, see the accompanying file LICENSE or http://opensource.org/licenses/GPL-3.0
using System;
namespace Bitcoin.APIClient.Responses
{
public class GetTxOutSetInfoResponse
{
public Int32 Height { get; set; }
public String BestBlock { get; set; }
public Int32 Transactions { get; set; }
public Int32 TxOuts { get; set; }
public Int32 BytesSerialized { get; set; }
public String HashSerialized { get; set; }
public Double TotalAmount { get; set; }
}
} | gpl-3.0 |
FHICT-Software/P3P4 | PTS/AirHockeyJeroen/AirHockey_ClassLibrary_Jeroen/src/components/chat/Chatter.java | 755 | //<editor-fold defaultstate="collapsed" desc="Jibberish">
package components.chat;
//</editor-fold>
/**
* In this class you can find all properties and operations for Chatter.
* //CHECK
*
* @organization: Moridrin
* @author J.B.A.J. Berkvens
* @date 2014/05/27
*/
public class Chatter {
//<editor-fold defaultstate="collapsed" desc="Declarations">
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Getters & Setters">
//</editor-fold>
//<editor-fold desc="Operations">
//<editor-fold defaultstate="collapsed" desc="Constructor()">
/**
* This is the constructor for Chatter.
*/
public Chatter(){
//TODO
}
//</editor-fold>
//</editor-fold>
}
| gpl-3.0 |
gi0e5b06/lmms | plugins/OutputGDX/OutputGDXDialog.cpp | 3300 | /*
* OutputGDXDialog.cpp - control dialog for audio output properties
*
* Copyright (c) 2018-2019 gi0e5b06 (on github.com)
*
* This file is part of LSMM -
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "OutputGDXDialog.h"
#include "OutputGDXControls.h"
#include "embed.h"
#include <QGridLayout>
OutputGDXDialog::OutputGDXDialog(OutputGDXControls* controls) :
EffectControlDialog(controls)
{
setWindowIcon(PLUGIN_NAME::getIcon("logo"));
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), embed::getIconPixmap("plugin_bg"));
setPalette(pal);
QGridLayout* mainLayout = new QGridLayout(this);
mainLayout->setContentsMargins(6, 6, 6, 6);
mainLayout->setSpacing(6);
Knob* leftKNB = new Knob(this);
leftKNB->setModel(&controls->m_leftModel);
leftKNB->setPointColor(Qt::white);
leftKNB->setInteractive(false);
leftKNB->setText(tr("LEFT"));
leftKNB->setHintText(tr("Left:"), "");
Knob* rightKNB = new Knob(this);
rightKNB->setModel(&controls->m_rightModel);
rightKNB->setPointColor(Qt::white);
rightKNB->setInteractive(false);
rightKNB->setText(tr("RIGHT"));
rightKNB->setHintText(tr("Right:"), "");
Knob* rmsKNB = new Knob(this);
rmsKNB->setModel(&controls->m_rmsModel);
rmsKNB->setPointColor(Qt::red);
rmsKNB->setInteractive(false);
rmsKNB->setText(tr("RMS"));
rmsKNB->setHintText(tr("Rms:"), "");
Knob* volKNB = new Knob(this);
volKNB->setModel(&controls->m_volModel);
volKNB->setPointColor(Qt::red);
volKNB->setInteractive(false);
volKNB->setText(tr("VOL"));
volKNB->setHintText(tr("Vol:"), "");
Knob* panKNB = new Knob(this);
panKNB->setModel(&controls->m_panModel);
panKNB->setPointColor(Qt::magenta);
panKNB->setInteractive(false);
panKNB->setText(tr("PAN"));
panKNB->setHintText(tr("Pan:"), "");
int col = 0, row = 0; // first row
mainLayout->addWidget(leftKNB, row, ++col, 1, 1,
Qt::AlignBottom | Qt::AlignHCenter);
mainLayout->addWidget(rightKNB, row, ++col, 1, 1,
Qt::AlignBottom | Qt::AlignHCenter);
mainLayout->addWidget(rmsKNB, row, ++col, 1, 1,
Qt::AlignBottom | Qt::AlignHCenter);
mainLayout->addWidget(volKNB, row, ++col, 1, 1,
Qt::AlignBottom | Qt::AlignHCenter);
mainLayout->addWidget(panKNB, row, ++col, 1, 1,
Qt::AlignBottom | Qt::AlignHCenter);
mainLayout->setColumnStretch(6, 1);
mainLayout->setRowStretch(1, 1);
setFixedWidth(250);
setMinimumHeight(((sizeHint().height() - 1) / 50 + 1) * 50);
}
| gpl-3.0 |
jonanv/Data-Mining | RD-AC.py | 39086 | """
Desarrollado por Johanny Vargas González
28/08/2017
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math, operator, random, copy, os
from numpy import linalg as la
# Función que retorna la variable con el nombre de la carpeta de dataset
def folder():
carpeta = 'dataset/'
return carpeta
# Función que retorna una lista con los archivos del dataset
def files(carpeta):
archivos = os.listdir(carpeta)
return archivos
# Función que selecciona el archivo
def seleccionar():
print()
archivos = files(folder())
for x in range(len(archivos)):
print(str(x+1) + ". " + archivos[x])
nArchivo = int(input("Ingrese el número del dataset que desea seleccionar: "))
while (nArchivo < 1 or nArchivo > len(archivos)):
nArchivo = int(input("El número es incorrecto, debe estar entre " + str(1) + " y " + str(len(archivos)) + ": "))
return archivos[nArchivo-1]
# Función que carga el archivo y pregunta si tiene encabezado
def loadDataset():
header = input("\nEl archivo tiene encabezado? y/n: ")
header = header.lower()
if header == 'y' or header == 'yes' or header == 's' or header == 'si':
header = 0
else:
header = None
print("El archivo debe de tener encabezado para determinar las caracteristicas y las clases")
exit()
dataset = pd.read_csv(str(folder()) + str(seleccionar()), header=header)
return dataset
# Función que recibe que n individuo de la matriz normalizada va a devolver
def vector_registro_matrizNormalizada(n, matrizNormalizada, columns):
registro_matrizNormalizada = list()
for i in range(columns):
valor = matrizNormalizada[n][i]
registro_matrizNormalizada.append(valor)
return registro_matrizNormalizada
# Función de la distancia euclidiana
def dist_euclidiana(v1, v2):
dimension = len(v1)
suma = 0
for i in range(dimension):
suma += math.pow(float(v1[i]) - float(v2[i]), 2)
return math.sqrt(suma)
# Función de la distancia de manhattan
def dist_manhattan(v1, v2):
dimension = len(v1)
resutl = 0
rest = 0
for x in range(dimension):
rest += (float(v1[x]) - float(v2[x]))
result = abs(rest)
return result
# Función que determina el numero menor de unal ista y devuelve su posición
def minimo(lista):
dimension = len(lista)
minimo = lista[0]
posicion = 0
for x in range(1, dimension):
if (minimo > lista[x]):
minimo = lista[x]
posicion = x
return posicion
# Lista de metricas de distancia
lista_metricas = ['Distancia euclidiana', 'Distancia de manhattan']
# Función que selecciona la metrica que se quiere
def seleccion_metrica():
print()
for x in range(len(lista_metricas)):
print(str(x+1) + ". " + str(lista_metricas[x]))
mOpcion = int(input("Seleccione la metrica que quiere utilizar: "))
while (mOpcion < 1 or mOpcion > len(lista_metricas)):
mOpcion = int(input("El número es incorrecto, debe estar entre " + str(1) + " y " + str(len(lista_metricas)) + ": "))
return mOpcion
# Función que escoge la metrica que se quiere
def seleccion_metrica_distancia(v1, v2, mOpcion):
if (mOpcion == 1):
resultado = dist_euclidiana(v1, v2) # Distancia euclidiana
elif (mOpcion == 2):
resultado = dist_manhattan(v1, v2) # Distancia de manhattan
return resultado
# ALGORITMOS DE ANÁLISIS DE COMPONENTES Y CLUSTERING
# =======================================================================================================================
# =======================================================================================================================
def ACP():
print("Algoritmo de ACP")
# Cargar el archivo dataset
dataset = loadDataset()
#print(dataset)
#print(dataset.head())
# Se extraen las columnas del dataset
dataset.columns
#print(dataset.columns)
print("Descripción del dataset: ")
print(dataset.describe()) # Descripción estadistica de los datos
columns = len(dataset.columns) # Número total de columnas
#print(columns)
rows = len(dataset.index) # Número total de filas
#print(rows)
# Agrupando columnas por tipo de datos
tipos = dataset.columns.to_series().groupby(dataset.dtypes).groups
# Armando lista de columnas categóricas
try:
ctext = tipos[np.dtype('object')]
except KeyError:
ctext = list() # lista de columnas vacia en caso de que no haya categóricas
print("\nNúmero de columnas categoricas: " + str(len(ctext))) # cantidad de columnas con datos categóricos
# Armando lista de columnas numéricas
columnas = dataset.columns # lista total las columnas
cnum = list(set(columnas) - set(ctext)) # Total de columnas menos columnas no numéricas
print("Número de columnas numericas: " + str(len(cnum)))
# Lista de medias
#print(dataset.mean())
'''media = list()
for x in range(len(dataset.mean())):
media.append(dataset.mean()[x])
print(media)'''
media = dataset.mean().values.tolist() # Convertir la media del dataset a una lista
print("\nLista de medias: " + str(media))
#print(media)
# Lista de desviación estandar
#print(dataset.std())
'''destandar = list()
for x in range(len(dataset.std())):
destandar.append(dataset.std()[x])
print(destandar)'''
destandar = dataset.std().values.tolist() # Convertir la desviación estandar del dataset a una lista
print("Lista de desviación estandar: " + str(destandar))
#print(destandar)
# Lista de caracteristicas
lcaracteristicas = list()
for x in range(len(cnum)):
lcaracteristicas.append(columnas[x])
print("Lista de características: " + str(lcaracteristicas))
#print(lcaracteristicas)
# Todas las filas y todas las columnas del dataset en una lista
matriz = dataset.loc[:,].values
print("\nMatriz:")
print(matriz)
# ===========================================================================================================================
# Datos ajustados de la matriz
matrizDatosAjustados = list()
MDArow = list()
for x in range(rows):
for y in range(len(cnum)):
result = (matriz[x][y] - media[y])
MDArow.append(result)
matrizDatosAjustados.append(MDArow)
MDArow = list()
print("\nMatriz de datos ajustados:")
#print(matrizDatosAjustados)
MDA = pd.DataFrame(np.array(matrizDatosAjustados)) # Matriz de datos ajustados con pandas
print(MDA)
# Transpuesta de la matriz de datos ajustados
Transpuesta = np.array(matrizDatosAjustados) # Convertir la lista a formato numpy
matrizDatosAjustadosT = Transpuesta.transpose().tolist() # Convertir la lista numpy con la transpuesta a formato normal de lista
print("\nMatriz de datos ajustados transpuesta:")
#print(matrizDatosAjustadosT)
MDAT = pd.DataFrame(np.array(matrizDatosAjustadosT)) # Matriz de datos ajustados con pandas
print(MDAT)
# Matriz de covarianza (Transpuesta X Datos-Ajustados)
matrizCovarianza = list()
MCrow = list()
suma = 0
for i in range(len(matrizDatosAjustadosT)): # Filas de la matriz 1
for j in range(len(cnum)): # Columnas de la matriz 2
for k in range(rows): # Filas de la matriz 2
suma += (matrizDatosAjustadosT[i][k] * matrizDatosAjustados[k][j])
covarianza = (suma / (rows-1)) # Cada valor de la matriz de covarianza se debe dividir por n-1 (filas-1)
MCrow.append(covarianza)
suma = 0
matrizCovarianza.append(MCrow)
MCrow = list()
print("\nMatriz de covarianza:")
#print(matrizCovarianza)
MC = pd.DataFrame(np.array(matrizCovarianza)) # Matriz de covarianza con pandas
print(MC)
# Valores propios y vectores propios
evalues, evectors = la.eig(np.array(matrizCovarianza))
print("\nValores propios:")
eigenvalues = evalues.tolist()
print(eigenvalues)
print("\nVectores propios:")
print(evectors)
eigenvectors = evectors.tolist()
#print(eigenvectors)
# Suma de los valores propios
sumaEigenvalues = 0
for x in range(len(eigenvalues)):
sumaEigenvalues += eigenvalues[x]
print("\nSuma de los valores propios: " + str(sumaEigenvalues))
# Importancia de las columnas en pocentajes
porcentaje = list()
for x in range(len(eigenvalues)):
result = (eigenvalues[x] / sumaEigenvalues) * 100
porcentaje.append(result)
print("\nImportancia de las columnas en porcentaje: " + str(porcentaje))
# Indices de los porcentajes
indicesPorcentajes = list()
for x in range(len(porcentaje)):
indicesPorcentajes.append(x)
# Diccionario de indices: porcentajes
diccionarioPorcentaje = dict(zip(indicesPorcentajes, porcentaje))
dp = sorted(diccionarioPorcentaje.items(), key=operator.itemgetter(1)) # Ordena el diccionario en tuplas por el valor (0 = clave, 1 = valor)
print("\nDiccionario columna:porcentaje ordenado por porcentaje (descendente):")
dp.reverse() # ordena descendente con .reverse()
print(dp) # Imprime el diccionario en tuplas ordenado por valor
# Nuevo conjunto de datos (Datos ajustados con la media X Matriz de vectores propios)
nuevoConjuntoDatos = list()
NCDrow = list()
suma = 0
for i in range(len(matrizDatosAjustados)): # Filas de la matriz 1
for j in range(len(eigenvectors)): # Columnas de la matriz 2
for k in range(len(eigenvectors)): # Filas de la matriz 2
suma += (matrizDatosAjustados[i][k] * eigenvectors[k][j])
NCDrow.append(suma)
suma = 0
nuevoConjuntoDatos.append(NCDrow)
NCDrow = list()
print("\nMatriz de nuevo conjunto de datos:")
#print(nuevoConjuntoDatos)
NCD = pd.DataFrame(np.array(nuevoConjuntoDatos)) # Matriz de nuevo conjunto de datos con pandas
print(NCD)
# Guardar componentes en un archivo csv
NCD.columns = lcaracteristicas
name = str(input("\nIngrese el nombre de su archivo .csv: "))
NCD.to_csv(str(folder()) + str(name) + '.csv', header=True, sep=',', index=False)
print("\nSe ha generado un archivo " + str(name) + ".csv con los componentes")
def ACPK():
print("Algoritmo de ACPK")
# Cargar el archivo dataset
dataset = loadDataset()
#print(dataset)
#print(dataset.head())
# Se extraen las columnas del dataset
dataset.columns
#print(dataset.columns)
print("Descripción del dataset: ")
print(dataset.describe()) # Descripción estadistica de los datos
columns = len(dataset.columns) # Número total de columnas
#print(columns)
rows = len(dataset.index) # Número total de filas
#print(rows)
# Agrupando columnas por tipo de datos
tipos = dataset.columns.to_series().groupby(dataset.dtypes).groups
# Armando lista de columnas categóricas
try:
ctext = tipos[np.dtype('object')]
except KeyError:
ctext = list() # lista de columnas vacia en caso de que no haya categóricas
print("\nNúmero de columnas categoricas: " + str(len(ctext))) # cantidad de columnas con datos categóricos
# Armando lista de columnas numéricas
columnas = dataset.columns # lista total las columnas
cnum = list(set(columnas) - set(ctext)) # Total de columnas menos columnas no numéricas
print("Número de columnas numericas: " + str(len(cnum)))
# Lista de medias
#print(dataset.mean())
'''media = list()
for x in range(len(dataset.mean())):
media.append(dataset.mean()[x])
print(media)'''
media = dataset.mean().values.tolist() # Convertir la media del dataset a una lista
print("\nLista de medias: " + str(media))
#print(media)
# Lista de desviación estandar
#print(dataset.std())
'''destandar = list()
for x in range(len(dataset.std())):
destandar.append(dataset.std()[x])
print(destandar)'''
destandar = dataset.std().values.tolist() # Convertir la desviación estandar del dataset a una lista
print("Lista de desviación estandar: " + str(destandar))
#print(destandar)
# Lista de caracteristicas
lcaracteristicas = list()
for x in range(len(cnum)):
lcaracteristicas.append(columnas[x])
print("Lista de características: " + str(lcaracteristicas))
#print(lcaracteristicas)
# Todas las filas y todas las columnas del dataset en una lista
matriz = dataset.loc[:,].values
print("\nMatriz:")
print(matriz)
# ===========================================================================================================================
# Datos de la matriz
matrizDatos = list()
MDrow = list()
for x in range(rows):
for y in range(len(cnum)):
result = (matriz[x][y])
MDrow.append(result)
matrizDatos.append(MDrow)
MDrow = list()
print("\nMatriz de datos:")
#print(matrizDatos)
MD = pd.DataFrame(np.array(matrizDatos)) # Matriz de datos con pandas
print(MD)
# Transpuesta de la matriz de datos
Transpuesta = np.array(matrizDatos) # Convertir la lista a formato numpy
matrizDatosT = Transpuesta.transpose().tolist() # Convertir la lista numpy con la transpuesta a formato normal de lista
print("\nMatriz transpuesta:")
#print(matrizDatosT)
MDT = pd.DataFrame(np.array(matrizDatosT)) # Matriz de datos con pandas
print(MDT)
# Matriz de covarianza (Transpuesta X Matriz)
matrizCovarianza = list()
MCrow = list()
suma = 0
for i in range(len(matrizDatosT)): # Filas de la matriz 1
for j in range(len(cnum)): # Columnas de la matriz 2
for k in range(rows): # Filas de la matriz 2
suma += (matrizDatosT[i][k] * matrizDatos[k][j])
covarianza = (suma / (rows-1)) # Cada valor de la matriz de covarianza se debe dividir por n-1 (filas-1)
MCrow.append(covarianza)
suma = 0
matrizCovarianza.append(MCrow)
MCrow = list()
print("\nMatriz de covarianza:")
#print(matrizCovarianza)
MC = pd.DataFrame(np.array(matrizCovarianza)) # Matriz de covarianza con pandas
print(MC)
# Valores propios y vectores propios
evalues, evectors = la.eig(np.array(matrizCovarianza))
print("\nValores propios:")
eigenvalues = evalues.tolist()
print(eigenvalues)
print("\nVectores propios:")
print(evectors)
eigenvectors = evectors.tolist()
#print(eigenvectors)
# Suma de los valores propios
sumaEigenvalues = 0
for x in range(len(eigenvalues)):
sumaEigenvalues += eigenvalues[x]
print("\nSuma de los valores propios: " + str(sumaEigenvalues))
# Multiplicación de la matriz de datos por la matriz de vectores propios (Matriz de datos X Vectores propios)
matrizNueva = list()
MNrow = list()
suma = 0
for i in range(len(matrizDatos)): # Filas de la matriz 1
for j in range(len(eigenvectors)): # Columnas de la matriz 2
for k in range(len(eigenvectors)): # Filas de la matriz 2
suma += (matrizDatos[i][k] * eigenvectors[k][j])
MNrow.append(suma)
suma = 0
matrizNueva.append(MNrow)
MNrow = list()
print("\nMatriz de nueva:")
#print(matrizNueva)
MN = pd.DataFrame(np.array(matrizNueva)) # Matriz de nueva con pandas
print(MN)
# Guardar componentes en un archivo csv
MN.columns = lcaracteristicas
name = str(input("\nIngrese el nombre de su archivo .csv: "))
MN.to_csv(str(folder()) + str(name) + '.csv', header=True, sep=',', index=False)
print("\nSe ha generado un archivo " + str(name) + ".csv con los componentes")
def KNN():
print("Algoritmo de KNN")
# Se establece la selección de la metrica que se quiere
opcionMetrica = seleccion_metrica()
# Cargar el archivo dataset
dataset = loadDataset()
#print(dataset)
#print(dataset.head())
# Se extraen las columnas del dataset
dataset.columns
#print(dataset.columns)
print("Descripción del dataset: ")
print(dataset.describe()) # Descripción estadistica de los datos
columns = len(dataset.columns) # Número total de columnas
#print(columns)
rows = len(dataset.index) # Número total de filas
#print(rows)
# Agrupando columnas por tipo de datos
tipos = dataset.columns.to_series().groupby(dataset.dtypes).groups
# Armando lista de columnas categóricas
try:
ctext = tipos[np.dtype('object')]
except KeyError:
ctext = list() # lista de columnas vacia en caso de que no haya categóricas
print("\nNúmero de columnas categoricas: " + str(len(ctext))) # cantidad de columnas con datos categóricos
# Armando lista de columnas numéricas
columnas = dataset.columns # lista total las columnas
cnum = list(set(columnas) - set(ctext)) # Total de columnas menos columnas no numéricas
print("Número de columnas numericas: " + str(len(cnum)))
# Lista de medias
#print(dataset.mean())
'''media = list()
for x in range(len(dataset.mean())):
media.append(dataset.mean()[x])
print(media)'''
media = dataset.mean().values.tolist() # Convertir la media del dataset a una lista
print("\nLista de medias: " + str(media))
#print(media)
# Lista de desviación estandar
#print(dataset.std())
'''destandar = list()
for x in range(len(dataset.std())):
destandar.append(dataset.std()[x])
print(destandar)'''
destandar = dataset.std().values.tolist() # Convertir la desviación estandar del dataset a una lista
print("Lista de desviación estandar: " + str(destandar))
#print(destandar)
# Lista de caracteristicas
lcaracteristicas = list()
for x in range(len(cnum)):
lcaracteristicas.append(columnas[x])
print("Lista de características: " + str(lcaracteristicas))
#print(lcaracteristicas)
# Todas las filas y todas las columnas del dataset en una lista
matriz = dataset.loc[:,].values
print("\nMatriz:")
print(matriz)
# Matriz normalizada
matrizNormalizada = list()
MNrow = list()
for x in range(rows):
for y in range(len(cnum)):
result = ((matriz[x][y] - media[y]) / destandar[y])
MNrow.append(result)
matrizNormalizada.append(MNrow)
MNrow = list()
print("\nMatriz normalizada:")
#print(matrizNormalizada) # Matriz con los valores normalizados de los Clusters
MN = pd.DataFrame(np.array(matrizNormalizada)) # Matriz normalizada con pandas
print(MN)
# Matriz de distancia euclidiana
individuo_tabla = list()
lista_metrica = list()
matriz_distancia = list()
for n in range(rows):
individuo = vector_registro_matrizNormalizada(n, matrizNormalizada, len(cnum))
#print(individuo)
for v in range(rows):
for h in range(len(cnum)):
valor = matrizNormalizada[v][h]
individuo_tabla.append(valor)
#print(individuo_tabla)
metrica = seleccion_metrica_distancia(individuo, individuo_tabla, opcionMetrica)
#print(metrica)
lista_metrica.append(metrica)
individuo_tabla = list()
#print(lista_metrica)
matriz_distancia.append(lista_metrica)
lista_metrica = list()
print("\nMatriz de " + str(lista_metricas[opcionMetrica-1]) + ": ")
#print(matriz_distancia)
MD = pd.DataFrame(np.array(matriz_distancia)) # Matriz de distacia con pandas
print(MD)
'''
# Matriz de distancia euclidiana, triangular inferior
triangular_inferior = copy.deepcopy(matriz_distancia) # Copia de la lista
TIrow = list()
for x in range(0,len(triangular_inferior)):
for y in range(x,len(triangular_inferior)):
triangular_inferior[x][y] = 0
print("\nMatriz de distancia euclidiana triangular inferior:")
#print(triangular_inferior)
TI = pd.DataFrame(np.array(triangular_inferior)) # Matriz de distacia triangular inferior con pandas
print(TI)
'''
# Selección de las características para el gráfico
print()
for x in range(len(lcaracteristicas)):
print(str(x+1) + ". " + lcaracteristicas[x])
print("Seleccione dos características para el gráfico de Cluster: ")
# Lista de las caracteristicas seleccionadas
listaGrafica = list()
etiquetasGrafica = list()
for x in range(2):
nCluster = int(input("Característica " + str(x+1) + ": "))
listaGrafica.append(nCluster-1) # Se seleccionan las caracteristicas de la lista de acuerdo al numero ingresado
etiquetasGrafica.append(lcaracteristicas[nCluster-1]) # Etiquetas de los ejes de la gráfica, las características seleccionadas
print("Ejes de la gráfica: " + str(listaGrafica)) # Lista de ejes para la gráfica
print("Etiquetas de la gráfica: " + str(etiquetasGrafica))
# Todas las filas y dos columnas para la gráfica
matrizGrafica = MN.ix[:, [listaGrafica[0], listaGrafica[1]]].values
print("\nMatriz de la gráfica:")
print(matrizGrafica)
# =============================================================================================================================
# Número de vecinos cercanos
k = int(input("\nIngrese el número de K o vecinos cercanos: "))
while (k < 1 or k > rows):
k = int(input("El valor de K es incorrecto, debe estar entre 1" + " y " + str(rows) + ": "))
# Valor seleccionado aleatoriamente para ser el Cluster
aleatorio = random.randint(0, rows-1)
print("Valor seleccionado aleatoriamente: " + str(aleatorio))
# Lista de distancias con respecto al Cluster seleccionado
valorDistancias = matriz_distancia[aleatorio]
print("\nDistancias al punto del Cluster:")
print(valorDistancias)
# Lista de indices
indices = list()
for x in range(len(valorDistancias)):
indices.append(x)
# Diccionario de indices: valorDistancias
diccionario = dict(zip(indices, valorDistancias))
d = sorted(diccionario.items(), key=operator.itemgetter(1)) # Ordena el diccionario en tuplas por el valor (0 = clave, 1 = valor)
print("\nDiccionario vecino:ditancia ordenado por distancia:")
print(d) # Imprime el diccionario en tuplas ordenado por valor
# Llaves y valores en listas
llaves = list()
valores = list()
for x in range(len(diccionario)):
llaves.append(d[x][0])
valores.append(d[x][1])
#print(llaves)
#print(valores)
# k vecinos más cercanos con el nuevo dato, ejes X y Y
knnDistancia = list()
knnDatos = list()
for x in range(k):
#print(str(llaves[x]) + " " + str(valores[x])) # Vecino (indice) y su distancia
#print(matrizNormalizada[llaves[x]]) # Datos de los vecinos más cercanos
knnDistancia.append([llaves[x], valores[x]]) # Lista del vecino más cercano con su distancia
knnDatos.append(matrizNormalizada[llaves[x]]) # Lista de los datos de los vecinos más cercanos
print("\nMatriz de vecinos más cercano con su distancia:")
#print(knnDistancia)
print(pd.DataFrame(np.array(knnDistancia))) # Matriz de vecinos más cercano con su distancia
print("\nMatriz de los datos de los vecinos más cercanos:")
#print(knnDatos)
print(pd.DataFrame(np.array(knnDatos))) # Matriz de los datos de los vecinos más cercanos
'''
# Listas de los ejes X y Y de Knn # Otra forma de hacerlo
kEjeX = list()
kEjeY = list()
for x in range(k):
kEjeX.append(knnDatos[x][0])
kEjeY.append(knnDatos[x][1])
print(kEjeX) # Eje X de los datos vecinos más cercanos
print(kEjeY) # Eje Y de los datos vecinos más cercanos
# Listas de los ejes X y Y # Otra forma de hacerlo
ejeX = list()
ejeY = list()
for x in range(len(matrizNormalizada)):
ejeX.append(matrizNormalizada[x][0])
ejeY.append(matrizNormalizada[x][1])
print(ejeX)
print(ejeY)
'''
# DataFrame con pandas de los ejes X y Y de la matriz normalizada
ejes = pd.DataFrame(np.array(matrizGrafica))
ejeX = ejes.ix[:, 0]
ejeY = ejes.ix[:, 1]
# DataFrame con pandas de los ejes X y Y de la matriz de vecinos más cercanos
KNND = pd.DataFrame(np.array(knnDatos)) # Se convierte la lista de datos de vecinos más cercanos a DataFrame
matrizGrafica = KNND.ix[:, [listaGrafica[0], listaGrafica[1]]].values # Lista de los ejes que se escogieron de vecinos más cercanos
kEjes = pd.DataFrame(np.array(matrizGrafica))
kEjeX = kEjes.ix[:, 0]
kEjeY = kEjes.ix[:, 1]
# Radio tomado de la mayor distancia de los vecinos más cercanos
#radio = knnDistancia[k-1][1]
# Grafica de los datos normalizados
plt.plot(ejeX, ejeY, 'ro', marker='o', color='r', label="Valores", alpha=0.5) # Datos de la matriz normalizada en rojo
plt.plot(knnDatos[0][listaGrafica[0]], knnDatos[0][listaGrafica[1]], 'bo', marker='o', color='b', label="Valor nuevo") # Nuevo dato en azul
plt.plot(knnDatos[0][listaGrafica[0]], knnDatos[0][listaGrafica[1]], 'bo', marker='o', markersize=100, linewidth=0.5, alpha=0.2) # Área del nuevo dato
plt.plot(kEjeX, kEjeY, 'go', marker='o', color='g', label="Vecinos cerca", alpha=0.5) # Datos de la matriz de vecinos más cercanos en verde
plt.xlabel(etiquetasGrafica[0]) # Etiqueda en el eje X
plt.ylabel(etiquetasGrafica[1]) # Etiqueta en el eje Y
plt.grid(color='b', alpha=0.2, linestyle='dashed', linewidth=0.5) # Malla o grilla
plt.title('KNN, k = ' + str(k)) # Titulo de la gráfica
plt.legend(loc="lower right") # Legenda de la gráfica
plt.show()
def KMEANS():
print("Algoritmo de K-MEANS")
# Se establece la selección de la metrica que se quiere
opcionMetrica = seleccion_metrica()
# Cargar el archivo dataset
dataset = loadDataset()
#print(dataset)
#print(dataset.head())
# Se extrane las columnas del dataset
dataset.columns
print(dataset.columns)
print(dataset.describe()) # Descripción estadistica de los datos
columns = len(dataset.columns) # Número total de columnas
#print(columns)
rows = len(dataset.index) # Número total de filas
#print(rows)
# Agrupando columnas por tipo de datos
tipos = dataset.columns.to_series().groupby(dataset.dtypes).groups
# Armando lista de columnas categóricas
try:
ctext = tipos[np.dtype('object')]
except KeyError:
ctext = list() # lista de columnas vacia en caso de que no haya categóricas
print("\nNúmero de columnas categoricas: " + str(len(ctext))) # cantidad de columnas con datos categóricos
# Armando lista de columnas numéricas
columnas = dataset.columns # lista total las columnas
cnum = list(set(columnas) - set(ctext)) # Total de columnas menos columnas no numéricas
print("Número de columnas numericas: " + str(len(cnum)))
# Lista de medias
#print(dataset.mean())
'''media = list()
for x in range(len(dataset.mean())):
media.append(dataset.mean()[x])
print(media)'''
media = dataset.mean().values.tolist() # Convertir la media del dataset a una lista
print("\nLista de medias: " + str(media))
#print(media)
# Lista de desviación estandar
#print(dataset.std())
'''destandar = list()
for x in range(len(dataset.std())):
destandar.append(dataset.std()[x])
print(destandar)'''
destandar = dataset.std().values.tolist() # Convertir la desviación estandar del dataset a una lista
print("Lista de desviación estandar: " + str(destandar))
#print(destandar)
# Lista de caracteristicas
lcaracteristicas = list()
for x in range(len(cnum)):
lcaracteristicas.append(columnas[x])
print("Lista de características: " + str(lcaracteristicas))
#print(lcaracteristicas)
# Todas las filas y todas las columnas del dataset en una lista
matriz = dataset.loc[:,].values
print("\nMatriz:")
print(matriz)
# Matriz normalizada
matrizNormalizada = list()
MNrow = list()
for x in range(rows):
for y in range(len(cnum)):
result = ((matriz[x][y] - media[y]) / destandar[y])
MNrow.append(result)
matrizNormalizada.append(MNrow)
MNrow = list()
print("\nMatriz normalizada:")
#print(matrizNormalizada) # Matriz con los valores normalizados de los Clusters
MN = pd.DataFrame(np.array(matrizNormalizada)) # Matriz normalizada con pandas
print(MN)
# Matriz de distancia euclidiana
individuo_tabla = list()
lista_metrica = list()
matriz_distancia = list()
for n in range(rows):
individuo = vector_registro_matrizNormalizada(n, matrizNormalizada, len(cnum))
#print(individuo)
for v in range(rows):
for h in range(len(cnum)):
valor = matrizNormalizada[v][h]
individuo_tabla.append(valor)
#print(individuo_tabla)
metrica = seleccion_metrica_distancia(individuo, individuo_tabla, opcionMetrica)
#print(metrica)
lista_metrica.append(metrica)
individuo_tabla = list()
#print(lista_metrica)
matriz_distancia.append(lista_metrica)
lista_metrica = list()
print("\nMatriz de " + str(lista_metricas[opcionMetrica-1]) + ": ")
#print(matriz_distancia)
MD = pd.DataFrame(np.array(matriz_distancia)) # Matriz de distacia con pandas
print(MD)
'''
# Matriz de distancia euclidiana, triangular inferior
triangular_inferior = copy.deepcopy(matriz_distancia) # Copia de la lista
TIrow = list()
for x in range(0,len(triangular_inferior)):
for y in range(x,len(triangular_inferior)):
triangular_inferior[x][y] = 0
print("\nMatriz de distancia euclidiana triangular inferior:")
#print(triangular_inferior)
TI = pd.DataFrame(np.array(triangular_inferior)) # Matriz de distacia triangular inferior con pandas
print(TI)
'''
# Selección de las características para el gráfico
print()
for x in range(len(lcaracteristicas)):
print(str(x+1) + ". " + lcaracteristicas[x])
print("Seleccione dos características para el gráfico de Cluster: ")
# Lista de las caracteristicas seleccionadas
listaGrafica = list()
etiquetasGrafica = list()
for x in range(2):
nCluster = int(input("Característica " + str(x+1) + ": "))
listaGrafica.append(nCluster-1) # Se seleccionan las caracteristicas de la lista de acuerdo al numero ingresado
etiquetasGrafica.append(lcaracteristicas[nCluster-1]) # Etiquetas de los ejes de la gráfica, las características seleccionadas
print("Ejes de la gráfica: " + str(listaGrafica)) # Lista de ejes para la gráfica
print("Etiquetas de la gráfica: " + str(etiquetasGrafica))
# Todas las filas y dos columnas para la gráfica
matrizGrafica = MN.ix[:, [listaGrafica[0], listaGrafica[1]]].values
print("\nMatriz de la gráfica:")
print(matrizGrafica)
# =========================================================================================================================
# Número de cluster
nCluster = int(input("\nIngrese el número de N Clusters: "))
while (nCluster < 1 or nCluster > rows):
nCluster = int(input("El valor de N es incorrecto, debe estar entre 1" + " y " + str(rows) + ": "))
# Selección de los centroides de los Clusters aleatorios y sus indices hasta completar el número de Clusters
ClustersCentroides = list()
ClustersIndices = list()
x = 0
while (x < nCluster):
nRandom = random.randint(0, len(matrizNormalizada)-1)
if nRandom not in ClustersIndices: # Si el nRandom no esta en la lista ClustersIndices no entra
x += 1
ClustersIndices.append(nRandom)
valor = matrizNormalizada[nRandom]
ClustersCentroides.append(valor)
print("\nIndices de los Clusters: " + str(ClustersIndices)) # Indices de los Clusters
print("Centroides de los Clusters: ") # Clusters
print(pd.DataFrame(np.array(ClustersCentroides)))
# Distancia de los Clusters
ClustersDistancias = list()
for x in range(nCluster):
indice = ClustersIndices[x]
ClustersDistancias.append(matriz_distancia[indice])
print("\nDistancia de los Clusters: ")
#print(ClustersDistancias)
CD = pd.DataFrame(np.array(ClustersDistancias)) # Matriz de distacia de los Clusters
print(CD)
#print(CD.describe())
#print(CD.min())
# Lista de mínimos
ClustersMin = CD.min().values.tolist() # Convertir los mínimos de ClustersDistancias a una lista
print("\nLista de mínimos: " + str(ClustersMin))
#print(ClustersMin)
# Lista de Clusters
Clusters = list()
listaMin = list()
for x in range(len(matriz_distancia)):
for y in range(nCluster):
listaMin.append(ClustersDistancias[y][x])
Clusters.append(minimo(listaMin))
listaMin = list()
print("\nLista de Clusters: " + str(Clusters))
# Lista de indices de los Clusters
indices = list()
for x in range(len(Clusters)):
indices.append(x)
# Diccionario de indices: Clusters
ClustersDiccionario = dict(zip(indices, Clusters))
cd = sorted(ClustersDiccionario.items(), key=operator.itemgetter(1)) # Ordena el diccionario en tuplas por el valor (0 = clave, 1 = valor)
print("\nDiccionario valor:Cluster ordenado por Cluster:")
print(cd) # Imprime el diccionario en tuplas ordenado por valor
# Llaves y valores en listas
llaves = list()
valores = list()
for x in range(len(ClustersDiccionario)):
llaves.append(cd[x][0])
valores.append(cd[x][1])
#print(llaves)
#print(valores)
# Diccionario con las claves pero sin valores Clusters:Valores
ClustersDiccionario = {}
for x in range(nCluster):
ClustersDiccionario.setdefault('Cluster'+str(x),)
#print(ClustersDiccionario) # Diccionario vacio
# Diccionario con los Clusters completos
listaClusters = list()
for x in range(nCluster):
for y in range(len(Clusters)):
if valores[y] == x:
listaClusters.append(matrizNormalizada[llaves[y]])
ClustersDiccionario['Cluster'+str(x)] = listaClusters
listaClusters = list()
#print(ClustersDiccionario)
# Diccionario de cada Cluster
for x in range(nCluster):
print("\nCluster " + str(x) + ": " + str(ClustersDiccionario['Cluster'+str(x)]))
# ============================================================================================================================
# SEGUNDA ITERACIÓN
iteraciones = 1
respuesta = False
while (respuesta == False):
# Nuevos centroides del Cluster calculados por la media
mediaClustersNuevosCentroides = list()
for x in range(nCluster):
ClusterNuevo = pd.DataFrame(np.array(ClustersDiccionario['Cluster'+str(x)]))
mcn = ClusterNuevo.mean().values.tolist() # Convertir la media del ClusterX a una lista
mediaClustersNuevosCentroides.append(mcn)
print("\nLista de medias de los Cluster nuevos: ")
print(pd.DataFrame(np.array(mediaClustersNuevosCentroides)))
# Distancia de nuevos centroides
individuo_tabla = list()
lista_metrica = list()
matriz_distancia_cluster = list()
for n in range(nCluster):
for v in range(rows):
for h in range(len(cnum)):
valor = matrizNormalizada[v][h]
individuo_tabla.append(valor)
#print(individuo_tabla)
metrica = seleccion_metrica_distancia(mediaClustersNuevosCentroides[n], individuo_tabla, opcionMetrica)
#print(metrica)
lista_metrica.append(metrica)
individuo_tabla = list()
#print(lista_metrica)
matriz_distancia_cluster.append(lista_metrica)
lista_metrica = list()
print("\nMatriz de " + str(lista_metricas[opcionMetrica-1]) + " de los Cluster nuevos:")
#print(matriz_distancia_cluster)
MDC = pd.DataFrame(np.array(matriz_distancia_cluster)) # Matriz de distacia con pandas
print(MDC)
# Lista de mínimos nuevos
ClustersMinNuevos = MDC.min().values.tolist() # Convertir los mínimos de ClustersMinNuevos a una lista
print("\nLista de mínimos nuevos: " + str(ClustersMinNuevos))
#print(ClustersMin)
# Lista de Clusters nuevos
ClustersNuevos = list()
listaMinNuevos = list()
for x in range(len(matriz_distancia)):
for y in range(nCluster):
listaMinNuevos.append(matriz_distancia_cluster[y][x])
ClustersNuevos.append(minimo(listaMinNuevos))
listaMinNuevos = list()
print("\nLista de Clusters pasada: " + str(Clusters))
print("\nLista de Clusters nuevos: " + str(ClustersNuevos))
# Condición que compara la lista inicial de los Clusters con la lista nueva de los Clusters
if (Clusters == ClustersNuevos):
respuesta = True
else:
respuesta = False
#print(respuesta)
# Lista de indices de los Clusters nuevos
indices = list()
for x in range(len(ClustersNuevos)):
indices.append(x)
# Diccionario de indices: Clusters nuevos
ClustersDiccionarioNuevo = dict(zip(indices, ClustersNuevos))
cdn = sorted(ClustersDiccionarioNuevo.items(), key=operator.itemgetter(1)) # Ordena el diccionario en tuplas por el valor (0 = clave, 1 = valor)
print("\nDiccionario valor:ClusterNuevo ordenado por Cluster:")
print(cdn) # Imprime el diccionario en tuplas ordenado por valor
# Llaves y valores en listas
llaves = list()
valores = list()
for x in range(len(ClustersDiccionarioNuevo)):
llaves.append(cdn[x][0])
valores.append(cdn[x][1])
#print(llaves)
#print(valores)
# Diccionario con las claves pero sin valores Clusters:Valores
ClustersDiccionarioNuevo = {}
for x in range(nCluster):
ClustersDiccionarioNuevo.setdefault('Cluster'+str(x),)
#print(ClustersDiccionarioNuevo) # Diccionario vacio
# Diccionario con los Clusters completos
listaClustersNuevo = list()
for x in range(nCluster):
for y in range(len(Clusters)):
if valores[y] == x:
listaClustersNuevo.append(matrizNormalizada[llaves[y]])
ClustersDiccionarioNuevo['Cluster'+str(x)] = listaClustersNuevo
listaClustersNuevo = list()
#print(ClustersDiccionarioNuevo)
# Diccionario de cada Cluster
for x in range(nCluster):
print("\nCluster " + str(x) + ": " + str(ClustersDiccionarioNuevo['Cluster'+str(x)]))
iteraciones += 1
Clusters = copy.deepcopy(ClustersNuevos)
# Número de iteraciones despues de la segunda iteración
print("\nNúmero de iteraciones: " + str(iteraciones))
# DataFrame con pandas de los ejes X y Y de los centroides de los Clusters seleccionados
ejesCentroides = pd.DataFrame(np.array(mediaClustersNuevosCentroides))
ejeXCentroides = ejesCentroides.ix[:, listaGrafica[0]]
ejeYCentroides = ejesCentroides.ix[:, listaGrafica[1]]
# DataFrame con pandas de los ejes X y Y de Clusters X
colors = "grcmykwb" # Lista de colores de los Cluster
for x in range(nCluster):
ejesCluster = pd.DataFrame(np.array(ClustersDiccionarioNuevo['Cluster'+str(x)]))
print("\nCluster " + str(x) + ":")
print(ejesCluster)
ejeXCluster = ejesCluster.ix[:, listaGrafica[0]]
ejeYCluster = ejesCluster.ix[:, listaGrafica[1]]
# Datos (coordenadas) de cada Cluster X
# Se asignan estas lineas en este bucle para no crear ejes, ejex y ejey por cada grupo de Clusters
color = colors[x] # Color de cada Cluster
plt.plot(ejeXCluster, ejeYCluster, color+str('o'), marker='o', color=color, label='Cluster'+str(x), alpha=0.5) # Datos del Cluster 0
# Grafica de los datos normalizados
plt.plot(ejeXCentroides, ejeYCentroides, 'bo', marker='o', color='b', label="Centroides", alpha=0.3) # Datos de los centroides en rojo
# Área de cada centroide X
for x in range(nCluster):
plt.plot(ejeXCentroides[x], ejeYCentroides[x], 'bo', marker='o', markersize=100, linewidth=0.5, alpha=0.1) # Área de los centroides X
plt.xlabel(etiquetasGrafica[0]) # Etiqueda en el eje X
plt.ylabel(etiquetasGrafica[1]) # Etiqueta en el eje Y
plt.grid(color='b', alpha=0.2, linestyle='dashed', linewidth=0.5) # Malla o grilla
plt.title('K-MEANS, N Clusters = ' + str(nCluster) + ', Iteraciones = ' + str(iteraciones)) # Titulo de la gráfica
plt.legend(loc="lower right") # Legenda de la gráfica
plt.show()
def menu():
bucle = True
while (bucle == True):
print("\n========================================================================")
print("PROGRAMA DE INPLEMENTACIÓN DE ALGORITMOS DE REDUCCIÓN DE DIMENSIONALIDAD")
print("E IMPLEMENTACIÓN DE ALGORITMOS DE ClUSTERING")
print("========================================================================\n")
print("SELECCIONE UN ALGOTIRMO:")
print("------------------------------------------------------------------------")
print("* Análisis de componentes principales (ACP o PCA) .................1")
print("* Análisis de componentes principales por kernel (ACPK o KPCA) ....2")
print("* KNN (K-Vecinos más Cercanos) ....................................3")
print("* K-MEANS (Método de agrupamiento) ................................4")
print("* SALIR ...........................................................0")
print("------------------------------------------------------------------------")
opcion = input("Opción: ")
if (opcion != "1" and opcion != "2" and opcion != "3" and opcion != "4" and opcion != "0"):
print("La opción seleccionada no es valida")
while (opcion < "0" or opcion > "4"):
opcion = input("Ingrese nuevamente la opcion: ")
if (opcion == "1"):
ACP()
elif (opcion == "2"):
ACPK()
elif (opcion == "3"):
KNN()
elif (opcion == "4"):
KMEANS()
elif (opcion == "0"):
bucle = False
exit()
menu() | gpl-3.0 |
winnerineast/Origae-6 | origae/config/tensorflow.py | 684 | from __future__ import absolute_import
from . import option_list
def test_tf_import():
"""
Tests if tensorflow can be imported, returns if it went okay and optional error.
"""
try:
import tensorflow as tf# noqa
return True
except ImportError:
return False
tf_enabled = test_tf_import()
if not tf_enabled:
print('Tensorflow support disabled.')
if tf_enabled:
import tensorflow as tf
version = tf.__version__
option_list['tensorflow'] = {
'version': version,
'enabled': True,
}
else:
version = 'N.A.'
option_list['tensorflow'] = {
'version': version,
'enabled': False,
}
| gpl-3.0 |
langpavel/tampermonkey | src/notification.js | 2442 | /**
* @filename notification.js
* @author Jan Biniok <jan@biniok.net>
* @licence GPL v3
*/
function cleanup() {
window.removeEventListener("load", load, false);
window.removeEventListener("DOMContentLoaded", load, false);
}
function load() {
cleanup();
var params = window.location.search.split('&');
var t = 10000;
var notifyId = 0;
for (var k in params) {
var a = params[k].split('=');
if (a.length < 2) continue;
if (a[0] == "title" ||
a[0] == "text") {
var d = document.getElementById(a[0]);
d.innerHTML = decodeURIComponent(a[1]).replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
d.setAttribute("style", "display:block;");
} else if (a[0] == "delay") {
t = Number(decodeURI(a[1]));
} else if (a[0] == "image") {
var d = document.getElementById(a[0]);
d.src = decodeURIComponent(a[1]);
d.setAttribute("style", "display:block; width: 48px; height: 48px;");
} else if (a[0] == "notifyId") {
notifyId = a[1];
document.body.addEventListener("click", function() {
var bg = chrome.extension.getBackgroundPage();
var customEvent = document.createEvent("MutationEvent");
customEvent.initMutationEvent("notify_" + notifyId,
false,
false,
null,
null,
null,
null,
null);
bg.dispatchEvent(customEvent);
window.close();
});
}
}
if (t) window.setTimeout(function() { window.close(); }, t);
}
window.addEventListener("load", load, false);
window.addEventListener("DOMContentLoaded", load, false);
| gpl-3.0 |
jiunjiun/eatit_web | config/environments/test.rb | 1562 | EatitWeb::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| gpl-3.0 |
javieriserte/bioUtils | src/utils/mutualinformation/mimatrixviewer/matrixview/RedBlueGradientMatrixColoringStrategy.java | 1121 | package utils.mutualinformation.mimatrixviewer.matrixview;
import java.awt.Color;
public class RedBlueGradientMatrixColoringStrategy extends TwoColorsGradientWithCutOffMatrixColoringStrategy {
///////////////////////////////
// Constructors
private RedBlueGradientMatrixColoringStrategy(Color lowValues, Color highValues, Color undefinedValue, Color diagonalColor, double lowerValue, double higherValue, double cutOffValue) {
super(lowValues, highValues, undefinedValue, diagonalColor, lowerValue, higherValue,cutOffValue);
}
public RedBlueGradientMatrixColoringStrategy(double lowerValue, double higherValue, double cutOffValue) {
super(new Color(0,0,150), Color.red, new Color(0,50,0), Color.white , lowerValue, higherValue, cutOffValue);
}
public RedBlueGradientMatrixColoringStrategy(double lowerValue, double higherValue) {
super(new Color(0,0,150), Color.red, new Color(0,50,0), Color.white , lowerValue, higherValue, 6.5);
}
//////////////////////////////
// Public Interface
@Override
public String toString() {
return "Red And Blue Gradient. With CutOff:"+this.getMeanValue();
}
}
| gpl-3.0 |
OpportunityLiu/ExViewer | ExClient/Status/UserStatus.cs | 8819 | using HtmlAgilityPack;
using Opportunity.MvvmUniverse;
using Opportunity.MvvmUniverse.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Web.Http;
namespace ExClient.Status
{
public sealed class UserStatus : ObservableObject
{
private static readonly Uri infoUri = new Uri(Internal.DomainProvider.Eh.RootUri, "home.php");
internal UserStatus() { }
private static int deEntitizeAndParse(HtmlNode node)
{
return int.Parse(node.GetInnerText(), System.Globalization.NumberStyles.Integer);
}
private void analyzeToplists(HtmlNode toplistsDiv)
{
var table = toplistsDiv.Element("table").Descendants("table").FirstOrDefault();
if (table is null)
{
this.toplists.Clear();
return;
}
var newList = new List<ToplistItem>();
foreach (var toplistRecord in table.Elements("tr"))
{
var rankNode = toplistRecord.Descendants("strong").FirstOrDefault();
var listNode = toplistRecord.Descendants("a").FirstOrDefault();
if (rankNode is null)
throw new InvalidOperationException("rankNode not found");
if (listNode is null)
throw new InvalidOperationException("listNode not found");
var rank = int.Parse(rankNode.GetInnerText().TrimStart('#'), System.Globalization.NumberStyles.Integer);
var link = listNode.GetAttribute("href", default(Uri));
var listID = int.Parse(link.Query.Split('=').Last(), System.Globalization.NumberStyles.Integer);
newList.Add(new ToplistItem(rank, (ToplistName)listID));
}
this.toplists.Update(newList);
}
private void analyzeImageLimit(HtmlNode imageLimitDiv)
{
var values = imageLimitDiv.Descendants("strong").Select(deEntitizeAndParse).ToList();
if (values.Count != 4)
throw new InvalidOperationException("Wrong values.Count from analyzeImageLimit");
this.ImageUsage = values[0];
this.ImageUsageLimit = values[1];
this.ImageUsageRegenerateRatePerMinute = values[2];
this.ImageUsageResetCost = values[3];
}
private void analyzeModPower(HtmlNode modPowerDiv)
{
this.ModerationPower = deEntitizeAndParse(modPowerDiv.Descendants("div").Last());
var values = modPowerDiv.Descendants("td")
.Where(n => n.GetAttribute("style", "").Contains("font-weight:bold"))
.Select(n => n.GetInnerText())
.Where(s => !string.IsNullOrWhiteSpace(s) && s[0] != '=')
.Select(double.Parse)
.ToList();
if (values.Count != 8)
throw new InvalidOperationException("Wrong values.Count from analyzeModPower");
this.ModerationPowerBase = values[0];
this.ModerationPowerAwards = values[1];
this.ModerationPowerTagging = values[2];
this.ModerationPowerLevel = values[3];
this.ModerationPowerDonations = values[4];
this.ModerationPowerForumActivity = values[5];
this.ModerationPowerUploadsAndHatH = values[6];
this.ModerationPowerAccountAge = values[7];
this.ModerationPowerCaculated = values.Take(3).Sum() + Math.Min(values.Skip(3).Take(5).Sum(), 25);
}
public async Task RefreshAsync()
{
var doc = await Client.Current.HttpClient.GetDocumentAsync(infoUri);
try
{
analyzeDoc(doc);
}
catch (Exception ex)
{
throw new InvalidOperationException(LocalizedStrings.Resources.WrongApiResponse, ex);
}
}
private void analyzeDoc(HtmlDocument doc)
{
if (doc is null)
throw new ArgumentNullException(nameof(doc));
var contentDivs = doc.DocumentNode
.Element("html").Element("body").Element("div")
.Elements("div", "homebox").ToList();
if (contentDivs.Count != 5)
throw new InvalidOperationException("Wrong `homebox` count");
analyzeImageLimit(contentDivs[0]);
var ehTrackerDiv = contentDivs[1];
var totalGPGainedDiv = contentDivs[2];
analyzeToplists(contentDivs[3]);
analyzeModPower(contentDivs[4]);
}
#region Image Limits
private int imageUsage;
private int imageUsageLimit = 5000;
private int imageUsageRegenerateRatePerMinute = 3;
private int imageUsageResetCost;
public int ImageUsage
{
get => this.imageUsage; private set => Set(ref this.imageUsage, value);
}
public int ImageUsageLimit
{
get => this.imageUsageLimit; private set => Set(ref this.imageUsageLimit, value);
}
public int ImageUsageRegenerateRatePerMinute
{
get => this.imageUsageRegenerateRatePerMinute; private set => Set(ref this.imageUsageRegenerateRatePerMinute, value);
}
public int ImageUsageResetCost
{
get => this.imageUsageResetCost; private set => Set(ref this.imageUsageResetCost, value);
}
public IAsyncAction ResetImageUsageAsync()
{
return AsyncInfo.Run(async token =>
{
var p = Client.Current.HttpClient.PostAsync(infoUri, new KeyValuePair<string, string>("act", "limits"));
token.Register(p.Cancel);
var r = await p;
var html = await r.Content.ReadAsStringAsync();
var doc = new HtmlDocument();
doc.LoadHtml(html);
try
{
analyzeDoc(doc);
}
catch (Exception)
{
await RefreshAsync();
}
});
}
#endregion
#region Toplist
private readonly ObservableList<ToplistItem> toplists = new ObservableList<ToplistItem>();
public ObservableListView<ToplistItem> Toplists => this.toplists.AsReadOnly();
#endregion
#region Moderation Power
private double moderationPower = 1;
private double moderationPowerCaculated = 1;
private double moderationPowerBase = 1;
private double moderationPowerAwards;
private double moderationPowerTagging;
private double moderationPowerLevel;
private double moderationPowerDonations;
private double moderationPowerForumActivity;
private double moderationPowerUploadsAndHatH;
private double moderationPowerAccountAge;
public double ModerationPower
{
get => this.moderationPower; private set => Set(ref this.moderationPower, value);
}
public double ModerationPowerCaculated
{
get => this.moderationPowerCaculated; private set => Set(ref this.moderationPowerCaculated, value);
}
public double ModerationPowerBase
{
get => this.moderationPowerBase; private set => Set(ref this.moderationPowerBase, value);
}
public double ModerationPowerAwards
{
get => this.moderationPowerAwards; private set => Set(ref this.moderationPowerAwards, value);
}
public double ModerationPowerTagging
{
get => this.moderationPowerTagging; private set => Set(ref this.moderationPowerTagging, value);
}
public double ModerationPowerLevel
{
get => this.moderationPowerLevel; private set => Set(ref this.moderationPowerLevel, value);
}
public double ModerationPowerDonations
{
get => this.moderationPowerDonations; private set => Set(ref this.moderationPowerDonations, value);
}
public double ModerationPowerForumActivity
{
get => this.moderationPowerForumActivity; private set => Set(ref this.moderationPowerForumActivity, value);
}
public double ModerationPowerUploadsAndHatH
{
get => this.moderationPowerUploadsAndHatH; private set => Set(ref this.moderationPowerUploadsAndHatH, value);
}
public double ModerationPowerAccountAge
{
get => this.moderationPowerAccountAge; private set => Set(ref this.moderationPowerAccountAge, value);
}
#endregion
}
}
| gpl-3.0 |
automenta/adams-core | src/main/java/adams/event/FlowSetupStateEvent.java | 2156 | /*
* 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/>.
*/
/*
* FlowSetupChangeEvent.java
* Copyright (C) 2009 University of Waikato, Hamilton, New Zealand
*/
package adams.event;
import java.util.EventObject;
import adams.flow.setup.FlowSetup;
/**
* Event that gets sent by a FlowSetup when the execution of a flow has
* started, finished, etc.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 4584 $
*/
public class FlowSetupStateEvent
extends EventObject {
/** for serialization. */
private static final long serialVersionUID = -113405042251910190L;
/**
* The type of event.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 4584 $
*/
public static enum Type {
/** flow was modified. */
MODIFIED,
/** flow started. */
STARTED,
/** successfully finished. */
FINISHED,
/** an error occurred. */
ERROR;
}
/** the type of event. */
protected Type m_Type;
/**
* Initializes the event.
*
* @param source the setup that triggered the event
* @param type the type of event
*/
public FlowSetupStateEvent(FlowSetup source, Type type) {
super(source);
m_Type = type;
}
/**
* Returns the setup that triggered the event.
*
* @return the setup
*/
public FlowSetup getFlowSetup() {
return (FlowSetup) getSource();
}
/**
* Returns the type of event.
*
* @return the type
*/
public Type getType() {
return m_Type;
}
}
| gpl-3.0 |
remcopeereboom/algs4ruby | spec/algs4ruby/fundamentals/union_find_quick_union_spec.rb | 121 | require 'spec_helper'
module Algs4Ruby
describe UnionFindQuickUnion do
it_behaves_like 'a disjoint-set'
end
end
| gpl-3.0 |
flower-platform/flower-platform-4 | org.flowerplatform.codesync.regex/src/org/flowerplatform/codesync/regex/controller/action/CheckStateNodeConfigurationProcessor.java | 655 | package org.flowerplatform.codesync.regex.controller.action;
import static org.flowerplatform.codesync.regex.CodeSyncRegexConstants.ACTION_PROPERTY_VALID_STATES_PROPERTY;
import org.flowerplatform.codesync.regex.action.CheckStateAction;
import org.flowerplatform.core.node.remote.Node;
import org.flowerplatform.util.regex.RegexAction;
/**
* @author Elena Posea
*/
public class CheckStateNodeConfigurationProcessor extends RegexActionConfigurationProcessor {
@Override
protected RegexAction createRegexAction(Node node) {
return new CheckStateAction((String) node.getPropertyValue(ACTION_PROPERTY_VALID_STATES_PROPERTY));
}
}
| gpl-3.0 |
yashpungaliya/MailingListParser | lib/analysis/author/time_statistics.py | 9723 | from util.read_utils import *
import json
import os.path
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def inv_func(x, a, b, c):
return a/x + b/(x**2) + c
def conversation_refresh_times(headers_filename, nodelist_filename, edgelist_filename, foldername, time_ubound = None, time_lbound = None, plot=False):
"""
:param json_data:
:param discussion_graph:
:return:
"""
# Time limit can be specified here in the form of a timestamp in one of the identifiable formats. All messages
# that have arrived after time_ubound and before time_lbound will be ignored.
# If ignore_lat is true, then messages that belong to threads that have only a single author are ignored.
ignore_lat = False
discussion_graph = nx.DiGraph()
email_re = re.compile(r'[\w\.-]+@[\w\.-]+')
msgs_before_time = set()
json_data = dict()
if time_ubound is None:
time_ubound = time.strftime("%a, %d %b %Y %H:%M:%S %z")
time_ubound = get_datetime_object(time_ubound)
if time_lbound is None:
time_lbound = "Sun, 01 Jan 2001 00:00:00 +0000"
time_lbound = get_datetime_object(time_lbound)
print("All messages before", time_ubound, "and after", time_lbound, "are being considered.")
# Add nodes into NetworkX graph by reading from CSV file
if not ignore_lat:
with open(nodelist_filename, "r") as node_file:
for pair in node_file:
node = pair.split(';', 2)
if get_datetime_object(node[2].strip()) < time_ubound:
node[0] = int(node[0])
msgs_before_time.add(node[0])
from_addr = email_re.search(node[1].strip())
from_addr = from_addr.group(0) if from_addr is not None else node[1].strip()
discussion_graph.add_node(node[0], time=node[2].strip(), color="#ffffff", style='bold',
sender=from_addr)
node_file.close()
print("Nodes added.")
if len(msgs_before_time) == 0:
return "No messages!"
# Add edges into NetworkX graph by reading from CSV file
with open(edgelist_filename, "r") as edge_file:
for pair in edge_file:
edge = pair.split(';')
edge[0] = int(edge[0])
edge[1] = int(edge[1])
if edge[0] in msgs_before_time and edge[1] in msgs_before_time:
discussion_graph.add_edge(*edge)
edge_file.close()
print("Edges added.")
else:
lone_author_threads = get_lone_author_threads(False)
# Add nodes into NetworkX graph only if they are not a part of a thread that has only a single author
with open(nodelist_filename, "r") as node_file:
for pair in node_file:
node = pair.split(';', 2)
node[0] = int(node[0])
if get_datetime_object(node[2].strip()) < time_ubound and node[0] not in lone_author_threads:
msgs_before_time.add(node[0])
from_addr = email_re.search(node[1].strip())
from_addr = from_addr.group(0) if from_addr is not None else node[1].strip()
discussion_graph.add_node(node[0], time=node[2].strip(), color="#ffffff", style='bold',
sender=from_addr)
node_file.close()
print("Nodes added.")
if len(msgs_before_time) == 0:
return "No messages!"
# Add edges into NetworkX graph only if they are not a part of a thread that has only a single author
with open(edgelist_filename, "r") as edge_file:
for pair in edge_file:
edge = pair.split(';')
edge[0] = int(edge[0])
edge[1] = int(edge[1])
if edge[0] not in lone_author_threads and edge[1] not in lone_author_threads:
if edge[0] in msgs_before_time and edge[1] in msgs_before_time:
discussion_graph.add_edge(*edge)
edge_file.close()
print("Edges added.")
if not ignore_lat:
with open(headers_filename, 'r') as json_file:
for chunk in lines_per_n(json_file, 9):
json_obj = json.loads(chunk)
json_obj['Message-ID'] = int(json_obj['Message-ID'])
json_obj['Time'] = datetime.datetime.strptime(json_obj['Time'], "%a, %d %b %Y %H:%M:%S %z")
if time_lbound <= json_obj['Time'] < time_ubound:
# print("\nFrom", json_obj['From'], "\nTo", json_obj['To'], "\nCc", json_obj['Cc'])
from_addr = email_re.search(json_obj['From'])
json_obj['From'] = from_addr.group(0) if from_addr is not None else json_obj['From']
json_obj['To'] = set(email_re.findall(json_obj['To']))
json_obj['Cc'] = set(email_re.findall(json_obj['Cc'])) if json_obj['Cc'] is not None else None
# print("\nFrom", json_obj['From'], "\nTo", json_obj['To'], "\nCc", json_obj['Cc'])
json_data[json_obj['Message-ID']] = json_obj
else:
lone_author_threads = get_lone_author_threads(False)
with open(headers_filename, 'r') as json_file:
for chunk in lines_per_n(json_file, 9):
json_obj = json.loads(chunk)
json_obj['Message-ID'] = int(json_obj['Message-ID'])
if json_obj['Message-ID'] not in lone_author_threads:
json_obj['Time'] = datetime.datetime.strptime(json_obj['Time'], "%a, %d %b %Y %H:%M:%S %z")
if time_lbound <= json_obj['Time'] < time_ubound:
# print("\nFrom", json_obj['From'], "\nTo", json_obj['To'], "\nCc", json_obj['Cc'])
from_addr = email_re.search(json_obj['From'])
json_obj['From'] = from_addr.group(0) if from_addr is not None else json_obj['From']
json_obj['To'] = set(email_re.findall(json_obj['To']))
json_obj['Cc'] = set(email_re.findall(json_obj['Cc'])) if json_obj['Cc'] is not None else None
# print("\nFrom", json_obj['From'], "\nTo", json_obj['To'], "\nCc", json_obj['Cc'])
json_data[json_obj['Message-ID']] = json_obj
print("JSON data loaded.")
# The list crt stores the conversation refresh times between authors as a list of tuples containing the author
# email IDs and the time in seconds.
crt = list()
# The last_conv_time dictionary stores the timestamp of the authors' last conversation. The items in the dictionary
# are referenced by a set containing the authors' email IDs.
last_conv_time = dict()
for msg_id, message in sorted(json_data.items(), key = lambda x1: x1[1]['Time']):
if message['Cc'] is None:
addr_list = message['To']
else:
addr_list = message['To'] | message['Cc']
for to_address in addr_list:
if to_address > message['From']:
addr1 = message['From']
addr2 = to_address
else:
addr2 = message['From']
addr1 = to_address
if last_conv_time.get((addr1, addr2), None) is None:
last_conv_time[(addr1, addr2)] = (message['Message-ID'], message['Time'])
elif not nx.has_path(discussion_graph, message['Message-ID'], last_conv_time[(addr1, addr2)][0])\
and not nx.has_path(discussion_graph, last_conv_time[(addr1, addr2)][0], message['Message-ID']):
crt.append((message['From'], to_address,
(message['Time']-last_conv_time[((addr1, addr2))][1]).total_seconds()))
last_conv_time[(addr1, addr2)] = (message['Message-ID'], message['Time'])
if len(crt) != 0:
if not os.path.exists(foldername):
os.makedirs(foldername)
with open(foldername + "conversation_refresh_times.csv", mode='w') as dist_file:
dist_file.write("From Address;To Address;Conv. Refresh Time\n")
for from_addr, to_address, crtime in crt:
if crtime > 9:
dist_file.write("{0};{1};{2}\n".format(from_addr, to_address, str(crtime)))
dist_file.close()
if plot:
crt = sorted([z for x, y, z in crt if z > 9])[:int(.9*len(crt))]
y, x1 = np.histogram(crt, bins=50)
y = list(y)
max_y = sum(y)
if max_y != 0:
y = [y1 / max_y for y1 in y]
x = list()
for i1 in range(len(x1)-1):
x.append((x1[i1]+x1[i1+1])/2)
popt, pcov = curve_fit(inv_func, x, y)
a, b, c = popt
plt.figure()
axes = plt.gca()
axes.set_xlim([0, max(x)])
axes.set_ylim([0, max(y)])
plt.plot(x, y, linestyle='--', color='b', label="Data")
plt.savefig(foldername + 'conversation_refresh_times.png')
x_range = np.linspace(min(x), max(x), 500)
plt.plot(x_range, a/x_range + b/(x_range**2) + c, 'r-', label="Fitted Curve")
plt.legend()
plt.savefig(foldername + 'conversation_refresh_times_inv.png')
plt.close()
return None
else:
return "No messages!"
| gpl-3.0 |
trejkaz/hex | main/src/main/java/org/trypticon/hex/gui/notebook/Notebook.java | 3006 | /*
* Hex - a hex viewer and annotator
* Copyright (C) 2009-2014 Trejkaz, Hex Project
*
* 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.trypticon.hex.gui.notebook;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URL;
import org.jetbrains.annotations.NonNls;
import org.trypticon.hex.binary.Binary;
import org.trypticon.hex.gui.anno.ExtendedAnnotationCollection;
/**
* Holds information about a single notebook.
*
* @author trejkaz
*/
public interface Notebook {
/**
* <p>Opens the notebook. Ultimately this means opening the binary.</p>
*
* <p>This is distinct from the constructor as this class can be thought to
* be serialisable, even though we are not performing the serialisation
* using the normal {@code Serializable} API.</p>
*
* @throws IOException if an I/O error prevents opening the binary.
*/
void open() throws IOException;
/**
* Closes the notebook.
*/
void close();
/**
* Gets the location from which the notebook was opened, or to which it was last saved.
*
* @return the notebook location.
*/
URL getNotebookLocation();
/**
* <p>Sets the location of the notebook.</p>
*
* <p>Also indicates that the notebook was just saved to that location, thus
* sets the dirty flag to {@code false}.</p>
*
* @param notebookLocation the new notebook location.
* @see #getNotebookLocation()
*/
void setNotebookLocation(URL notebookLocation);
URL getBinaryLocation();
ExtendedAnnotationCollection getAnnotations();
Binary getBinary();
/**
* Tests if the notebook is open.
*
* @return {@code true} if it is open, {@code false} if it is closed.
*/
boolean isOpen();
/**
* Adds a listener for property change events.
*
* @param propertyName the name of the property to listen to.
* @param listener the listener to add.
*/
void addPropertyChangeListener(@NonNls String propertyName, PropertyChangeListener listener);
/**
* Removes a listener from property change events.
*
* @param propertyName the name of the property to listen to.
* @param listener the listener to remove.
*/
void removePropertyChangeListener(@NonNls String propertyName, PropertyChangeListener listener);
}
| gpl-3.0 |
Akatsuki06/Hillffair | app/src/main/java/com/appteamnith/hillffair/custom_views/EditorView.java | 7777 | package com.appteamnith.hillffair.custom_views;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.appteamnith.hillffair.R;
public class EditorView extends ScrollView {
private static final int EDIT_PADDING_TOP = 10;
private static final int EDIT_PADDING = 10;
private LinearLayout allLayout;
private LayoutInflater inflater;
private EditText lastEditText;
private OnFocusChangeListener focusChangeListener;
private OnKeyListener keyListener;
private OnClickListener onClickListener;
private int viewTag = 1;
public EditorView(Context context) {
this(context, null);
}
public EditorView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EditorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflater = LayoutInflater.from(context);
allLayout = new LinearLayout(context);
allLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
addView(allLayout, layoutParams);
onClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
allLayout.removeView(view);
}
};
focusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
lastEditText = (EditText) view;
}
}
};
keyListener = new OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.getKeyCode() == KeyEvent.KEYCODE_DEL) {
EditText editText = (EditText) view;
onBackPress(editText);
}
return false;
}
};
EditText e = createEditText("Title", dip2px(10));
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
allLayout.addView(e, p);
EditText content = createEditText("Type Content or Insert Image", dip2px(10));
LinearLayout.LayoutParams contentp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
allLayout.addView(content, contentp
);
lastEditText = content;
}
private EditText createEditText(String hint, int Padding) {
EditText editText = (EditText) inflater.inflate(R.layout.item_edittext, null);
editText.setTag(viewTag++);
editText.setOnFocusChangeListener(focusChangeListener);
editText.setOnKeyListener(keyListener);
editText.setPadding(dip2px(EDIT_PADDING_TOP), Padding, dip2px(EDIT_PADDING_TOP), 0);
editText.setHint(hint);
return editText;
}
private void createImageViewAtIndex(Bitmap bmp, int index) {
ImageView imageView = (ImageView) inflater.inflate(R.layout.item_image, null);
imageView.setImageBitmap(bmp);
int imageHeight = getWidth() * bmp.getHeight() / bmp.getWidth();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, imageHeight);
imageView.setLayoutParams(lp);
imageView.setOnClickListener(onClickListener);
allLayout.addView(imageView, index);
}
private void createEditTextAtIndex(String text, int index) {
EditText e = createEditText("", dip2px(10));
e.setText(text);
allLayout.addView(e, index);
}
private void onBackPress(EditText editText) {
int selection = editText.getSelectionStart();
if (selection == 0) {
int viewIndex = allLayout.indexOfChild(editText);
View v = allLayout.getChildAt(viewIndex - 1);
if (v != null) {
if (v instanceof EditText) {
if ((int) v.getTag() != 1) {
String s1 = editText.getText().toString();
EditText q = (EditText) v;
String s2 = q.getText().toString();
allLayout.removeView(editText);
q.setText(s1 + s2);
q.requestFocus();
q.setSelection(s2.length(), s2.length());
lastEditText = q;
}
} else if (v instanceof ImageView) {
allLayout.removeView(v);
}
}
}
}
public void addImage(Bitmap b) {
String text1 = lastEditText.getText().toString();
int pos = lastEditText.getSelectionStart();
String text2 = text1.substring(0, pos).trim();
int index = allLayout.indexOfChild(lastEditText);
if (text1.isEmpty() && (int) lastEditText.getTag() != 1) {
createImageViewAtIndex(b, index);
} else {
lastEditText.setText(text2);
String t = text1.substring(pos).trim();
if (allLayout.getChildCount() - 1 == index || !t.isEmpty()) {
createEditTextAtIndex(t, index + 1);
}
createImageViewAtIndex(b, index + 1);
lastEditText.requestFocus();
lastEditText.setSelection(text2.length(), text2.length());
}
hideKeyBoard();
}
public void hideKeyBoard() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(lastEditText.getWindowToken(), 0);
}
private int dip2px(float dipValue) {
float m = getContext().getResources().getDisplayMetrics().density;
return (int) (dipValue * m + 0.5f);
}
public AddTopic buildEditData() {
String topic="",detail="";
int num = allLayout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = allLayout.getChildAt(index);
Log.d("index",""+index);
if (itemView instanceof EditText) {
EditText item = (EditText) itemView;
if (index == 0) {
topic=item.getText().toString();
}
if (index == 2) {
detail=item.getText().toString();
}
else if(index==1){
detail=item.getText().toString();
}
}
/*
else if (itemView instanceof ImageView) {
ImageView item = (ImageView) itemView;
}*/
}
AddTopic itemData = new AddTopic(topic,detail);
return itemData;
}
public class AddTopic{
public String title,detail,imageUrl;
public AddTopic(String title, String detail) {
this.title = title;
this.detail = detail;
}
public AddTopic(String title, String detail, String imageUrl) {
this.title = title;
this.detail = detail;
this.imageUrl = imageUrl;
}
}
}
| gpl-3.0 |
adventurerscodex/adventurerscodex | src/charactersheet/models/dm/encounter_sections/encounter_item.js | 3607 | import {
Fixtures,
Utility
} from 'charactersheet/utilities';
import { KOModel } from 'hypnos/lib/models/ko';
import ko from 'knockout';
export class EncounterItem extends KOModel {
static __skeys__ = ['core', 'encounters', 'treasures'];
static mapping = {
include: [
'coreUuid',
'encounterUuid',
'type',
'uuid',
'name',
'description',
'quantity',
'weight',
'cost',
'currencyDenomination'
]
};
uuid = ko.observable();
coreUuid = ko.observable();
encounterUuid = ko.observable();
type = ko.observable();
// Item Fields
name = ko.observable('');
description = ko.observable('');
quantity = ko.observable(1);
weight = ko.observable(0);
cost = ko.observable(0);
currencyDenomination = ko.observable('');
SHORT_DESCRIPTION_MAX_LENGTH = 100;
DESCRIPTION_MAX_LENGTH = 200;
itemCurrencyDenominationOptions = Fixtures.general.currencyDenominationList;
totalCost = ko.pureComputed(() => {
if (this.quantity() && this.quantity() > 0
&& this.cost() && this.cost() > 0
) {
return parseInt(this.quantity()) * parseInt(this.cost());
}
return 0;
}, this);
totalWeight = ko.pureComputed(() => {
if (this.quantity() && this.weight()) {
return parseInt(this.quantity()) * parseFloat(this.weight());
}
return 0;
}, this);
nameLabel = ko.pureComputed(() => {
return this.name();
});
propertyLabel = ko.pureComputed(() => {
return 'N/A';
});
descriptionLabel = ko.pureComputed(() => {
return this.shortDescription();
});
shortDescription = ko.pureComputed(() => {
return Utility.string.truncateStringAtLength(this.description(), this.SHORT_DESCRIPTION_MAX_LENGTH);
});
descriptionHTML = ko.pureComputed(() => {
if (!this.description()) {
return '<div class="h3"><small>Add a description via the edit tab.</small></div>';
}
return this.description();
});
costLabel = ko.pureComputed(() => {
return this.cost() !== '' ? this.cost() + ' ' + this.currencyDenomination() : '';
}, this);
totalCostLabel = ko.pureComputed(() => {
return this.totalCost() !== '' ? this.totalCost() + ' ' + this.currencyDenomination() : '';
}, this);
weightLabel = ko.pureComputed(() => {
return this.weight() !== '' && this.weight() >= 0 ? this.weight() + ' lbs.' : '0 lbs.';
});
totalWeightLabel = ko.pureComputed(() => {
return this.totalWeight() >= 0 ? this.totalWeight() + ' lbs.' : '0 lbs.';
}, this);
}
EncounterItem.validationConstraints = {
fieldParams: {
name: {
required: true,
maxlength: 256,
},
weight: {
required: true,
type: 'number',
max: 10000,
min: -10000,
step: 1,
},
quantity: {
required: true,
type: 'number',
max: 10000,
min: -10000,
step: 1,
},
cost: {
required: true,
type: 'number',
max: 10000,
min: -10000,
step: 1,
},
currencyDenomination: {
required: true,
type: 'text',
maxlength: 256,
},
description: {
required: false,
type: 'text',
},
},
};
| gpl-3.0 |
dnjohnstone/hyperspy | hyperspy/tests/drawing/test_plot_signal1d.py | 10216 | # Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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.
#
# HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>.
import os
from shutil import copyfile
import matplotlib.pyplot as plt
import numpy as np
import pytest
import scipy.misc
import hyperspy.api as hs
from hyperspy.misc.test_utils import update_close_figure
from hyperspy.signals import Signal1D
from hyperspy.drawing.signal1d import Signal1DLine
from hyperspy.tests.drawing.test_plot_signal import _TestPlot
scalebar_color = 'blue'
default_tol = 2.0
baseline_dir = 'plot_signal1d'
style_pytest_mpl = 'default'
style = ['default', 'overlap', 'cascade', 'mosaic', 'heatmap']
@pytest.fixture
def mpl_generate_path_cmdopt(request):
return request.config.getoption("--mpl-generate-path")
def _generate_filename_list(style):
path = os.path.dirname(__file__)
filename_list = ['test_plot_spectra_%s' % s for s in style] + \
['test_plot_spectra_rev_%s' % s for s in style]
filename_list2 = []
for filename in filename_list:
for i in range(0, 4):
filename_list2.append(os.path.join(path, baseline_dir,
'%s%i.png' % (filename, i)))
return filename_list2
@pytest.fixture
def setup_teardown(request, scope="class"):
mpl_generate_path_cmdopt = request.config.getoption("--mpl-generate-path")
# SETUP
# duplicate baseline images to match the test_name when the
# parametrized 'test_plot_spectra' are run. For a same 'style', the
# expected images are the same.
if mpl_generate_path_cmdopt is None:
for filename in _generate_filename_list(style):
copyfile("%s.png" % filename[:-5], filename)
yield
# TEARDOWN
# Create the baseline images: copy one baseline image for each test
# and remove the other ones.
if mpl_generate_path_cmdopt:
for filename in _generate_filename_list(style):
copyfile(filename, "%s.png" % filename[:-5])
# Delete the images that have been created in 'setup_class'
for filename in _generate_filename_list(style):
os.remove(filename)
@pytest.mark.usefixtures("setup_teardown")
class TestPlotSpectra():
s = hs.signals.Signal1D(scipy.misc.ascent()[100:160:10])
# Add a test signal with decreasing axis
s_reverse = s.deepcopy()
s_reverse.axes_manager[1].offset = 512
s_reverse.axes_manager[1].scale = -1
def _generate_parameters(style):
parameters = []
for s in style:
for fig in [True, None]:
for ax in [True, None]:
parameters.append([s, fig, ax])
return parameters
def _generate_ids(style, duplicate=4):
ids = []
for s in style:
ids.extend([s] * duplicate)
return ids
@pytest.mark.parametrize(("style", "fig", "ax"),
_generate_parameters(style),
ids=_generate_ids(style))
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_spectra(self, style, fig, ax):
if fig:
fig = plt.figure()
if ax:
fig = plt.figure()
ax = fig.add_subplot(111)
ax = hs.plot.plot_spectra(self.s, style=style, legend='auto',
fig=fig, ax=ax)
if style == 'mosaic':
ax = ax[0]
return ax.figure
@pytest.mark.parametrize(("style", "fig", "ax"),
_generate_parameters(style),
ids=_generate_ids(style))
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_spectra_rev(self, style, fig, ax):
if fig:
fig = plt.figure()
if ax:
fig = plt.figure()
ax = fig.add_subplot(111)
ax = hs.plot.plot_spectra(self.s_reverse, style=style, legend='auto',
fig=fig, ax=ax)
if style == 'mosaic':
ax = ax[0]
return ax.figure
@pytest.mark.parametrize("figure", ['1nav', '1sig', '2nav', '2sig'])
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_spectra_sync(self, figure):
s1 = hs.signals.Signal1D(scipy.misc.face()).as_signal1D(0).inav[:, :3]
s2 = s1.deepcopy() * -1
hs.plot.plot_signals([s1, s2])
if figure == '1nav':
return s1._plot.signal_plot.figure
if figure == '1sig':
return s1._plot.navigator_plot.figure
if figure == '2nav':
return s2._plot.navigator_plot.figure
if figure == '2sig':
return s2._plot.navigator_plot.figure
def test_plot_spectra_legend_pick(self):
x = np.linspace(0., 2., 512)
n = np.arange(1, 5)
x_pow_n = x[None, :]**n[:, None]
s = hs.signals.Signal1D(x_pow_n)
my_legend = [r'x^' + str(io) for io in n]
f = plt.figure()
ax = hs.plot.plot_spectra(s, legend=my_legend, fig=f)
leg = ax.get_legend()
leg_artists = leg.get_lines()
click = plt.matplotlib.backend_bases.MouseEvent(
'button_press_event', f.canvas, 0, 0, 'left')
for artist, li in zip(leg_artists, ax.lines[::-1]):
plt.matplotlib.backends.backend_agg.FigureCanvasBase.pick_event(
f.canvas, click, artist)
assert not li.get_visible()
plt.matplotlib.backends.backend_agg.FigureCanvasBase.pick_event(
f.canvas, click, artist)
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_spectra_auto_update(self):
s = hs.signals.Signal1D(np.arange(100))
s2 = s / 2
ax = hs.plot.plot_spectra([s, s2])
s.data = -s.data
s.events.data_changed.trigger(s)
s2.data = -s2.data * 4 + 50
s2.events.data_changed.trigger(s2)
return ax.get_figure()
@update_close_figure
def test_plot_nav0_close():
test_plot = _TestPlot(ndim=0, sdim=1)
test_plot.signal.plot()
return test_plot.signal
@update_close_figure
def test_plot_nav1_close():
test_plot = _TestPlot(ndim=1, sdim=1)
test_plot.signal.plot()
return test_plot.signal
@update_close_figure
def test_plot_nav2_close():
test_plot = _TestPlot(ndim=2, sdim=1)
test_plot.signal.plot()
return test_plot.signal
def _test_plot_two_cursors(ndim):
test_plot = _TestPlot(ndim=ndim, sdim=1) # sdim=2 not supported
s = test_plot.signal
s.metadata.General.title = 'Nav %i, Sig 1, two cursor' % ndim
s.axes_manager[0].index = 4
s.plot()
s._plot.add_right_pointer()
s._plot.navigator_plot.figure.canvas.draw()
s._plot.signal_plot.figure.canvas.draw()
s._plot.right_pointer.axes_manager[0].index = 2
if ndim == 2:
s.axes_manager[1].index = 2
s._plot.right_pointer.axes_manager[1].index = 3
return s
def _generate_parameter():
parameters = []
for ndim in [1, 2]:
for plot_type in ['nav', 'sig']:
parameters.append([ndim, plot_type])
return parameters
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_log_scale():
s = Signal1D(np.exp(-np.arange(100) / 5.0))
s.plot(norm='log')
return s._plot.signal_plot.figure
@pytest.mark.parametrize(("ndim", "plot_type"),
_generate_parameter())
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_two_cursors(ndim, plot_type):
s = _test_plot_two_cursors(ndim=ndim)
if plot_type == "sig":
return s._plot.signal_plot.figure
else:
return s._plot.navigator_plot.figure
@update_close_figure
def test_plot_nav2_sig1_two_cursors_close():
return _test_plot_two_cursors(ndim=2)
def test_plot_with_non_finite_value():
s = hs.signals.Signal1D(np.array([np.nan, 2.0]))
s.plot()
s.axes_manager.events.indices_changed.trigger(s.axes_manager)
s = hs.signals.Signal1D(np.array([np.nan, np.nan]))
s.plot()
s.axes_manager.events.indices_changed.trigger(s.axes_manager)
s = hs.signals.Signal1D(np.array([-np.inf, 2.0]))
s.plot()
s.axes_manager.events.indices_changed.trigger(s.axes_manager)
s = hs.signals.Signal1D(np.array([np.inf, 2.0]))
s.plot()
s.axes_manager.events.indices_changed.trigger(s.axes_manager)
def test_plot_add_line_events():
s = hs.signals.Signal1D(np.arange(100))
s.plot()
assert len(s.axes_manager.events.indices_changed.connected) == 2
figure = s._plot.signal_plot
def line_function(axes_manager=None):
return 100 - np.arange(100)
line = Signal1DLine()
line.data_function = line_function
line.set_line_properties(color='blue', type='line', scaley=False)
figure.add_line(line)
line.plot()
assert len(line.events.closed.connected) == 1
assert len(s.axes_manager.events.indices_changed.connected) == 3
line.close()
assert len(line.events.closed.connected) == 0
assert len(s.axes_manager.events.indices_changed.connected) == 2
figure.close()
assert len(s.axes_manager.events.indices_changed.connected) == 0
| gpl-3.0 |
TheOpenCloudEngine/process-codi | src/main/java/org/uengine/codi/mw3/calendar/ScheduleCalendarEvent.java | 1051 | package org.uengine.codi.mw3.calendar;
import java.util.Date;
public class ScheduleCalendarEvent {
String title;
String id;
boolean allDay;
String callType;
Date start;
Date end;
boolean complete;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isAllDay() {
return allDay;
}
public void setAllDay(boolean allDay) {
this.allDay = allDay;
}
public String getCallType() {
return callType;
}
public void setCallType(String callType) {
this.callType = callType;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
}
| gpl-3.0 |
EventaxhlTeam/Eventaxhl | src/pocketmine/event/entity/EntityArmorChangeEvent.php | 1689 | <?php
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\event\entity;
use pocketmine\entity\Entity;
use pocketmine\event\Cancellable;
use pocketmine\item\Item;
class EntityArmorChangeEvent extends EntityEvent implements Cancellable
{
public static $handlerList = null;
private $oldItem;
private $newItem;
private $slot;
public function __construct(Entity $entity, Item $oldItem, Item $newItem, $slot)
{
$this->entity = $entity;
$this->oldItem = $oldItem;
$this->newItem = $newItem;
$this->slot = (int)$slot;
}
public function getSlot()
{
return $this->slot;
}
public function getNewItem()
{
return $this->newItem;
}
public function setNewItem(Item $item)
{
$this->newItem = $item;
}
public function getOldItem()
{
return $this->oldItem;
}
/**
* @return string
*/
public function getName()
{
return "EntityArmorChangeEvent";
}
} | gpl-3.0 |
leMaik/chunky | chunky/src/java/se/llbit/chunky/entity/ArmorStand.java | 25762 | /*
* Copyright (c) 2017 Jesper Öqvist <jesper@llbit.se>
*
* This file is part of Chunky.
*
* Chunky 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.
*
* Chunky 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 Chunky. If not, see <http://www.gnu.org/licenses/>.
*/
package se.llbit.chunky.entity;
import se.llbit.chunky.PersistentSettings;
import se.llbit.chunky.resources.Texture;
import se.llbit.chunky.world.Material;
import se.llbit.chunky.world.material.TextureMaterial;
import se.llbit.json.JsonObject;
import se.llbit.json.JsonValue;
import se.llbit.math.Quad;
import se.llbit.math.QuickMath;
import se.llbit.math.Transform;
import se.llbit.math.Vector3;
import se.llbit.math.Vector4;
import se.llbit.math.primitive.Primitive;
import se.llbit.nbt.CompoundTag;
import se.llbit.nbt.Tag;
import se.llbit.util.JsonUtil;
import java.util.Collection;
import java.util.LinkedList;
public class ArmorStand extends Entity implements Poseable, Geared {
private static final String[] partNames =
{ "all", "head", "chest", "leftArm", "rightArm", "leftLeg", "rightLeg" };
private static final String[] gearSlots =
{ "leftHand", "rightHand", "head", "chest", "legs", "feet" };
private static final Quad[] base = {
// cube1
new Quad(
new Vector3(2 / 16.0, 1 / 16.0, 14 / 16.0),
new Vector3(14 / 16.0, 1 / 16.0, 14 / 16.0),
new Vector3(2 / 16.0, 1 / 16.0, 2 / 16.0),
new Vector4(12 / 64.0, 24 / 64.0, 20 / 64.0, 32 / 64.0)),
new Quad(
new Vector3(2 / 16.0, 0, 2 / 16.0),
new Vector3(14 / 16.0, 0, 2 / 16.0),
new Vector3(2 / 16.0, 0, 14 / 16.0),
new Vector4(36 / 64.0, 24 / 64.0, 32 / 64.0, 20 / 64.0)),
new Quad(
new Vector3(14 / 16.0, 0, 14 / 16.0),
new Vector3(14 / 16.0, 0, 2 / 16.0),
new Vector3(14 / 16.0, 1 / 16.0, 14 / 16.0),
new Vector4(24 / 64.0, 36 / 64.0, 19 / 64.0, 20 / 64.0)),
new Quad(
new Vector3(2 / 16.0, 0, 2 / 16.0),
new Vector3(2 / 16.0, 0, 14 / 16.0),
new Vector3(2 / 16.0, 1 / 16.0, 2 / 16.0),
new Vector4(0, 12 / 64.0, 19 / 64.0, 20 / 64.0)),
new Quad(
new Vector3(14 / 16.0, 0, 2 / 16.0),
new Vector3(2 / 16.0, 0, 2 / 16.0),
new Vector3(14 / 16.0, 1 / 16.0, 2 / 16.0),
new Vector4(36 / 64.0, 48 / 64.0, 19 / 64.0, 20 / 64.0)),
new Quad(
new Vector3(2 / 16.0, 0, 14 / 16.0),
new Vector3(14 / 16.0, 0, 14 / 16.0),
new Vector3(2 / 16.0, 1 / 16.0, 14 / 16.0),
new Vector4(12 / 64.0, 24 / 64.0, 19 / 64.0, 20 / 64.0)),
};
private static final Quad[] torso = {
// torsoTop
new Quad(
new Vector3(-5 / 16.0, 6 / 16.0, 1.5 / 16.0),
new Vector3(5 / 16.0, 6 / 16.0, 1.5 / 16.0),
new Vector3(-5 / 16.0, 6 / 16.0, -1.5 / 16.0),
new Vector4(0.75 / 16.0, 3.75 / 16.0, 8.75 / 16.0, 9.5 / 16.0)),
new Quad(
new Vector3(-5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(-5 / 16.0, 3 / 16.0, 1.5 / 16.0),
new Vector4(3.75 / 16.0, 6.75 / 16.0, 9.5 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 3 / 16.0, 1.5 / 16.0),
new Vector3(5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(5 / 16.0, 6 / 16.0, 1.5 / 16.0),
new Vector4(3.75 / 16.0, 4.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(-5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(-5 / 16.0, 3 / 16.0, 1.5 / 16.0),
new Vector3(-5 / 16.0, 6 / 16.0, -1.5 / 16.0),
new Vector4(0, 0.75 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(-5 / 16.0, 3 / 16.0, -1.5 / 16.0),
new Vector3(5 / 16.0, 6 / 16.0, -1.5 / 16.0),
new Vector4(4.5 / 16.0, 7.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(-5 / 16.0, 3 / 16.0, 1.5 / 16.0),
new Vector3(5 / 16.0, 3 / 16.0, 1.5 / 16.0),
new Vector3(-5 / 16.0, 6 / 16.0, 1.5 / 16.0),
new Vector4(0.75 / 16.0, 3.75 / 16.0, 8 / 16.0, 8.75 / 16.0)),
// torsoLeft
new Quad(
new Vector3(-3 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(-3 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(4.5 / 16.0, 5 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(-3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-3 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector4(5 / 16.0, 5.5 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(5 / 16.0, 5.5 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-3 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(-3 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(4 / 16.0, 4.5 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(5.5 / 16.0, 6 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-3 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(-3 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(4.5 / 16.0, 5 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
// torsoRight
new Quad(
new Vector3(1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(3 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(12.5 / 16.0, 13 / 16.0, 11.5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector4(13 / 16.0, 13.5 / 16.0, 11.5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(3 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(3 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(13 / 16.0, 13.5 / 16.0, 9.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(12 / 16.0, 12.5 / 16.0, 9.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(3 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector3(3 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(13.5 / 16.0, 14 / 16.0, 9.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(3 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(12.5 / 16.0, 13 / 16.0, 9.75 / 16.0, 11.5 / 16.0)),
// pelvis
new Quad(
new Vector3(-4 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(4 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector3(-4 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector4(4.5 / 16.0, 7.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(-4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-4 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector4(4.5 / 16.0, 7.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(4 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(4 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector4(0, 0.75 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(-4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-4 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-4 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector4(3.75 / 16.0, 4.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-4 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(4 / 16.0, -4 / 16.0, -1 / 16.0),
new Vector4(4.5 / 16.0, 7.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
new Quad(
new Vector3(-4 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(4 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-4 / 16.0, -4 / 16.0, 1 / 16.0),
new Vector4(4.5 / 16.0, 7.5 / 16.0, 8 / 16.0, 8.75 / 16.0)),
};
private static final Quad[] neck = {
new Quad(
new Vector3(-1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(0.5 / 16.0, 1 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -3 / 16.0, 1 / 16.0),
new Vector4(1 / 16.0, 1.5 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -3 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(0, 0.5 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -3 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(1 / 16.0, 1.5 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -3 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 3 / 16.0, -1 / 16.0),
new Vector4(0.5 / 16.0, 1 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -3 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -3 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 3 / 16.0, 1 / 16.0),
new Vector4(1.5 / 16.0, 2 / 16.0, 13.75 / 16.0, 15.5 / 16.0)),
};
private static final Quad[] leftArm = {
new Quad(
new Vector3(-1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(36 / 64.0, 34 / 64.0, 46 / 64.0, 48 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector4(38 / 64.0, 36 / 64.0, 48 / 64.0, 46 / 64.0)),
new Quad(
new Vector3(1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector4(38 / 64.0, 36 / 64.0, 34 / 64.0, 46 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(34 / 64.0, 32 / 64.0, 34 / 64.0, 46 / 64.0)),
new Quad(
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(36 / 64.0, 34 / 64.0, 34 / 64.0, 46 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector4(40 / 64.0, 38 / 64.0, 34 / 64.0, 46 / 64.0)),
};
private static final Quad[] rightArm = {
new Quad(
new Vector3(-1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(28 / 64.0, 26 / 64.0, 64 / 64.0, 62 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector4(28 / 64.0, 30 / 64.0, 62 / 64.0, 64 / 64.0)),
new Quad(
new Vector3(1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector4(24 / 64.0, 26 / 64.0, 50 / 64.0, 62 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(28 / 64.0, 30 / 64.0, 50 / 64.0, 62 / 64.0)),
new Quad(
new Vector3(1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -6 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 6 / 16.0, -1 / 16.0),
new Vector4(26 / 64.0, 28 / 64.0, 50 / 64.0, 62 / 64.0)),
new Quad(
new Vector3(-1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -6 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 6 / 16.0, 1 / 16.0),
new Vector4(30 / 64.0, 32 / 64.0, 50 / 64.0, 62 / 64.0)),
};
private static final Quad[] leftLeg = {
new Quad(
new Vector3(-1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(10.5 / 16.0, 11 / 16.0, 11.5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector4(11 / 16.0, 11.5 / 16.0, 11.5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector4(10.5 / 16.0, 10 / 16.0, 8.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(11.5 / 16.0, 11 / 16.0, 8.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(12 / 16.0, 11.5 / 16.0, 8.75 / 16.0, 11.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector4(11 / 16.0, 10.5 / 16.0, 8.75 / 16.0, 11.5 / 16.0)),
};
private static final Quad[] rightLeg = {
new Quad(
new Vector3(-1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(2.5 / 16.0, 3 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector4(3 / 16.0, 3.5 / 16.0, 15.5 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector4(3 / 16.0, 3.5 / 16.0, 12.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(2 / 16.0, 2.5 / 16.0, 12.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(-1 / 16.0, -5.5 / 16.0, -1 / 16.0),
new Vector3(1 / 16.0, 5.5 / 16.0, -1 / 16.0),
new Vector4(3.5 / 16.0, 4 / 16.0, 12.75 / 16.0, 15.5 / 16.0)),
new Quad(
new Vector3(-1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(1 / 16.0, -5.5 / 16.0, 1 / 16.0),
new Vector3(-1 / 16.0, 5.5 / 16.0, 1 / 16.0),
new Vector4(2.5 / 16.0, 3 / 16.0, 12.75 / 16.0, 15.5 / 16.0)),
};
private double scale = 1.0;
private double headScale = 1.0;
private final JsonObject gear;
private final JsonObject pose;
private final boolean showArms;
private final boolean invisible;
private final boolean noBasePlate;
public ArmorStand(JsonObject json) {
super(JsonUtil.vec3FromJsonObject(json.get("position")));
this.scale = json.get("scale").asDouble(1.0);
this.headScale = json.get("headScale").asDouble(1.0);
this.showArms = json.get("showArms").asBoolean(false);
this.gear = json.get("gear").object();
this.pose = json.get("pose").object();
this.invisible = json.get("invisible").asBoolean(false);
this.noBasePlate = json.get("noBasePlate").asBoolean(false);
}
public ArmorStand(Vector3 position, Tag tag) {
super(position);
gear = new JsonObject();
Tag handItems = tag.get("HandItems");
Tag armorItems = tag.get("ArmorItems");
int armorItemsCount = armorItems.asList().size(); // in worlds upgraded from older versions the list only contains some gear pieces, see #895
if (armorItemsCount > 0) {
CompoundTag boots = armorItems.get(0).asCompound();
// TODO: handle colored leather.
if (!boots.isEmpty()) {
gear.add("feet", PlayerEntity.parseItem(boots));
}
}
if (armorItemsCount > 1) {
CompoundTag legs = armorItems.get(1).asCompound();
if (!legs.isEmpty()) {
gear.add("legs", PlayerEntity.parseItem(legs));
}
}
if (armorItemsCount > 2) {
CompoundTag chest = armorItems.get(2).asCompound();
if (!chest.isEmpty()) {
gear.add("chest", PlayerEntity.parseItem(chest));
}
}
if (armorItemsCount > 3) {
CompoundTag head = armorItems.get(3).asCompound();
if (!head.isEmpty()) {
gear.add("head", PlayerEntity.parseItem(head));
}
}
showArms = tag.get("ShowArms").boolValue(false);
if (tag.get("Small").boolValue(false)) {
scale = 0.5;
headScale = 1.75;
}
Tag poseTag = tag.get("Pose");
pose = new JsonObject();
float rotation = tag.get("Rotation").get(0).floatValue();
double yaw = QuickMath.degToRad(180 - rotation);
pose.add("all", JsonUtil.vec3ToJson(new Vector3(0, yaw, 0)));
pose.add("head", JsonUtil.listTagToJson(poseTag.get("Head")));
pose.add("chest", JsonUtil.listTagToJson(poseTag.get("Body")));
pose.add("leftArm", JsonUtil.listTagToJson(poseTag.get("LeftArm")));
pose.add("rightArm", JsonUtil.listTagToJson(poseTag.get("RightArm")));
pose.add("leftLeg", JsonUtil.listTagToJson(poseTag.get("LeftLeg")));
pose.add("rightLeg", JsonUtil.listTagToJson(poseTag.get("RightLeg")));
invisible = tag.get("Invisible").boolValue(false);
noBasePlate = tag.get("NoBasePlate").boolValue(false);
}
@Override public Collection<Primitive> primitives(Vector3 offset) {
Collection<Primitive> primitives = new LinkedList<>();
Material material = new TextureMaterial(Texture.armorStand);
Vector3 worldOffset = new Vector3(
position.x + offset.x,
position.y + offset.y,
position.z + offset.z);
double armWidth = 2;
JsonObject pose = new JsonObject();
// TODO: sort out rotations so we use the same sign everywhere (player entity).
Vector3 allPose = JsonUtil.vec3FromJsonArray(this.pose.get("all"));
double yaw = allPose.y;
Vector3 headPose = JsonUtil.vec3FromJsonArray(this.pose.get("head"));
headPose.x = - headPose.x;
headPose.y = - headPose.y;
Vector3 chestPose = JsonUtil.vec3FromJsonArray(this.pose.get("chest"));
Vector3 leftArmPose = JsonUtil.vec3FromJsonArray(this.pose.get("leftArm"));
leftArmPose.x = -leftArmPose.x;
leftArmPose.y = -leftArmPose.y;
Vector3 rightArmPose = JsonUtil.vec3FromJsonArray(this.pose.get("rightArm"));
rightArmPose.x = -rightArmPose.x;
rightArmPose.y = -rightArmPose.y;
Vector3 leftLegPose = JsonUtil.vec3FromJsonArray(this.pose.get("leftLeg"));
leftLegPose.x = -leftLegPose.x;
leftLegPose.y = -leftLegPose.y;
Vector3 rightLegPose = JsonUtil.vec3FromJsonArray(this.pose.get("rightLeg"));
rightLegPose.x = -rightLegPose.x;
rightLegPose.y = -rightLegPose.y;
pose.add("all", JsonUtil.vec3ToJson(allPose));
pose.add("head", JsonUtil.vec3ToJson(headPose));
pose.add("chest", JsonUtil.vec3ToJson(chestPose));
pose.add("leftArm", JsonUtil.vec3ToJson(leftArmPose));
pose.add("rightArm", JsonUtil.vec3ToJson(rightArmPose));
pose.add("leftLeg", JsonUtil.vec3ToJson(leftLegPose));
pose.add("rightLeg", JsonUtil.vec3ToJson(rightLegPose));
Transform worldTransform = Transform.NONE
.scale(scale)
.rotateX(allPose.x)
.rotateY(allPose.y)
.rotateZ(allPose.z)
.translate(worldOffset);
PlayerEntity.addArmor(primitives, gear, pose, armWidth, worldTransform, headScale);
Transform transform = Transform.NONE.translate(-0.5, 0, -0.5).translate(worldOffset);
if (!invisible) {
if (!noBasePlate) {
// Add the base - not rotated or scaled.
for (Quad quad : base) {
quad.addTriangles(primitives, material, transform);
}
}
if (showArms) {
transform = Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(leftArmPose.x)
.rotateY(leftArmPose.y)
.rotateZ(leftArmPose.z)
.translate(-(4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform);
for (Quad quad : leftArm) {
quad.addTriangles(primitives, material, transform);
}
transform = Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(rightArmPose.x)
.rotateY(rightArmPose.y)
.rotateZ(rightArmPose.z)
.translate((4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform);
for (Quad quad : rightArm) {
quad.addTriangles(primitives, material, transform);
}
}
transform = Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(leftLegPose.x)
.rotateY(leftLegPose.y)
.rotateZ(leftLegPose.z)
.translate(-2 / 16., 11.5 / 16., 0)
.chain(worldTransform);
for (Quad quad : leftLeg) {
quad.addTriangles(primitives, material, transform);
}
transform = Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(rightLegPose.x)
.rotateY(rightLegPose.y)
.rotateZ(rightLegPose.z)
.translate(2 / 16., 11.5 / 16., 0)
.chain(worldTransform);
for (Quad quad : rightLeg) {
quad.addTriangles(primitives, material, transform);
}
transform = Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(chestPose.x)
.rotateY(chestPose.y)
.rotateZ(chestPose.z)
.translate(0, (5 + 18) / 16., 0)
.chain(worldTransform);
for (Quad quad : torso) {
quad.addTriangles(primitives, material, transform);
}
transform = Transform.NONE
.translate(0, 2 / 16.0, 0)
.rotateX(headPose.x)
.rotateY(headPose.y)
.rotateZ(headPose.z)
.scale(headScale)
.translate(0, 24 / 16.0, 0)
.chain(worldTransform);
for (Quad quad : neck) {
quad.addTriangles(primitives, material, transform);
}
}
return primitives;
}
@Override public JsonValue toJson() {
JsonObject json = new JsonObject();
json.add("kind", "armor_stand");
json.add("position", position.toJson());
json.add("scale", scale);
json.add("headScale", headScale);
json.add("showArms", showArms);
json.add("gear", gear);
json.add("pose", pose);
json.add("invisible", invisible);
json.add("noBasePlate", noBasePlate);
return json;
}
/**
* Deserialize entity from JSON.
*
* @return deserialized entity, or {@code null} if it was not a valid entity
*/
public static Entity fromJson(JsonObject json) {
return new ArmorStand(json);
}
@Override public String[] partNames() {
return partNames;
}
@Override public double getScale() {
return scale;
}
@Override public void setScale(double scale) {
this.scale = scale;
}
@Override public double getHeadScale() {
return headScale;
}
@Override public void setHeadScale(double headScale) {
this.headScale = headScale;
}
@Override public JsonObject getPose() {
return pose;
}
@Override public String[] gearSlots() {
return gearSlots;
}
@Override public JsonObject getGear() {
return gear;
}
}
| gpl-3.0 |
chrigu6/vocabulary | vocabulary/trainer/forms.py | 1356 | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from trainer.models import Language
class AddWordForm(forms.Form):
language = forms.ModelChoiceField(queryset=Language.objects.all())
word = forms.CharField(required=True)
class CreateSetForm(forms.Form):
name = models.CharField(default="")
class UserCreateForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ("username", "email", "first_name", "last_name", "password1", "password2")
def save(self, commit=True):
user = super(UserCreateForm,self).save(commit=False)
user.email = self.cleaned_data["email"]
user.name = self.cleaned_data["first_name"]
user.prename = self.cleaned_data["last_name"]
if commit:
user.save()
return user
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(widget=forms.PasswordInput())
class UploadFileForm(forms.Form):
language = forms.ModelChoiceField(label='Language', queryset=Language.objects.all(), required=True)
file = forms.FileField(required=True) | gpl-3.0 |
Chuvi-w/ReGameDLL_CS | regamedll/dlls/multiplay_gamerules.cpp | 124110 | #include "precompiled.h"
/*
* Globals initialization
*/
#ifndef HOOK_GAMEDLL
static char mp_com_token[ 1500 ];
cvar_t *sv_clienttrace = NULL;
#endif
CCStrikeGameMgrHelper g_GameMgrHelper;
CHalfLifeMultiplay *g_pMPGameRules = nullptr;
RewardAccount CHalfLifeMultiplay::m_rgRewardAccountRules[] = {
REWARD_CTS_WIN, // RR_CTS_WIN
REWARD_TERRORISTS_WIN, // RR_TERRORISTS_WIN
REWARD_TARGET_BOMB, // RR_TARGET_BOMB
REWARD_VIP_ESCAPED, // RR_VIP_ESCAPED
REWARD_VIP_ASSASSINATED, // RR_VIP_ASSASSINATED
REWARD_TERRORISTS_ESCAPED, // RR_TERRORISTS_ESCAPED
REWARD_CTS_PREVENT_ESCAPE, // RR_CTS_PREVENT_ESCAPE
REWARD_ESCAPING_TERRORISTS_NEUTRALIZED, // RR_ESCAPING_TERRORISTS_NEUTRALIZED
REWARD_BOMB_DEFUSED, // RR_BOMB_DEFUSED
REWARD_BOMB_PLANTED, // RR_BOMB_PLANTED
REWARD_BOMB_EXPLODED, // RR_BOMB_EXPLODED
REWARD_ALL_HOSTAGES_RESCUED, // RR_ALL_HOSTAGES_RESCUED
REWARD_TARGET_BOMB_SAVED, // RR_TARGET_BOMB_SAVED
REWARD_HOSTAGE_NOT_RESCUED, // RR_HOSTAGE_NOT_RESCUED
REWARD_VIP_NOT_ESCAPED, // RR_VIP_NOT_ESCAPED
REWARD_LOSER_BONUS_DEFAULT, // RR_LOSER_BONUS_DEFAULT
REWARD_LOSER_BONUS_MIN, // RR_LOSER_BONUS_MIN
REWARD_LOSER_BONUS_MAX, // RR_LOSER_BONUS_MAX
REWARD_LOSER_BONUS_ADD, // RR_LOSER_BONUS_ADD
REWARD_RESCUED_HOSTAGE, // RR_RESCUED_HOSTAGE
REWARD_TOOK_HOSTAGE_ACC, // RR_TOOK_HOSTAGE_ACC
REWARD_TOOK_HOSTAGE, // RR_TOOK_HOSTAGE
};
bool IsBotSpeaking()
{
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *pPlayer = UTIL_PlayerByIndex(i);
if (!pPlayer || !pPlayer->IsBot())
continue;
CCSBot *pBot = static_cast<CCSBot *>(pPlayer);
if (pBot->IsUsingVoice())
return true;
}
return false;
}
void SV_Continue_f()
{
if (CSGameRules()->IsCareer() && CSGameRules()->m_flRestartRoundTime > 100000.0)
{
CSGameRules()->m_flRestartRoundTime = gpGlobals->time;
// go continue
MESSAGE_BEGIN(MSG_ALL, gmsgCZCareer);
WRITE_STRING("GOGOGO");
MESSAGE_END();
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *pPlayer = UTIL_PlayerByIndex(i);
if (pPlayer && !pPlayer->IsBot())
{
// at the end of the round is showed window with the proposal surrender or continue
// now of this time HUD is completely hidden
// we must to restore HUD after entered continued
pPlayer->m_iHideHUD &= ~HIDEHUD_ALL;
}
}
}
}
void SV_Tutor_Toggle_f()
{
CVAR_SET_FLOAT("tutor_enable", (CVAR_GET_FLOAT("tutor_enable") <= 0.0));
}
void SV_Career_Restart_f()
{
if (CSGameRules()->IsCareer())
{
CSGameRules()->CareerRestart();
}
}
void SV_Career_EndRound_f()
{
if (!CSGameRules()->IsCareer() || !CSGameRules()->IsInCareerRound())
{
return;
}
CBasePlayer *localPlayer = UTIL_GetLocalPlayer();
if (localPlayer)
{
SERVER_COMMAND("kill\n");
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *player = UTIL_PlayerByIndex(i);
if (!player || FNullEnt(player->pev))
continue;
if (player->IsBot() && player->m_iTeam == localPlayer->m_iTeam)
{
SERVER_COMMAND(UTIL_VarArgs("bot_kill \"%s\"\n", STRING(player->pev->netname)));
}
}
}
}
bool CHalfLifeMultiplay::IsInCareerRound()
{
return IsMatchStarted() ? false : true;
}
void SV_CareerAddTask_f()
{
if (CMD_ARGC() != 7)
return;
const char *taskName = CMD_ARGV(1);
const char *weaponName = CMD_ARGV(2);
int reps = Q_atoi(CMD_ARGV(3));
bool mustLive = Q_atoi(CMD_ARGV(4)) != 0;
bool crossRounds = Q_atoi(CMD_ARGV(5)) != 0;
bool isComplete = Q_atoi(CMD_ARGV(6)) != 0;
if (TheCareerTasks)
{
TheCareerTasks->AddTask(taskName, weaponName, reps, mustLive, crossRounds, isComplete);
}
}
void SV_CareerMatchLimit_f()
{
if (CMD_ARGC() != 3)
{
return;
}
if (CSGameRules()->IsCareer())
{
CSGameRules()->SetCareerMatchLimit(Q_atoi(CMD_ARGV(1)), Q_atoi(CMD_ARGV(2)));
}
}
void CHalfLifeMultiplay::SetCareerMatchLimit(int minWins, int winDifference)
{
if (!IsCareer())
{
return;
}
if (!m_iCareerMatchWins)
{
m_iCareerMatchWins = minWins;
m_iRoundWinDifference = winDifference;
}
}
BOOL CHalfLifeMultiplay::IsCareer()
{
return IS_CAREER_MATCH();
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, ServerDeactivate)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(ServerDeactivate)()
{
if (!IsCareer())
{
return;
}
CVAR_SET_FLOAT("pausable", 0);
CVAR_SET_FLOAT("mp_windifference", 1);
UTIL_LogPrintf("Career End\n");
}
bool CCStrikeGameMgrHelper::__MAKE_VHOOK(CanPlayerHearPlayer)(CBasePlayer *pListener, CBasePlayer *pSender)
{
if (
#ifndef REGAMEDLL_FIXES
!pSender->IsPlayer() ||
#endif
pListener->m_iTeam != pSender->m_iTeam)
{
return false;
}
BOOL bListenerAlive = pListener->IsAlive();
BOOL bSenderAlive = pSender->IsAlive();
if (pListener->IsObserver())
{
return true;
}
if (bListenerAlive)
{
if (!bSenderAlive)
return false;
}
else
{
if (bSenderAlive)
return true;
}
return (bListenerAlive == bSenderAlive);
}
void Broadcast(const char *sentence)
{
char text[32];
if (!sentence)
{
return;
}
Q_strcpy(text, "%!MRAD_");
Q_strcat(text, UTIL_VarArgs("%s", sentence));
MESSAGE_BEGIN(MSG_BROADCAST, gmsgSendAudio);
WRITE_BYTE(0);
WRITE_STRING(text);
WRITE_SHORT(100);
MESSAGE_END();
}
char *GetTeam(int team)
{
switch (team)
{
case CT: return "CT";
case TERRORIST: return "TERRORIST";
case SPECTATOR: return "SPECTATOR";
default: return "";
}
}
void CHalfLifeMultiplay::EndRoundMessage(const char *sentence, int event)
{
char *team = NULL;
const char *message = sentence;
bool bTeamTriggered = true;
if (sentence[0] == '#')
message = sentence + 1;
if (sentence[0])
{
UTIL_ClientPrintAll(HUD_PRINTCENTER, sentence);
switch (event)
{
case ROUND_TARGET_BOMB:
case ROUND_VIP_ASSASSINATED:
case ROUND_TERRORISTS_ESCAPED:
case ROUND_TERRORISTS_WIN:
case ROUND_HOSTAGE_NOT_RESCUED:
case ROUND_VIP_NOT_ESCAPED:
team = GetTeam(TERRORIST);
// tell bots the terrorists won the round
if (TheBots)
{
TheBots->OnEvent(EVENT_TERRORISTS_WIN);
}
break;
case ROUND_VIP_ESCAPED:
case ROUND_CTS_PREVENT_ESCAPE:
case ROUND_ESCAPING_TERRORISTS_NEUTRALIZED:
case ROUND_BOMB_DEFUSED:
case ROUND_CTS_WIN:
case ROUND_ALL_HOSTAGES_RESCUED:
case ROUND_TARGET_SAVED:
case ROUND_TERRORISTS_NOT_ESCAPED:
team = GetTeam(CT);
// tell bots the CTs won the round
if (TheBots)
{
TheBots->OnEvent(EVENT_CTS_WIN);
}
break;
default:
bTeamTriggered = false;
// tell bots the round was a draw
if (TheBots)
{
TheBots->OnEvent(EVENT_ROUND_DRAW);
}
break;
}
if (bTeamTriggered)
{
UTIL_LogPrintf("Team \"%s\" triggered \"%s\" (CT \"%i\") (T \"%i\")\n", team, message, m_iNumCTWins, m_iNumTerroristWins);
}
else
{
UTIL_LogPrintf("World triggered \"%s\" (CT \"%i\") (T \"%i\")\n", message, m_iNumCTWins, m_iNumTerroristWins);
}
}
UTIL_LogPrintf("World triggered \"Round_End\"\n");
}
void CHalfLifeMultiplay::ReadMultiplayCvars()
{
m_iRoundTime = int(CVAR_GET_FLOAT("mp_roundtime") * 60);
m_iC4Timer = int(CVAR_GET_FLOAT("mp_c4timer"));
m_iIntroRoundTime = int(CVAR_GET_FLOAT("mp_freezetime"));
m_iLimitTeams = int(CVAR_GET_FLOAT("mp_limitteams"));
#ifndef REGAMEDLL_ADD
if (m_iRoundTime > 540)
{
CVAR_SET_FLOAT("mp_roundtime", 9);
m_iRoundTime = 540;
}
else if (m_iRoundTime < 60)
{
CVAR_SET_FLOAT("mp_roundtime", 1);
m_iRoundTime = 60;
}
if (m_iIntroRoundTime > 60)
{
CVAR_SET_FLOAT("mp_freezetime", 60);
m_iIntroRoundTime = 60;
}
else if (m_iIntroRoundTime < 0)
{
CVAR_SET_FLOAT("mp_freezetime", 0);
m_iIntroRoundTime = 0;
}
if (m_iC4Timer > 90)
{
CVAR_SET_FLOAT("mp_c4timer", 90);
m_iC4Timer = 90;
}
else if (m_iC4Timer < 10)
{
CVAR_SET_FLOAT("mp_c4timer", 10);
m_iC4Timer = 10;
}
if (m_iLimitTeams > 20)
{
CVAR_SET_FLOAT("mp_limitteams", 20);
m_iLimitTeams = 20;
}
else if (m_iLimitTeams < 0)
{
CVAR_SET_FLOAT("mp_limitteams", 0);
m_iLimitTeams = 0;
}
#else
// a limit of 500 minutes because
// if you do more minutes would be a bug in the HUD RoundTime in the form 00:00
if (m_iRoundTime > 30000)
{
CVAR_SET_FLOAT("mp_roundtime", 500);
m_iRoundTime = 30000;
}
else if (m_iRoundTime < 0)
{
CVAR_SET_FLOAT("mp_roundtime", 0);
m_iRoundTime = 0;
}
if (m_iIntroRoundTime < 0)
{
CVAR_SET_FLOAT("mp_freezetime", 0);
m_iIntroRoundTime = 0;
}
if (m_iC4Timer < 0)
{
CVAR_SET_FLOAT("mp_c4timer", 0);
m_iC4Timer = 0;
}
if (m_iLimitTeams < 0)
{
CVAR_SET_FLOAT("mp_limitteams", 0);
m_iLimitTeams = 0;
}
// auto-disable ff
if (freeforall.value)
{
CVAR_SET_FLOAT("mp_friendlyfire", 0);
}
#endif
}
CHalfLifeMultiplay::CHalfLifeMultiplay()
{
m_bFreezePeriod = TRUE;
m_VoiceGameMgr.Init(&g_GameMgrHelper, gpGlobals->maxClients);
RefreshSkillData();
m_flIntermissionEndTime = 0;
m_flIntermissionStartTime = 0;
m_flRestartRoundTime = 0;
m_iAccountCT = 0;
m_iAccountTerrorist = 0;
m_iHostagesRescued = 0;
m_iRoundWinStatus = WINNER_NONE;
m_iNumCTWins = 0;
m_iNumTerroristWins = 0;
m_pVIP = NULL;
m_iNumCT = 0;
m_iNumTerrorist = 0;
m_iNumSpawnableCT = 0;
m_iNumSpawnableTerrorist = 0;
m_bMapHasCameras = FALSE;
m_iLoserBonus = m_rgRewardAccountRules[RR_LOSER_BONUS_DEFAULT];
m_iNumConsecutiveCTLoses = 0;
m_iNumConsecutiveTerroristLoses = 0;
m_iC4Guy = 0;
m_bBombDefused = false;
m_bTargetBombed = false;
m_bLevelInitialized = false;
m_tmNextPeriodicThink = 0;
m_bGameStarted = false;
m_bCompleteReset = false;
m_flRequiredEscapeRatio = 0.5;
m_iNumEscapers = 0;
// by default everyone can buy
m_bCTCantBuy = false;
m_bTCantBuy = false;
m_flBombRadius = 500.0;
m_iTotalGunCount = 0;
m_iTotalGrenadeCount = 0;
m_iTotalArmourCount = 0;
m_iConsecutiveVIP = 0;
m_iUnBalancedRounds = 0;
m_iNumEscapeRounds = 0;
m_bRoundTerminating = false;
g_iHostageNumber = 0;
m_iMaxRounds = int(CVAR_GET_FLOAT("mp_maxrounds"));
if (m_iMaxRounds < 0)
{
m_iMaxRounds = 0;
CVAR_SET_FLOAT("mp_maxrounds", 0);
}
m_iTotalRoundsPlayed = 0;
m_iMaxRoundsWon = int(CVAR_GET_FLOAT("mp_winlimit"));
if (m_iMaxRoundsWon < 0)
{
m_iMaxRoundsWon = 0;
CVAR_SET_FLOAT("mp_winlimit", 0);
}
Q_memset(m_iMapVotes, 0, sizeof(m_iMapVotes));
m_iLastPick = 1;
m_bMapHasEscapeZone = false;
m_bMapHasVIPSafetyZone = FALSE;
m_bMapHasBombZone = false;
m_bMapHasRescueZone = false;
m_iStoredSpectValue = int(allow_spectators.value);
for (int j = 0; j < MAX_VIP_QUEUES; ++j)
{
m_pVIPQueue[j] = NULL;
}
#ifdef REGAMEDLL_FIXES
if (!IS_DEDICATED_SERVER())
#endif
{
// NOTE: cvar cl_himodels refers for the client side
CVAR_SET_FLOAT("cl_himodels", 0);
}
ReadMultiplayCvars();
m_iIntroRoundTime += 2;
#ifdef REGAMEDLL_FIXES
m_fMaxIdlePeriod = (((m_iRoundTime < 60) ? 60 : m_iRoundTime) * 2);
#else
m_fMaxIdlePeriod = (m_iRoundTime * 2);
#endif
float flAutoKickIdle = autokick_timeout.value;
if (flAutoKickIdle > 0.0)
{
m_fMaxIdlePeriod = flAutoKickIdle;
}
m_bInCareerGame = false;
m_iRoundTimeSecs = m_iIntroRoundTime;
if (IS_DEDICATED_SERVER())
{
CVAR_SET_FLOAT("pausable", 0);
}
else if (IsCareer())
{
CVAR_SET_FLOAT("pausable", 1);
CVAR_SET_FLOAT("sv_aim", 0);
CVAR_SET_FLOAT("sv_maxspeed", 322);
CVAR_SET_FLOAT("sv_cheats", 0);
CVAR_SET_FLOAT("mp_windifference", 2);
m_bInCareerGame = true;
UTIL_LogPrintf("Career Start\n");
}
else
{
// 3/31/99
// Added lservercfg file cvar, since listen and dedicated servers should not
// share a single config file. (sjb)
// listen server
CVAR_SET_FLOAT("pausable", 0);
const char *lservercfgfile = CVAR_GET_STRING("lservercfgfile");
if (lservercfgfile && lservercfgfile[0] != '\0')
{
char szCommand[256];
ALERT(at_console, "Executing listen server config file\n");
Q_sprintf(szCommand, "exec %s\n", lservercfgfile);
SERVER_COMMAND(szCommand);
}
}
m_fRoundStartTime = 0;
m_fRoundStartTimeReal = 0;
#ifndef CSTRIKE
InstallBotControl();
#endif
InstallHostageManager();
m_bSkipSpawn = m_bInCareerGame;
static bool installedCommands = false;
if (!installedCommands)
{
installedCommands = true;
if (g_bIsCzeroGame)
{
ADD_SERVER_COMMAND("career_continue", SV_Continue_f);
ADD_SERVER_COMMAND("career_matchlimit", SV_CareerMatchLimit_f);
ADD_SERVER_COMMAND("career_add_task", SV_CareerAddTask_f);
ADD_SERVER_COMMAND("career_endround", SV_Career_EndRound_f);
ADD_SERVER_COMMAND("career_restart", SV_Career_Restart_f);
ADD_SERVER_COMMAND("tutor_toggle", SV_Tutor_Toggle_f);
}
ADD_SERVER_COMMAND("perf_test", loopPerformance);
ADD_SERVER_COMMAND("print_ent", printEntities);
}
m_fCareerRoundMenuTime = 0;
m_fCareerMatchMenuTime = 0;
m_iCareerMatchWins = 0;
m_iRoundWinDifference = int(CVAR_GET_FLOAT("mp_windifference"));
CCareerTaskManager::Create();
if (m_iRoundWinDifference < 1)
{
m_iRoundWinDifference = 1;
CVAR_SET_FLOAT("mp_windifference", 1);
}
sv_clienttrace = CVAR_GET_POINTER("sv_clienttrace");
InstallTutor(CVAR_GET_FLOAT("tutor_enable") != 0.0f);
m_bSkipShowMenu = false;
m_bNeededPlayers = false;
m_flEscapeRatio = 0.0f;
m_flTimeLimit = 0.0f;
m_flGameStartTime = 0.0f;
#ifndef REGAMEDLL_FIXES
g_pMPGameRules = this;
#endif
}
void CHalfLifeMultiplay::__MAKE_VHOOK(RefreshSkillData)()
{
// load all default values
CGameRules::RefreshSkillData();
// override some values for multiplay.
// Glock Round
gSkillData.plrDmg9MM = 12;
// MP5 Round
gSkillData.plrDmgMP5 = 12;
// suitcharger
gSkillData.suitchargerCapacity = 30;
// 357 Round
gSkillData.plrDmg357 = 40;
// M203 grenade
gSkillData.plrDmgM203Grenade = 100;
// Shotgun buckshot
// fewer pellets in deathmatch
gSkillData.plrDmgBuckshot = 20;
// Crossbow
gSkillData.plrDmgCrossbowClient = 20;
// RPG
gSkillData.plrDmgRPG = 120;
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, RemoveGuns)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(RemoveGuns)()
{
CBaseEntity *toremove = NULL;
while ((toremove = UTIL_FindEntityByClassname(toremove, "weaponbox")))
((CWeaponBox *)toremove)->Kill();
toremove = NULL;
while ((toremove = UTIL_FindEntityByClassname(toremove, "weapon_shield")))
{
toremove->SetThink(&CBaseEntity::SUB_Remove);
toremove->pev->nextthink = gpGlobals->time + 0.1;
}
}
void CHalfLifeMultiplay::UpdateTeamScores()
{
MESSAGE_BEGIN(MSG_ALL, gmsgTeamScore);
WRITE_STRING("CT");
WRITE_SHORT(m_iNumCTWins);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgTeamScore);
WRITE_STRING("TERRORIST");
WRITE_SHORT(m_iNumTerroristWins);
MESSAGE_END();
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, CleanUpMap)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(CleanUpMap)()
{
#ifdef REGAMEDLL_FIXES
// Release or reset everything entities in depending of flags ObjectCaps
// (FCAP_MUST_RESET / FCAP_MUST_RELEASE)
UTIL_ResetEntities();
#endif
// Recreate all the map entities from the map data (preserving their indices),
// then remove everything else except the players.
UTIL_RestartOther("cycler_sprite");
UTIL_RestartOther("light");
UTIL_RestartOther("func_breakable");
UTIL_RestartOther("func_door");
UTIL_RestartOther("func_water");
UTIL_RestartOther("func_door_rotating");
UTIL_RestartOther("func_tracktrain");
UTIL_RestartOther("func_vehicle");
UTIL_RestartOther("func_train");
UTIL_RestartOther("armoury_entity");
UTIL_RestartOther("ambient_generic");
UTIL_RestartOther("env_sprite");
#ifdef REGAMEDLL_FIXES
UTIL_RestartOther("multisource");
UTIL_RestartOther("func_button");
UTIL_RestartOther("trigger_auto");
UTIL_RestartOther("trigger_once");
UTIL_RestartOther("multi_manager");
#endif
// Remove grenades and C4
#ifdef REGAMEDLL_FIXES
UTIL_RemoveOther("grenade");
#else
int icount = 0;
CBaseEntity *toremove = UTIL_FindEntityByClassname(NULL, "grenade");
while (toremove && icount < 20)
{
UTIL_Remove(toremove);
toremove = UTIL_FindEntityByClassname(toremove, "grenade");
++icount;
}
#endif
// Remove defuse kit
// Old code only removed 4 kits and stopped.
UTIL_RemoveOther("item_thighpack");
#ifdef REGAMEDLL_FIXES
UTIL_RemoveOther("gib");
UTIL_RemoveOther("DelayedUse");
#endif
RemoveGuns();
PLAYBACK_EVENT((FEV_GLOBAL | FEV_RELIABLE), 0, m_usResetDecals);
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, GiveC4)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(GiveC4)()
{
int iTeamCount;
int iTemp = 0;
int humansPresent = 0;
iTeamCount = m_iNumTerrorist;
++m_iC4Guy;
bool giveToHumans = (cv_bot_defer_to_human.value > 0.0);
if (giveToHumans)
{
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *player = UTIL_PlayerByIndex(i);
if (!player || FNullEnt(player->edict()))
continue;
if (player->pev->deadflag != DEAD_NO || player->m_iTeam != TERRORIST)
continue;
if (!player->IsBot())
++humansPresent;
}
if (humansPresent)
iTeamCount = humansPresent;
else
giveToHumans = false;
}
// if we've looped past the last Terrorist.. then give the C4 to the first one.
if (m_iC4Guy > iTeamCount)
{
m_iC4Guy = 1;
}
// Give the C4 to the specified T player..
CBaseEntity *pPlayer = NULL;
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (!pPlayer->IsPlayer())
continue;
if (pPlayer->pev->flags == FL_DORMANT)
continue;
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (player->pev->deadflag != DEAD_NO || player->m_iTeam != TERRORIST || (giveToHumans && player->IsBot()))
continue;
if (++iTemp == m_iC4Guy)
{
if (player->MakeBomber())
{
#ifdef REGAMEDLL_FIXES
// we already have bomber
return;
#endif
}
}
}
// if there are no players with a bomb
if (!IsThereABomber())
{
m_iC4Guy = 0;
pPlayer = NULL;
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (!pPlayer->IsPlayer())
continue;
if (pPlayer->pev->flags == FL_DORMANT)
continue;
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (player->pev->deadflag != DEAD_NO || player->m_iTeam != TERRORIST)
continue;
player->MakeBomber();
return;
}
}
}
void CHalfLifeMultiplay::QueueCareerRoundEndMenu(float tmDelay, int iWinStatus)
{
if (!TheCareerTasks)
return;
if (m_fCareerMatchMenuTime != 0.0f)
return;
m_fCareerRoundMenuTime = tmDelay + gpGlobals->time;
bool humansAreCTs = (Q_strcmp(humans_join_team.string, "CT") == 0);
if (humansAreCTs)
{
CBaseEntity *hostage = NULL;
int numHostagesInMap = 0;
int numHostagesFollowingHumans = 0;
int numHostagesAlive = 0;
while ((hostage = UTIL_FindEntityByClassname(hostage, "hostage_entity")))
{
++numHostagesInMap;
CHostage *pHostage = static_cast<CHostage *>(hostage);
if (!pHostage->IsAlive())
continue;
CBasePlayer *pLeader = NULL;
if (pHostage->IsFollowingSomeone())
pLeader = static_cast<CBasePlayer *>(pHostage->GetLeader());
if (pLeader == NULL)
{
++numHostagesAlive;
}
else
{
if (!pLeader->IsBot())
{
++numHostagesFollowingHumans;
TheCareerTasks->HandleEvent(EVENT_HOSTAGE_RESCUED, pLeader, 0);
}
}
}
if (!numHostagesAlive)
{
if ((numHostagesInMap * 0.5) <= (numHostagesFollowingHumans + m_iHostagesRescued))
{
TheCareerTasks->HandleEvent(EVENT_ALL_HOSTAGES_RESCUED);
}
}
}
switch (iWinStatus)
{
case WINSTATUS_CTS:
TheCareerTasks->HandleEvent(humansAreCTs ? EVENT_ROUND_WIN : EVENT_ROUND_LOSS);
break;
case WINSTATUS_TERRORISTS:
TheCareerTasks->HandleEvent(humansAreCTs ? EVENT_ROUND_LOSS : EVENT_ROUND_WIN);
break;
default:
TheCareerTasks->HandleEvent(EVENT_ROUND_DRAW);
break;
}
if (m_fCareerMatchMenuTime == 0.0f && m_iCareerMatchWins)
{
bool canTsWin = true;
bool canCTsWin = true;
if (m_iNumCTWins < m_iCareerMatchWins || (m_iNumCTWins - m_iNumTerroristWins < m_iRoundWinDifference))
canCTsWin = false;
if (m_iNumTerroristWins < m_iCareerMatchWins || (m_iNumTerroristWins - m_iNumCTWins < m_iRoundWinDifference))
canTsWin = false;
if (!TheCareerTasks->AreAllTasksComplete())
{
if (humansAreCTs)
return;
canTsWin = false;
}
if (canCTsWin || canTsWin)
{
m_fCareerRoundMenuTime = 0;
m_fCareerMatchMenuTime = gpGlobals->time + 3.0f;
}
}
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, CheckWinConditions)
// Check if the scenario has been won/lost.
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(CheckWinConditions)()
{
if (HasRoundInfinite())
return;
#ifdef REGAMEDLL_FIXES
// If a winner has already been determined.. then get the heck out of here
if (m_iRoundWinStatus != WINNER_NONE)
return;
#else
// If a winner has already been determined and game of started.. then get the heck out of here
if (m_bGameStarted && m_iRoundWinStatus != WINNER_NONE)
return;
#endif
#ifdef REGAMEDLL_ADD
int scenarioFlags = UTIL_ReadFlags(round_infinite.string);
#else
// the icc compiler will cut out all of the code which refers to it
int scenarioFlags = 0;
#endif
// Initialize the player counts..
int NumDeadCT, NumDeadTerrorist, NumAliveTerrorist, NumAliveCT;
InitializePlayerCounts(NumAliveTerrorist, NumAliveCT, NumDeadTerrorist, NumDeadCT);
// other player's check
m_bNeededPlayers = false;
if (!(scenarioFlags & SCENARIO_BLOCK_NEED_PLAYERS) && NeededPlayersCheck())
return;
// Assasination/VIP scenarion check
if (!(scenarioFlags & SCENARIO_BLOCK_VIP_ESCAPE) && VIPRoundEndCheck())
return;
// Prison escape check
if (!(scenarioFlags & SCENARIO_BLOCK_PRISON_ESCAPE) && PrisonRoundEndCheck(NumAliveTerrorist, NumAliveCT, NumDeadTerrorist, NumDeadCT))
return;
// Bomb check
if (!(scenarioFlags & SCENARIO_BLOCK_BOMB) && BombRoundEndCheck())
return;
// Team Extermination check
// CounterTerrorists won by virture of elimination
if (!(scenarioFlags & SCENARIO_BLOCK_TEAM_EXTERMINATION) && TeamExterminationCheck(NumAliveTerrorist, NumAliveCT, NumDeadTerrorist, NumDeadCT))
return;
// Hostage rescue check
if (!(scenarioFlags & SCENARIO_BLOCK_HOSTAGE_RESCUE) && HostageRescueRoundEndCheck())
return;
// scenario not won - still in progress
}
void CHalfLifeMultiplay::InitializePlayerCounts(int &NumAliveTerrorist, int &NumAliveCT, int &NumDeadTerrorist, int &NumDeadCT)
{
NumAliveTerrorist = NumAliveCT = NumDeadCT = NumDeadTerrorist = 0;
m_iNumTerrorist = m_iNumCT = m_iNumSpawnableTerrorist = m_iNumSpawnableCT = 0;
m_iHaveEscaped = 0;
// initialize count dead/alive players
// Count how many dead players there are on each team.
CBaseEntity *pPlayer = NULL;
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
{
break;
}
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (pPlayer->pev->flags == FL_DORMANT)
{
continue;
}
// TODO: check it out, for what here used player->IsBot() ?
// maybe body this conditions is located under the wrapper #ifdef 0
// if (player->IsBot())
// {
// #ifdef 0
// ....
// #endif
// }
switch (player->m_iTeam)
{
case CT:
{
++m_iNumCT;
if (player->m_iMenu != Menu_ChooseAppearance)
{
++m_iNumSpawnableCT;
//player->IsBot();
}
//player->IsBot();
if (player->pev->deadflag != DEAD_NO)
++NumDeadCT;
else
++NumAliveCT;
break;
}
case TERRORIST:
{
++m_iNumTerrorist;
if (player->m_iMenu != Menu_ChooseAppearance)
{
++m_iNumSpawnableTerrorist;
//player->IsBot();
}
//player->IsBot();
if (player->pev->deadflag != DEAD_NO)
++NumDeadTerrorist;
else
++NumAliveTerrorist;
// Check to see if this guy escaped.
if (player->m_bEscaped)
++m_iHaveEscaped;
break;
}
default:
break;
}
}
}
bool EXT_FUNC CHalfLifeMultiplay::NeededPlayersCheck_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
// Start the round immediately when the first person joins
UTIL_LogPrintf("World triggered \"Game_Commencing\"\n");
// Make sure we are not on the FreezePeriod.
m_bFreezePeriod = FALSE;
m_bCompleteReset = true;
EndRoundMessage("#Game_Commencing", event);
TerminateRound(tmDelay, winStatus);
m_bGameStarted = true;
if (TheBots)
{
TheBots->OnEvent(EVENT_GAME_COMMENCE);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::NeededPlayersCheck()
{
// We needed players to start scoring
// Do we have them now?
// start the game, after the players entered in game
if (!m_iNumSpawnableTerrorist || !m_iNumSpawnableCT)
{
UTIL_ClientPrintAll(HUD_PRINTCONSOLE, "#Game_scoring");
m_bNeededPlayers = true;
m_bGameStarted = false;
}
if (!m_bGameStarted && m_iNumSpawnableTerrorist != 0 && m_iNumSpawnableCT != 0)
{
if (IsCareer())
{
CBasePlayer *player = UTIL_PlayerByIndex(gpGlobals->maxClients);
if (!player || !player->IsBot())
{
return true;
}
}
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::NeededPlayersCheck_internal, this, WINSTATUS_DRAW, ROUND_GAME_COMMENCE, IsCareer() ? 0 : 3);
}
return false;
}
bool EXT_FUNC CHalfLifeMultiplay::VIP_Escaped_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
Broadcast("ctwin");
m_iAccountCT += m_rgRewardAccountRules[RR_VIP_ESCAPED];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
MESSAGE_BEGIN(MSG_SPEC, SVC_DIRECTOR);
WRITE_BYTE(9); // command length in bytes
WRITE_BYTE(DRC_CMD_EVENT); // VIP rescued
WRITE_SHORT(ENTINDEX(m_pVIP->edict())); // index number of primary entity
WRITE_SHORT(0); // index number of secondary entity
WRITE_LONG(15 | DRC_FLAG_FINAL); // eventflags (priority and flags)
MESSAGE_END();
EndRoundMessage("#VIP_Escaped", event);
// tell the bots the VIP got out
if (TheBots)
{
TheBots->OnEvent(EVENT_VIP_ESCAPED);
}
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::VIP_Died_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[RR_VIP_ASSASSINATED];
if (!m_bNeededPlayers)
{
++m_iNumTerroristWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#VIP_Assassinated", event);
// tell the bots the VIP was killed
if (TheBots)
{
TheBots->OnEvent(EVENT_VIP_ASSASSINATED);
}
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::VIPRoundEndCheck()
{
// checks to scenario Escaped VIP on map with vip safety zones
if (m_bMapHasVIPSafetyZone && m_pVIP)
{
if (m_pVIP->m_bEscaped)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::VIP_Escaped_internal, this, WINSTATUS_CTS, ROUND_VIP_ESCAPED, GetRoundRestartDelay());
}
// The VIP is dead
else if (m_pVIP->pev->deadflag != DEAD_NO)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::VIP_Died_internal, this, WINSTATUS_TERRORISTS, ROUND_VIP_ASSASSINATED, GetRoundRestartDelay());
}
}
return false;
}
bool EXT_FUNC CHalfLifeMultiplay::Prison_Escaped_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[RR_TERRORISTS_ESCAPED];
if (!m_bNeededPlayers)
{
++m_iNumTerroristWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#Terrorists_Escaped", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::Prison_PreventEscape_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
Broadcast("ctwin");
// CTs are rewarded based on how many terrorists have escaped...
m_iAccountCT += (1 - m_flEscapeRatio) * m_rgRewardAccountRules[RR_CTS_PREVENT_ESCAPE];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#CTs_PreventEscape", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::Prison_Neutralized_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
Broadcast("ctwin");
// CTs are rewarded based on how many terrorists have escaped...
m_iAccountCT += (1 - m_flEscapeRatio) * m_rgRewardAccountRules[RR_ESCAPING_TERRORISTS_NEUTRALIZED];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#Escaping_Terrorists_Neutralized", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool EXT_FUNC CHalfLifeMultiplay::PrisonRoundEndCheck(int NumAliveTerrorist, int NumAliveCT, int NumDeadTerrorist, int NumDeadCT)
{
// checks to scenario Escaped Terrorist's
if (m_bMapHasEscapeZone)
{
m_flEscapeRatio = float_precision(m_iHaveEscaped) / float_precision(m_iNumEscapers);
if (m_flEscapeRatio >= m_flRequiredEscapeRatio)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Prison_Escaped_internal, this, WINSTATUS_TERRORISTS, ROUND_TERRORISTS_ESCAPED, GetRoundRestartDelay());
}
else if (NumAliveTerrorist == 0 && m_flEscapeRatio < m_flRequiredEscapeRatio)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Prison_PreventEscape_internal, this, WINSTATUS_CTS, ROUND_CTS_PREVENT_ESCAPE, GetRoundRestartDelay());
}
else if (NumAliveTerrorist == 0 && NumDeadTerrorist != 0 && m_iNumSpawnableCT > 0)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Prison_Neutralized_internal, this, WINSTATUS_CTS, ROUND_ESCAPING_TERRORISTS_NEUTRALIZED, GetRoundRestartDelay());
}
// else return true;
}
return false;
}
bool CHalfLifeMultiplay::Target_Bombed_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[RR_TARGET_BOMB];
if (!m_bNeededPlayers)
{
++m_iNumTerroristWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#Target_Bombed", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool CHalfLifeMultiplay::Target_Defused_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("ctwin");
m_iAccountCT += m_rgRewardAccountRules[RR_BOMB_DEFUSED];
m_iAccountTerrorist += m_rgRewardAccountRules[RR_BOMB_PLANTED];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#Bomb_Defused", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool CHalfLifeMultiplay::BombRoundEndCheck()
{
// Check to see if the bomb target was hit or the bomb defused.. if so, then let's end the round!
if (m_bTargetBombed && m_bMapHasBombTarget)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Target_Bombed_internal, this, WINSTATUS_TERRORISTS, ROUND_TARGET_BOMB, GetRoundRestartDelay());
}
else if (m_bBombDefused && m_bMapHasBombTarget)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Target_Defused_internal, this, WINSTATUS_CTS, ROUND_BOMB_DEFUSED, GetRoundRestartDelay());
}
return false;
}
bool CHalfLifeMultiplay::Round_Cts_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("ctwin");
m_iAccountCT += m_rgRewardAccountRules[m_bMapHasBombTarget ? RR_BOMB_DEFUSED : RR_CTS_WIN];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#CTs_Win", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool CHalfLifeMultiplay::Round_Ts_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[m_bMapHasBombTarget ? RR_BOMB_EXPLODED : RR_TERRORISTS_WIN];
if (!m_bNeededPlayers)
{
++m_iNumTerroristWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#Terrorists_Win", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool CHalfLifeMultiplay::Round_Draw_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
EndRoundMessage("#Round_Draw", event);
Broadcast("rounddraw");
TerminateRound(tmDelay, winStatus);
return true;
}
bool CHalfLifeMultiplay::TeamExterminationCheck(int NumAliveTerrorist, int NumAliveCT, int NumDeadTerrorist, int NumDeadCT)
{
if ((m_iNumCT > 0 && m_iNumSpawnableCT > 0) && (m_iNumTerrorist > 0 && m_iNumSpawnableTerrorist > 0))
{
if (NumAliveTerrorist == 0 && NumDeadTerrorist != 0 && NumAliveCT > 0)
{
CGrenade *pBomb = NULL;
bool nowin = false;
while ((pBomb = (CGrenade *)UTIL_FindEntityByClassname(pBomb, "grenade")))
{
if (pBomb->m_bIsC4 && !pBomb->m_bJustBlew)
{
nowin = true;
#ifdef REGAMEDLL_FIXES
break;
#endif
}
}
if (!nowin)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Round_Cts_internal, this, WINSTATUS_CTS, ROUND_CTS_WIN, GetRoundRestartDelay());
}
}
// Terrorists WON
else if (NumAliveCT == 0 && NumDeadCT != 0)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Round_Ts_internal, this, WINSTATUS_TERRORISTS, ROUND_TERRORISTS_WIN, GetRoundRestartDelay());
}
}
else if (NumAliveCT == 0 && NumAliveTerrorist == 0)
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Round_Draw_internal, this, WINSTATUS_DRAW, ROUND_END_DRAW, GetRoundRestartDelay());
}
return false;
}
bool CHalfLifeMultiplay::Hostage_Rescue_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("ctwin");
m_iAccountCT += m_rgRewardAccountRules[RR_ALL_HOSTAGES_RESCUED];
if (!m_bNeededPlayers)
{
++m_iNumCTWins;
// Update the clients team score
UpdateTeamScores();
}
EndRoundMessage("#All_Hostages_Rescued", event);
// tell the bots all the hostages have been rescued
if (TheBots)
{
TheBots->OnEvent(EVENT_ALL_HOSTAGES_RESCUED);
}
if (IsCareer())
{
if (TheCareerTasks)
{
TheCareerTasks->HandleEvent(EVENT_ALL_HOSTAGES_RESCUED);
}
}
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
return true;
}
bool CHalfLifeMultiplay::HostageRescueRoundEndCheck()
{
// Check to see if 50% of the hostages have been rescued.
CBaseEntity *hostage = NULL;
int iHostages = 0;
// Assume that all hostages are either rescued or dead..
bool bHostageAlive = false;
while ((hostage = UTIL_FindEntityByClassname(hostage, "hostage_entity")))
{
++iHostages;
// We've found a live hostage. don't end the round
if (hostage->IsAlive())
{
bHostageAlive = true;
}
}
// There are no hostages alive.. check to see if the CTs have rescued atleast 50% of them.
if (!bHostageAlive && iHostages > 0)
{
if (m_iHostagesRescued >= (iHostages * 0.5f))
{
return g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Hostage_Rescue_internal, this, WINSTATUS_CTS, ROUND_ALL_HOSTAGES_RESCUED, GetRoundRestartDelay());
}
}
return false;
}
void CHalfLifeMultiplay::SwapAllPlayers()
{
CBaseEntity *pPlayer = NULL;
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (pPlayer->pev->flags == FL_DORMANT)
continue;
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
player->SwitchTeam();
}
// Swap Team victories
SWAP(m_iNumTerroristWins, m_iNumCTWins);
// Update the clients team score
UpdateTeamScores();
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, BalanceTeams)
void EXT_FUNC CHalfLifeMultiplay::__API_HOOK(BalanceTeams)()
{
int iTeamToSwap = UNASSIGNED;
int iNumToSwap;
// The ratio for teams is different for Assasination maps
if (m_bMapHasVIPSafetyZone)
{
int iDesiredNumCT, iDesiredNumTerrorist;
// uneven number of players
if ((m_iNumCT + m_iNumTerrorist) % 2 != 0)
iDesiredNumCT = int((m_iNumCT + m_iNumTerrorist) * 0.55f) + 1;
else
iDesiredNumCT = int((m_iNumCT + m_iNumTerrorist) / 2);
iDesiredNumTerrorist = (m_iNumCT + m_iNumTerrorist) - iDesiredNumCT;
if (m_iNumCT < iDesiredNumCT)
{
iTeamToSwap = TERRORIST;
iNumToSwap = iDesiredNumCT - m_iNumCT;
}
else if (m_iNumTerrorist < iDesiredNumTerrorist)
{
iTeamToSwap = CT;
iNumToSwap = iDesiredNumTerrorist - m_iNumTerrorist;
}
else
{
return;
}
}
else
{
if (m_iNumCT > m_iNumTerrorist)
{
iTeamToSwap = CT;
iNumToSwap = (m_iNumCT - m_iNumTerrorist) / 2;
}
else if (m_iNumTerrorist > m_iNumCT)
{
iTeamToSwap = TERRORIST;
iNumToSwap = (m_iNumTerrorist - m_iNumCT) / 2;
}
else
{
// Teams are even.. Get out of here.
return;
}
}
// Don't swap more than 4 players at a time.. This is a naive method of avoiding infinite loops.
if (iNumToSwap > 4)
iNumToSwap = 4;
// last person to join the server
int iHighestUserID = 0;
CBasePlayer *toSwap = NULL;
for (int i = 1; i <= iNumToSwap; ++i)
{
iHighestUserID = 0;
toSwap = NULL;
CBaseEntity *pPlayer = NULL;
// search for player with highest UserID = most recently joined to switch over
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (pPlayer->pev->flags == FL_DORMANT)
continue;
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (player->m_iTeam == iTeamToSwap && GETPLAYERUSERID(player->edict()) > iHighestUserID && m_pVIP != player)
{
iHighestUserID = GETPLAYERUSERID(player->edict());
toSwap = player;
}
}
if (toSwap) {
toSwap->SwitchTeam();
}
}
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, CheckMapConditions)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(CheckMapConditions)()
{
// Check to see if this map has a bomb target in it
if (UTIL_FindEntityByClassname(NULL, "func_bomb_target"))
{
m_bMapHasBombTarget = true;
m_bMapHasBombZone = true;
}
else if (UTIL_FindEntityByClassname(NULL, "info_bomb_target"))
{
m_bMapHasBombTarget = true;
m_bMapHasBombZone = false;
}
else
{
m_bMapHasBombTarget = false;
m_bMapHasBombZone = false;
}
// Check to see if this map has hostage rescue zones
m_bMapHasRescueZone = (UTIL_FindEntityByClassname(NULL, "func_hostage_rescue") != NULL);
// See if the map has func_buyzone entities
// Used by CBasePlayer::HandleSignals() to support maps without these entities
m_bMapHasBuyZone = (UTIL_FindEntityByClassname(NULL, "func_buyzone") != NULL);
// GOOSEMAN : See if this map has func_escapezone entities
m_bMapHasEscapeZone = (UTIL_FindEntityByClassname(NULL, "func_escapezone") != NULL);
// Check to see if this map has VIP safety zones
m_bMapHasVIPSafetyZone = (UTIL_FindEntityByClassname(NULL, "func_vip_safetyzone") != NULL);
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, RestartRound)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(RestartRound)()
{
// tell bots that the round is restarting
if (TheBots)
{
TheBots->RestartRound();
}
if (g_pHostages)
{
g_pHostages->RestartRound();
}
#ifdef REGAMEDLL_FIXES
if (!m_bCompleteReset)
#endif
{
++m_iTotalRoundsPlayed;
}
ClearBodyQue();
// Hardlock the player accelaration to 5.0
CVAR_SET_FLOAT("sv_accelerate", 5.0);
CVAR_SET_FLOAT("sv_friction", 4.0);
CVAR_SET_FLOAT("sv_stopspeed", 75);
// Tabulate the number of players on each team.
m_iNumCT = CountTeamPlayers(CT);
m_iNumTerrorist = CountTeamPlayers(TERRORIST);
// reset the dropped bomb on everyone's radar
if (m_bMapHasBombTarget)
{
MESSAGE_BEGIN(MSG_ALL, gmsgBombPickup);
MESSAGE_END();
#ifdef REGAMEDLL_FIXES
if (m_iRoundTime > 0)
#endif
{
MESSAGE_BEGIN(MSG_ALL, gmsgShowTimer);
MESSAGE_END();
}
}
m_bBombDropped = FALSE;
// reset all players health for HLTV
MESSAGE_BEGIN(MSG_SPEC, gmsgHLTV);
WRITE_BYTE(0); // 0 = all players
WRITE_BYTE(100 | DRC_FLAG_FACEPLAYER); // 100 health + msg flag
MESSAGE_END();
// reset all players FOV for HLTV
MESSAGE_BEGIN(MSG_SPEC, gmsgHLTV);
WRITE_BYTE(0); // all players
WRITE_BYTE(0); // to default FOV value
MESSAGE_END();
auto shouldBalancedOnNextRound = []() -> bool
{
#ifdef REGAMEDLL_ADD
return autoteambalance.value == 1;
#else
return autoteambalance.value > 0;
#endif
};
if (shouldBalancedOnNextRound() && m_iUnBalancedRounds >= 1)
{
BalanceTeams();
}
if ((m_iNumCT - m_iNumTerrorist) >= 2 || (m_iNumTerrorist - m_iNumCT) >= 2)
{
++m_iUnBalancedRounds;
}
else
m_iUnBalancedRounds = 0;
// Warn the players of an impending auto-balance next round...
if (shouldBalancedOnNextRound() && m_iUnBalancedRounds == 1)
{
UTIL_ClientPrintAll(HUD_PRINTCENTER, "#Auto_Team_Balance_Next_Round");
}
#ifdef REGAMEDLL_ADD
else if (autoteambalance.value >= 2 && m_iUnBalancedRounds >= 1)
{
BalanceTeams();
}
#endif
if (m_bCompleteReset)
{
// bounds check
if (timelimit.value < 0)
{
CVAR_SET_FLOAT("mp_timelimit", 0);
}
m_flGameStartTime = gpGlobals->time;
// Reset timelimit
if (timelimit.value)
m_flTimeLimit = gpGlobals->time + (timelimit.value * 60);
// Reset total # of rounds played
m_iTotalRoundsPlayed = 0;
m_iMaxRounds = int(CVAR_GET_FLOAT("mp_maxrounds"));
if (m_iMaxRounds < 0)
{
m_iMaxRounds = 0;
CVAR_SET_FLOAT("mp_maxrounds", 0);
}
m_iMaxRoundsWon = int(CVAR_GET_FLOAT("mp_winlimit"));
if (m_iMaxRoundsWon < 0)
{
m_iMaxRoundsWon = 0;
CVAR_SET_FLOAT("mp_winlimit", 0);
}
// Reset score info
m_iNumTerroristWins = 0;
m_iNumCTWins = 0;
m_iNumConsecutiveTerroristLoses = 0;
m_iNumConsecutiveCTLoses = 0;
// Reset team scores
UpdateTeamScores();
// Reset the player stats
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *plr = UTIL_PlayerByIndex(i);
if (plr && !FNullEnt(plr->pev))
plr->Reset();
}
if (TheBots)
{
TheBots->OnEvent(EVENT_NEW_MATCH);
}
}
m_bFreezePeriod = TRUE;
m_bRoundTerminating = false;
ReadMultiplayCvars();
float flAutoKickIdle = autokick_timeout.value;
// set the idlekick max time (in seconds)
if (flAutoKickIdle > 0)
m_fMaxIdlePeriod = flAutoKickIdle;
else
#ifdef REGAMEDLL_FIXES
m_fMaxIdlePeriod = (((m_iRoundTime < 60) ? 60 : m_iRoundTime) * 2);
#else
m_fMaxIdlePeriod = (m_iRoundTime * 2);
#endif
// This makes the round timer function as the intro timer on the client side
m_iRoundTimeSecs = m_iIntroRoundTime;
// Check to see if there's a mapping info paramater entity
if (g_pMapInfo)
g_pMapInfo->CheckMapInfo();
CheckMapConditions();
if (m_bMapHasEscapeZone)
{
// Will increase this later when we count how many Ts are starting
m_iNumEscapers = m_iHaveEscaped = 0;
if (m_iNumEscapeRounds >= 3)
{
SwapAllPlayers();
m_iNumEscapeRounds = 0;
}
// Increment the number of rounds played... After 8 rounds, the players will do a whole sale switch..
++m_iNumEscapeRounds;
}
if (m_bMapHasVIPSafetyZone)
{
PickNextVIP();
++m_iConsecutiveVIP;
}
int acct_tmp = 0;
CBaseEntity *hostage = NULL;
while ((hostage = UTIL_FindEntityByClassname(hostage, "hostage_entity")))
{
if (acct_tmp >= 2000)
break;
CHostage *temp = static_cast<CHostage *>(hostage);
if (hostage->pev->solid != SOLID_NOT)
{
acct_tmp += m_rgRewardAccountRules[RR_TOOK_HOSTAGE];
if (hostage->pev->deadflag == DEAD_DEAD)
{
hostage->pev->deadflag = DEAD_RESPAWNABLE;
}
}
temp->RePosition();
}
// Scale up the loser bonus when teams fall into losing streaks
if (m_iRoundWinStatus == WINSTATUS_TERRORISTS) // terrorists won
{
// check to see if they just broke a losing streak
if (m_iNumConsecutiveTerroristLoses > 1)
{
// this is the default losing bonus
m_iLoserBonus = m_rgRewardAccountRules[RR_LOSER_BONUS_MIN];
}
m_iNumConsecutiveTerroristLoses = 0; // starting fresh
m_iNumConsecutiveCTLoses++; // increment the number of wins the CTs have had
}
else if (m_iRoundWinStatus == WINSTATUS_CTS)
{
// check to see if they just broke a losing streak
if (m_iNumConsecutiveCTLoses > 1)
{
// this is the default losing bonus
m_iLoserBonus = m_rgRewardAccountRules[RR_LOSER_BONUS_MIN];
}
m_iNumConsecutiveCTLoses = 0; // starting fresh
m_iNumConsecutiveTerroristLoses++; // increment the number of wins the Terrorists have had
}
// check if the losing team is in a losing streak & that the loser bonus hasen't maxed out.
if (m_iNumConsecutiveTerroristLoses > 1 && m_iLoserBonus < m_rgRewardAccountRules[RR_LOSER_BONUS_MAX])
{
// help out the team in the losing streak
m_iLoserBonus += m_rgRewardAccountRules[RR_LOSER_BONUS_ADD];
}
else if (m_iNumConsecutiveCTLoses > 1 && m_iLoserBonus < m_rgRewardAccountRules[RR_LOSER_BONUS_MAX])
{
// help out the team in the losing streak
m_iLoserBonus += m_rgRewardAccountRules[RR_LOSER_BONUS_ADD];
}
// assign the wining and losing bonuses
if (m_iRoundWinStatus == WINSTATUS_TERRORISTS) // terrorists won
{
m_iAccountTerrorist += acct_tmp;
m_iAccountCT += m_iLoserBonus;
}
else if (m_iRoundWinStatus == WINSTATUS_CTS) // CT Won
{
m_iAccountCT += acct_tmp;
if (!m_bMapHasEscapeZone)
{
// only give them the bonus if this isn't an escape map
m_iAccountTerrorist += m_iLoserBonus;
}
}
// Update CT account based on number of hostages rescued
m_iAccountCT += m_iHostagesRescued * m_rgRewardAccountRules[RR_RESCUED_HOSTAGE];
// Update individual players accounts and respawn players
// the round time stamp must be set before players are spawned
m_fRoundStartTime = m_fRoundStartTimeReal = gpGlobals->time;
// Adrian - No cash for anyone at first rounds! ( well, only the default. )
if (m_bCompleteReset)
{
// No extra cash!.
m_iAccountTerrorist = m_iAccountCT = 0;
// We are starting fresh. So it's like no one has ever won or lost.
m_iNumTerroristWins = 0;
m_iNumCTWins = 0;
m_iNumConsecutiveTerroristLoses = 0;
m_iNumConsecutiveCTLoses = 0;
m_iLoserBonus = m_rgRewardAccountRules[RR_LOSER_BONUS_DEFAULT];
}
#ifdef REGAMEDLL_FIXES
// Respawn entities (glass, doors, etc..)
CleanUpMap();
#endif
// tell bots that the round is restarting
CBaseEntity *pPlayer = NULL;
while ((pPlayer = UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (pPlayer->pev->flags == FL_DORMANT)
continue;
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
player->m_iNumSpawns = 0;
player->m_bTeamChanged = false;
#ifndef REGAMEDLL_FIXES
// NOTE: unreachable code
if (!player->IsPlayer())
{
player->SyncRoundTimer();
}
#endif
if (player->m_iTeam == CT)
{
if (!player->m_bReceivesNoMoneyNextRound)
{
player->AddAccount(m_iAccountCT, RT_ROUND_BONUS);
}
}
else if (player->m_iTeam == TERRORIST)
{
// Add another potential escaper to the mix!
++m_iNumEscapers;
if (!player->m_bReceivesNoMoneyNextRound)
{
player->AddAccount(m_iAccountTerrorist, RT_ROUND_BONUS);
}
// If it's a prison scenario then remove the Ts guns
if (m_bMapHasEscapeZone)
{
// this will cause them to be reset with default weapons, armor, and items
player->m_bNotKilled = false;
}
}
if (player->m_iTeam != UNASSIGNED && player->m_iTeam != SPECTATOR)
{
#ifdef REGAMEDLL_FIXES
// remove the c4 if the player is carrying it
if (player->m_bHasC4) {
player->RemoveBomb();
}
#else
// drop the c4 if the player is carrying it
if (player->m_bHasC4) {
player->DropPlayerItem("weapon_c4");
}
#endif
player->RoundRespawn();
}
// Gooseman : The following code fixes the HUD icon bug
// by removing the C4 and DEFUSER icons from the HUD regardless
// for EVERY player (regardless of what team they're on)
}
// Moved above the loop spawning the players
#ifndef REGAMEDLL_FIXES
CleanUpMap();
#endif
// Give C4 to the terrorists
if (m_bMapHasBombTarget)
{
GiveC4();
}
if (TheBots)
{
TheBots->OnEvent(EVENT_BUY_TIME_START);
}
// Reset game variables
m_flIntermissionEndTime = 0;
m_flIntermissionStartTime = 0;
m_flRestartRoundTime = 0.0;
m_iAccountTerrorist = m_iAccountCT = 0;
m_iHostagesRescued = 0;
m_iHostagesTouched = 0;
m_iRoundWinStatus = WINNER_NONE;
m_bTargetBombed = m_bBombDefused = false;
m_bLevelInitialized = false;
m_bCompleteReset = false;
}
BOOL CHalfLifeMultiplay::IsThereABomber()
{
CBasePlayer *pPlayer = NULL;
while ((pPlayer = (CBasePlayer *)UTIL_FindEntityByClassname(pPlayer, "player")))
{
if (FNullEnt(pPlayer->edict()))
break;
if (pPlayer->m_iTeam != CT && pPlayer->IsBombGuy())
{
// There you are.
return TRUE;
}
}
// Didn't find a bomber.
return FALSE;
}
BOOL CHalfLifeMultiplay::IsThereABomb()
{
CGrenade *pC4 = NULL;
CBaseEntity *pWeaponC4 = NULL;
bool bFoundBomb = false;
while ((pWeaponC4 = UTIL_FindEntityByClassname(pWeaponC4, "grenade")))
{
if (!pWeaponC4)
continue;
pC4 = static_cast<CGrenade *>(pWeaponC4);
if (pC4->m_bIsC4)
{
bFoundBomb = true;
break;
}
}
if (bFoundBomb || (UTIL_FindEntityByClassname(NULL, "weapon_c4")))
return TRUE;
return FALSE;
}
BOOL CHalfLifeMultiplay::TeamFull(int team_id)
{
switch (team_id)
{
case TERRORIST:
return (m_iNumTerrorist >= m_iSpawnPointCount_Terrorist);
case CT:
return (m_iNumCT >= m_iSpawnPointCount_CT);
}
return FALSE;
}
// checks to see if the desired team is stacked, returns true if it is
BOOL CHalfLifeMultiplay::TeamStacked(int newTeam_id, int curTeam_id)
{
// players are allowed to change to their own team
if (newTeam_id == curTeam_id)
return FALSE;
if (!m_iLimitTeams)
return FALSE;
switch (newTeam_id)
{
case TERRORIST:
if (curTeam_id != UNASSIGNED && curTeam_id != SPECTATOR)
return ((m_iNumTerrorist + 1) > (m_iNumCT + m_iLimitTeams - 1));
else
return ((m_iNumTerrorist + 1) > (m_iNumCT + m_iLimitTeams));
case CT:
if (curTeam_id != UNASSIGNED && curTeam_id != SPECTATOR)
return ((m_iNumCT + 1) > (m_iNumTerrorist + m_iLimitTeams - 1));
else
return ((m_iNumCT + 1) > (m_iNumTerrorist + m_iLimitTeams));
}
return FALSE;
}
void CHalfLifeMultiplay::StackVIPQueue()
{
for (int i = MAX_VIP_QUEUES - 2; i > 0; --i)
{
if (m_pVIPQueue[i - 1])
{
if (!m_pVIPQueue[i])
{
m_pVIPQueue[i] = m_pVIPQueue[i + 1];
m_pVIPQueue[i + 1] = NULL;
}
}
else
{
m_pVIPQueue[i - 1] = m_pVIPQueue[i];
m_pVIPQueue[i] = m_pVIPQueue[i + 1];
m_pVIPQueue[i + 1] = NULL;
}
}
}
bool CHalfLifeMultiplay::IsVIPQueueEmpty()
{
for (int i = 0; i < MAX_VIP_QUEUES; ++i)
{
CBasePlayer *toCheck = m_pVIPQueue[i];
if (toCheck && toCheck->m_iTeam != CT)
{
m_pVIPQueue[i] = NULL;
}
}
StackVIPQueue();
return (!m_pVIPQueue[0] && !m_pVIPQueue[1] && !m_pVIPQueue[2] && !m_pVIPQueue[3] && !m_pVIPQueue[4]);
}
bool CHalfLifeMultiplay::AddToVIPQueue(CBasePlayer *toAdd)
{
for (int i = 0; i < MAX_VIP_QUEUES; ++i)
{
CBasePlayer *toCheck = m_pVIPQueue[i];
if (toCheck && toCheck->m_iTeam != CT)
{
m_pVIPQueue[i] = NULL;
}
}
StackVIPQueue();
if (toAdd->m_iTeam == CT)
{
int j;
for (j = 0; j < MAX_VIP_QUEUES; ++j)
{
if (m_pVIPQueue[j] == toAdd)
{
ClientPrint(toAdd->pev, HUD_PRINTCENTER, "#Game_in_position", UTIL_dtos1(j + 1));
return FALSE;
}
}
for (j = 0; j < MAX_VIP_QUEUES; ++j)
{
if (!m_pVIPQueue[j])
{
m_pVIPQueue[j] = toAdd;
StackVIPQueue();
ClientPrint(toAdd->pev, HUD_PRINTCENTER, "#Game_added_position", UTIL_dtos1(j + 1));
return TRUE;
}
}
ClientPrint(toAdd->pev, HUD_PRINTCENTER, "#All_VIP_Slots_Full");
}
return FALSE;
}
void CHalfLifeMultiplay::ResetCurrentVIP()
{
char *infobuffer = GET_INFO_BUFFER(m_pVIP->edict());
int numSkins = g_bIsCzeroGame ? CZ_NUM_SKIN : CS_NUM_SKIN;
switch (RANDOM_LONG(0, numSkins))
{
case 1:
m_pVIP->m_iModelName = MODEL_GSG9;
m_pVIP->SetClientUserInfoModel(infobuffer, "gsg9");
break;
case 2:
m_pVIP->m_iModelName = MODEL_SAS;
m_pVIP->SetClientUserInfoModel(infobuffer, "sas");
break;
case 3:
m_pVIP->m_iModelName = MODEL_GIGN;
m_pVIP->SetClientUserInfoModel(infobuffer, "gign");
break;
case 4:
if (g_bIsCzeroGame)
{
m_pVIP->m_iModelName = MODEL_SPETSNAZ;
m_pVIP->SetClientUserInfoModel(infobuffer, "spetsnaz");
break;
}
default:
m_pVIP->m_iModelName = MODEL_URBAN;
m_pVIP->SetClientUserInfoModel(infobuffer, "urban");
break;
}
m_pVIP->m_bIsVIP = false;
m_pVIP->m_bNotKilled = false;
}
void CHalfLifeMultiplay::PickNextVIP()
{
if (!IsVIPQueueEmpty())
{
// Remove the current VIP from his VIP status and make him a regular CT.
if (m_pVIP)
{
ResetCurrentVIP();
}
for (int i = 0; i < MAX_VIP_QUEUES; ++i)
{
if (m_pVIPQueue[i])
{
m_pVIP = m_pVIPQueue[i];
m_pVIP->MakeVIP();
m_pVIPQueue[i] = NULL; // remove this player from the VIP queue
StackVIPQueue(); // and re-organize the queue
m_iConsecutiveVIP = 0;
return;
}
}
}
// If it's been the same VIP for 3 rounds already.. then randomly pick a new one
else if (m_iConsecutiveVIP >= 3)
{
if (++m_iLastPick > m_iNumCT)
m_iLastPick = 1;
int iCount = 1;
CBaseEntity *pPlayer = NULL;
CBasePlayer *player = NULL;
CBasePlayer *pLastPlayer = NULL;
pPlayer = UTIL_FindEntityByClassname(pPlayer, "player");
while (pPlayer && !FNullEnt(pPlayer->edict()))
{
if (!(pPlayer->pev->flags & FL_DORMANT))
{
player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (player->m_iTeam == CT && iCount == m_iLastPick)
{
if (player == m_pVIP && pLastPlayer)
player = pLastPlayer;
// Remove the current VIP from his VIP status and make him a regular CT.
if (m_pVIP)
{
ResetCurrentVIP();
}
player->MakeVIP();
m_iConsecutiveVIP = 0;
return;
}
else if (player->m_iTeam == CT)
++iCount;
if (player->m_iTeam != SPECTATOR)
pLastPlayer = player;
}
pPlayer = UTIL_FindEntityByClassname(pPlayer, "player");
}
}
// There is no VIP and there is no one waiting to be the VIP.. therefore just pick the first CT player we can find.
else if (m_pVIP == NULL)
{
CBaseEntity *pPlayer = NULL;
CBasePlayer *player = NULL;
pPlayer = UTIL_FindEntityByClassname(pPlayer, "player");
while (pPlayer && !FNullEnt(pPlayer->edict()))
{
if (pPlayer->pev->flags != FL_DORMANT)
{
player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
if (player->m_iTeam == CT)
{
player->MakeVIP();
m_iConsecutiveVIP = 0;
return;
}
}
pPlayer = UTIL_FindEntityByClassname(pPlayer, "player");
}
}
}
void CHalfLifeMultiplay::__MAKE_VHOOK(Think)()
{
MonitorTutorStatus();
m_VoiceGameMgr.Update(gpGlobals->frametime);
if (sv_clienttrace->value != 1.0f)
{
CVAR_SET_FLOAT("sv_clienttrace", 1);
}
if (!m_fRoundStartTime)
{
// initialize the timer time stamps, this happens once only
m_fRoundStartTime = m_fRoundStartTimeReal = gpGlobals->time;
}
if (m_flForceCameraValue != forcecamera.value
|| m_flForceChaseCamValue != forcechasecam.value
|| m_flFadeToBlackValue != fadetoblack.value)
{
MESSAGE_BEGIN(MSG_ALL, gmsgForceCam);
WRITE_BYTE(forcecamera.value != 0);
WRITE_BYTE(forcechasecam.value != 0);
WRITE_BYTE(fadetoblack.value != 0);
MESSAGE_END();
m_flForceCameraValue = forcecamera.value;
m_flForceChaseCamValue = forcechasecam.value;
m_flFadeToBlackValue = fadetoblack.value;
}
// Check game rules
if (CheckGameOver())
return;
// have we hit the timelimit?
if (CheckTimeLimit())
return;
// did somebody hit the fraglimit ?
if (CheckFragLimit())
return;
if (!IsCareer())
{
// have we hit the max rounds?
if (CheckMaxRounds())
return;
if (CheckWinLimit())
return;
}
if (!IsCareer() || (m_fCareerMatchMenuTime <= 0.0 || m_fCareerMatchMenuTime >= gpGlobals->time))
{
if (m_iStoredSpectValue != allow_spectators.value)
{
m_iStoredSpectValue = allow_spectators.value;
MESSAGE_BEGIN(MSG_ALL, gmsgAllowSpec);
WRITE_BYTE(int(allow_spectators.value));
MESSAGE_END();
}
// Check for the end of the round.
if (IsFreezePeriod())
{
CheckFreezePeriodExpired();
}
else
{
CheckRoundTimeExpired();
}
if (m_flRestartRoundTime > 0.0f && m_flRestartRoundTime <= gpGlobals->time)
{
if (!IsCareer() || !m_fCareerRoundMenuTime)
{
RestartRound();
}
else if (TheCareerTasks)
{
bool isBotSpeaking = false;
if (m_flRestartRoundTime + 10.0f > gpGlobals->time)
{
isBotSpeaking = IsBotSpeaking();
}
if (!isBotSpeaking)
{
if (m_fCareerMatchMenuTime == 0.0f && m_iCareerMatchWins)
{
bool canCTsWin = true;
bool canTsWin = true;
if (m_iNumCTWins < m_iCareerMatchWins || (m_iNumCTWins - m_iNumTerroristWins < m_iRoundWinDifference))
canCTsWin = false;
if (m_iNumTerroristWins < m_iCareerMatchWins || (m_iNumTerroristWins - m_iNumCTWins < m_iRoundWinDifference))
canTsWin = false;
if (!Q_strcmp(humans_join_team.string, "CT"))
{
if (!TheCareerTasks->AreAllTasksComplete())
{
canCTsWin = false;
}
}
else if (!TheCareerTasks->AreAllTasksComplete())
{
canTsWin = false;
}
if (canCTsWin || canTsWin)
{
m_fCareerRoundMenuTime = 0;
m_fCareerMatchMenuTime = gpGlobals->time + 3.0f;
return;
}
}
m_bFreezePeriod = TRUE;
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *pPlayer = UTIL_PlayerByIndex(i);
if (pPlayer && !pPlayer->IsBot())
{
MESSAGE_BEGIN(MSG_ONE, gmsgCZCareerHUD, NULL, pPlayer->pev);
WRITE_STRING("ROUND");
WRITE_LONG(m_iNumCTWins);
WRITE_LONG(m_iNumTerroristWins);
WRITE_BYTE(m_iCareerMatchWins);
WRITE_BYTE(m_iRoundWinDifference);
WRITE_BYTE(m_iRoundWinStatus);
MESSAGE_END();
pPlayer->m_iHideHUD |= HIDEHUD_ALL;
m_flRestartRoundTime = gpGlobals->time + 100000.0;
UTIL_LogPrintf("Career Round %d %d %d %d\n", m_iRoundWinStatus, m_iNumCTWins, m_iNumTerroristWins, TheCareerTasks->AreAllTasksComplete());
break;
}
}
m_fCareerRoundMenuTime = 0;
}
}
if (TheTutor)
{
TheTutor->PurgeMessages();
}
}
CheckLevelInitialized();
if (gpGlobals->time > m_tmNextPeriodicThink)
{
CheckRestartRound();
m_tmNextPeriodicThink = gpGlobals->time + 1.0f;
if (g_psv_accelerate->value != 5.0f)
{
CVAR_SET_FLOAT("sv_accelerate", 5.0f);
}
if (g_psv_friction->value != 4.0f)
{
CVAR_SET_FLOAT("sv_friction", 4.0f);
}
if (g_psv_stopspeed->value != 75.0f)
{
CVAR_SET_FLOAT("sv_stopspeed", 75.0f);
}
m_iMaxRounds = int(maxrounds.value);
if (m_iMaxRounds < 0)
{
m_iMaxRounds = 0;
CVAR_SET_FLOAT("mp_maxrounds", 0);
}
m_iMaxRoundsWon = int(winlimit.value);
if (m_iMaxRoundsWon < 0)
{
m_iMaxRoundsWon = 0;
CVAR_SET_FLOAT("mp_winlimit", 0);
}
}
}
else
{
if (m_fCareerMatchMenuTime + 10 <= gpGlobals->time || !IsBotSpeaking())
{
UTIL_CareerDPrintf("Ending career match...one team has won the specified number of rounds\n");
MESSAGE_BEGIN(MSG_ALL, gmsgCZCareer);
WRITE_STRING("MATCH");
WRITE_LONG(m_iNumCTWins);
WRITE_LONG(m_iNumTerroristWins);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgCZCareerHUD);
WRITE_STRING("MATCH");
WRITE_LONG(m_iNumCTWins);
WRITE_LONG(m_iNumTerroristWins);
WRITE_BYTE(m_iCareerMatchWins);
WRITE_BYTE(m_iRoundWinDifference);
WRITE_BYTE(m_iRoundWinStatus);
MESSAGE_END();
UTIL_LogPrintf("Career Match %d %d %d %d\n", m_iRoundWinStatus, m_iNumCTWins, m_iNumTerroristWins, TheCareerTasks->AreAllTasksComplete());
SERVER_COMMAND("setpause\n");
}
}
}
bool CHalfLifeMultiplay::CheckGameOver()
{
// someone else quit the game already
if (m_bGameOver)
{
// bounds check
int time = int(CVAR_GET_FLOAT("mp_chattime"));
if (time < 1)
CVAR_SET_STRING("mp_chattime", "1");
else if (time > MAX_INTERMISSION_TIME)
CVAR_SET_STRING("mp_chattime", UTIL_dtos1(MAX_INTERMISSION_TIME));
m_flIntermissionEndTime = m_flIntermissionStartTime + mp_chattime.value;
// check to see if we should change levels now
if (m_flIntermissionEndTime < gpGlobals->time && !IsCareer())
{
if (!UTIL_HumansInGame() // if only bots, just change immediately
|| m_iEndIntermissionButtonHit // check that someone has pressed a key, or the max intermission time is over
|| ((m_flIntermissionStartTime + MAX_INTERMISSION_TIME) < gpGlobals->time))
{
// intermission is over
ChangeLevel();
}
}
return true;
}
return false;
}
bool CHalfLifeMultiplay::CheckTimeLimit()
{
if (timelimit.value < 0)
{
CVAR_SET_FLOAT("mp_timelimit", 0);
return false;
}
if (!IsCareer())
{
if (timelimit.value)
{
m_flTimeLimit = m_flGameStartTime + timelimit.value * 60.0f;
if (gpGlobals->time >= m_flTimeLimit)
{
ALERT(at_console, "Changing maps because time limit has been met\n");
GoToIntermission();
return true;
}
}
#ifdef REGAMEDLL_ADD
static int lastTime = 0;
int timeRemaining = (int)(timelimit.value ? (m_flTimeLimit - gpGlobals->time) : 0);
// Updates once per second
if (timeRemaining != lastTime)
{
lastTime = timeRemaining;
g_engfuncs.pfnCvar_DirectSet(&timeleft, UTIL_VarArgs("%02d:%02d", timeRemaining / 60, timeRemaining % 60));
}
#endif
}
return false;
}
bool CHalfLifeMultiplay::CheckMaxRounds()
{
if (m_iMaxRounds != 0 && m_iTotalRoundsPlayed >= m_iMaxRounds)
{
ALERT(at_console, "Changing maps due to maximum rounds have been met\n");
GoToIntermission();
return true;
}
return false;
}
bool CHalfLifeMultiplay::CheckWinLimit()
{
// has one team won the specified number of rounds?
if (m_iMaxRoundsWon != 0 && (m_iNumCTWins >= m_iMaxRoundsWon || m_iNumTerroristWins >= m_iMaxRoundsWon))
{
if ((m_iNumCTWins - m_iNumTerroristWins >= m_iRoundWinDifference) || (m_iNumTerroristWins - m_iNumCTWins >= m_iRoundWinDifference))
{
ALERT(at_console, "Changing maps...one team has won the specified number of rounds\n");
GoToIntermission();
return true;
}
}
return false;
}
bool CHalfLifeMultiplay::CheckFragLimit()
{
#ifdef REGAMEDLL_ADD
int fragsRemaining = 0;
if (fraglimit.value)
{
int bestFrags = fraglimit.value;
// check if any player is over the frag limit
for (int i = 1; i <= gpGlobals->maxClients; i++)
{
auto pPlayer = UTIL_PlayerByIndex(i);
if (!pPlayer || pPlayer->has_disconnected)
continue;
if (pPlayer->pev->frags >= fraglimit.value)
{
ALERT(at_console, "Changing maps because frag limit has been met\n");
GoToIntermission();
return true;
}
int remain = (int)(fraglimit.value - pPlayer->pev->frags);
if (remain < bestFrags)
{
bestFrags = remain;
}
}
fragsRemaining = bestFrags;
}
static int lastFrags = 0;
// Updates when frags change
if (fragsRemaining != lastFrags)
{
lastFrags = fragsRemaining;
g_engfuncs.pfnCvar_DirectSet(&fragsleft, UTIL_VarArgs("%i", fragsRemaining));
}
#endif
return false;
}
void EXT_FUNC CHalfLifeMultiplay::OnRoundFreezeEnd()
{
// Log this information
UTIL_LogPrintf("World triggered \"Round_Start\"\n");
// Freeze period expired: kill the flag
m_bFreezePeriod = FALSE;
char CT_sentence[40];
char T_sentence[40];
switch (RANDOM_LONG(0, 3))
{
case 0:
Q_strncpy(CT_sentence, "%!MRAD_MOVEOUT", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_MOVEOUT", sizeof(T_sentence));
break;
case 1:
Q_strncpy(CT_sentence, "%!MRAD_LETSGO", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_LETSGO", sizeof(T_sentence));
break;
case 2:
Q_strncpy(CT_sentence, "%!MRAD_LOCKNLOAD", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_LOCKNLOAD", sizeof(T_sentence));
break;
default:
Q_strncpy(CT_sentence, "%!MRAD_GO", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_GO", sizeof(T_sentence));
break;
}
// More specific radio commands for the new scenarios : Prison & Assasination
if (m_bMapHasEscapeZone)
{
Q_strncpy(CT_sentence, "%!MRAD_ELIM", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_GETOUT", sizeof(T_sentence));
}
else if (m_bMapHasVIPSafetyZone)
{
Q_strncpy(CT_sentence, "%!MRAD_VIP", sizeof(CT_sentence));
Q_strncpy(T_sentence, "%!MRAD_LOCKNLOAD", sizeof(T_sentence));
}
// Reset the round time
m_fRoundStartTimeReal = m_fRoundStartTime = gpGlobals->time;
// in seconds
m_iRoundTimeSecs = m_iRoundTime;
bool bCTPlayed = false;
bool bTPlayed = false;
if (TheCareerTasks)
{
TheCareerTasks->HandleEvent(EVENT_ROUND_START);
}
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *plr = UTIL_PlayerByIndex(i);
if (!plr || plr->pev->flags == FL_DORMANT)
continue;
if (plr->m_iJoiningState == JOINED)
{
if (plr->m_iTeam == CT && !bCTPlayed)
{
plr->Radio(CT_sentence);
bCTPlayed = true;
}
else if (plr->m_iTeam == TERRORIST && !bTPlayed)
{
plr->Radio(T_sentence);
bTPlayed = true;
}
if (plr->m_iTeam != SPECTATOR)
{
plr->ResetMaxSpeed();
plr->m_bCanShoot = true;
}
}
plr->SyncRoundTimer();
}
if (TheBots)
{
TheBots->OnEvent(EVENT_ROUND_START);
}
if (TheCareerTasks)
{
TheCareerTasks->HandleEvent(EVENT_ROUND_START);
}
}
void CHalfLifeMultiplay::CheckFreezePeriodExpired()
{
if (GetRoundRemainingTime() > 0)
return;
g_ReGameHookchains.m_CSGameRules_OnRoundFreezeEnd.callChain(&CHalfLifeMultiplay::OnRoundFreezeEnd, this);
}
bool CHalfLifeMultiplay::Target_Saved_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("ctwin");
m_iAccountCT += m_rgRewardAccountRules[RR_TARGET_BOMB_SAVED];
#ifdef REGAMEDLL_FIXES
if (!m_bNeededPlayers)
{
m_iNumCTWins++;
// Update the clients team score
UpdateTeamScores();
}
#else
m_iNumCTWins++;
#endif
EndRoundMessage("#Target_Saved", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
#ifndef REGAMEDLL_FIXES
UpdateTeamScores();
#endif
MarkLivingPlayersOnTeamAsNotReceivingMoneyNextRound(TERRORIST);
return true;
}
bool CHalfLifeMultiplay::Hostage_NotRescued_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[RR_HOSTAGE_NOT_RESCUED];
#ifdef REGAMEDLL_FIXES
if (!m_bNeededPlayers)
{
m_iNumTerroristWins++;
// Update the clients team score
UpdateTeamScores();
}
#else
m_iNumTerroristWins++;
#endif
EndRoundMessage("#Hostages_Not_Rescued", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
#ifndef REGAMEDLL_FIXES
UpdateTeamScores();
#endif
MarkLivingPlayersOnTeamAsNotReceivingMoneyNextRound(CT);
return true;
}
bool CHalfLifeMultiplay::Prison_NotEscaped_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("ctwin");
#ifdef REGAMEDLL_FIXES
if (!m_bNeededPlayers)
{
m_iNumCTWins++;
// Update the clients team score
UpdateTeamScores();
}
#else
m_iNumCTWins++;
#endif
EndRoundMessage("#Terrorists_Not_Escaped", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
#ifndef REGAMEDLL_FIXES
UpdateTeamScores();
#endif
return true;
}
bool CHalfLifeMultiplay::VIP_NotEscaped_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
Broadcast("terwin");
m_iAccountTerrorist += m_rgRewardAccountRules[RR_VIP_NOT_ESCAPED];
#ifdef REGAMEDLL_FIXES
if (!m_bNeededPlayers)
{
m_iNumTerroristWins++;
// Update the clients team score
UpdateTeamScores();
}
#else
m_iNumTerroristWins++;
#endif
EndRoundMessage("#VIP_Not_Escaped", event);
TerminateRound(tmDelay, winStatus);
if (IsCareer())
{
QueueCareerRoundEndMenu(tmDelay, winStatus);
}
#ifndef REGAMEDLL_FIXES
UpdateTeamScores();
#endif
return true;
}
bool CHalfLifeMultiplay::RoundOver_internal(int winStatus, ScenarioEventEndRound event, float tmDelay)
{
EndRoundMessage("Round is Over!", event);
Broadcast("rounddraw");
TerminateRound(tmDelay, winStatus);
return true;
}
void CHalfLifeMultiplay::CheckRoundTimeExpired()
{
if (HasRoundInfinite(SCENARIO_BLOCK_TIME_EXPRIRED))
return;
if (!HasRoundTimeExpired())
return;
#if 0
// Round time expired
float flEndRoundTime;
// Check to see if there's still a live C4 hanging around.. if so, wait until this C4 blows before ending the round
CGrenade *pBomb = (CGrenade *)UTIL_FindEntityByClassname(NULL, "grenade");
if (pBomb)
{
if (!pBomb->m_bJustBlew)
flEndRoundTime = pBomb->m_flC4Blow;
else
flEndRoundTime = gpGlobals->time + 5.0f;
}
#endif
// New code to get rid of round draws!!
if (m_bMapHasBombTarget)
{
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Target_Saved_internal, this, WINSTATUS_CTS, ROUND_TARGET_SAVED, GetRoundRestartDelay()))
return;
}
else if (UTIL_FindEntityByClassname(NULL, "hostage_entity"))
{
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Hostage_NotRescued_internal, this, WINSTATUS_TERRORISTS, ROUND_HOSTAGE_NOT_RESCUED, GetRoundRestartDelay()))
return;
}
else if (m_bMapHasEscapeZone)
{
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::Prison_NotEscaped_internal, this, WINSTATUS_CTS, ROUND_TERRORISTS_NOT_ESCAPED, GetRoundRestartDelay()))
return;
}
else if (m_bMapHasVIPSafetyZone)
{
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::VIP_NotEscaped_internal, this, WINSTATUS_TERRORISTS, ROUND_VIP_NOT_ESCAPED, GetRoundRestartDelay()))
return;
}
#ifdef REGAMEDLL_ADD
else if (roundover.value)
{
// round is over
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::RoundOver_internal, this, WINSTATUS_DRAW, ROUND_GAME_OVER, GetRoundRestartDelay()))
return;
}
#endif
// This is done so that the portion of code has enough time to do it's thing.
m_fRoundStartTime = gpGlobals->time + 60.0f;
}
void CHalfLifeMultiplay::CheckLevelInitialized()
{
if (!m_bLevelInitialized)
{
// Count the number of spawn points for each team
// This determines the maximum number of players allowed on each
CBaseEntity *ent = NULL;
m_iSpawnPointCount_Terrorist = 0;
m_iSpawnPointCount_CT = 0;
while ((ent = UTIL_FindEntityByClassname(ent, "info_player_deathmatch")))
++m_iSpawnPointCount_Terrorist;
while ((ent = UTIL_FindEntityByClassname(ent, "info_player_start")))
++m_iSpawnPointCount_CT;
m_bLevelInitialized = true;
}
}
bool CHalfLifeMultiplay::RestartRoundCheck_internal(int winStatus, ScenarioEventEndRound event, float tmDelay) {
return true;
}
void CHalfLifeMultiplay::CheckRestartRound()
{
// Restart the round if specified by the server
int iRestartDelay = int(restartround.value);
if (!iRestartDelay)
{
iRestartDelay = sv_restart.value;
}
if (iRestartDelay > 0)
{
#ifndef REGAMEDLL_ADD
if (iRestartDelay > 60)
iRestartDelay = 60;
#endif
if (!g_ReGameHookchains.m_RoundEnd.callChain(&CHalfLifeMultiplay::RestartRoundCheck_internal, this, 0, ROUND_GAME_RESTART, iRestartDelay))
return;
// log the restart
UTIL_LogPrintf("World triggered \"Restart_Round_(%i_%s)\"\n", iRestartDelay, (iRestartDelay == 1) ? "second" : "seconds");
UTIL_LogPrintf("Team \"CT\" scored \"%i\" with \"%i\" players\n", m_iNumCTWins, m_iNumCT);
UTIL_LogPrintf("Team \"TERRORIST\" scored \"%i\" with \"%i\" players\n", m_iNumTerroristWins, m_iNumTerrorist);
// let the players know
UTIL_ClientPrintAll(HUD_PRINTCENTER, "#Game_will_restart_in", UTIL_dtos1(iRestartDelay), (iRestartDelay == 1) ? "SECOND" : "SECONDS");
UTIL_ClientPrintAll(HUD_PRINTCONSOLE, "#Game_will_restart_in_console", UTIL_dtos1(iRestartDelay), (iRestartDelay == 1) ? "SECOND" : "SECONDS");
m_flRestartRoundTime = gpGlobals->time + iRestartDelay;
m_bCompleteReset = true;
CVAR_SET_FLOAT("sv_restartround", 0);
CVAR_SET_FLOAT("sv_restart", 0);
CareerRestart();
}
}
bool CHalfLifeMultiplay::HasRoundTimeExpired()
{
#ifdef REGAMEDLL_ADD
if (!m_iRoundTime)
return false;
#endif
// We haven't completed other objectives, so go for this!.
if (GetRoundRemainingTime() > 0 || m_iRoundWinStatus != WINNER_NONE)
{
return false;
}
// If the bomb is planted, don't let the round timer end the round.
// keep going until the bomb explodes or is defused
if (!IsBombPlanted())
{
if (cv_bot_nav_edit.value == 0.0f || IS_DEDICATED_SERVER() || UTIL_HumansInGame() != 1)
{
return true;
}
}
return false;
}
bool CHalfLifeMultiplay::IsBombPlanted()
{
if (m_bMapHasBombTarget)
{
CGrenade *bomb = nullptr;
while ((bomb = (CGrenade *)UTIL_FindEntityByClassname(bomb, "grenade")))
{
if (bomb->m_bIsC4)
{
return true;
}
}
}
return false;
}
// living players on the given team need to be marked as not receiving any money
// next round.
void CHalfLifeMultiplay::MarkLivingPlayersOnTeamAsNotReceivingMoneyNextRound(int iTeam)
{
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *player = UTIL_PlayerByIndex(i);
if (!player || FNullEnt(player->pev))
continue;
if (player->m_iTeam == iTeam)
{
if (player->pev->health > 0 && player->pev->deadflag == DEAD_NO)
{
player->m_bReceivesNoMoneyNextRound = true;
}
}
}
}
void CHalfLifeMultiplay::CareerRestart()
{
m_bGameOver = false;
if (m_flRestartRoundTime == 0.0f)
{
m_flRestartRoundTime = gpGlobals->time + 1.0f;
}
// for reset everything
m_bCompleteReset = true;
m_fCareerRoundMenuTime = 0;
m_fCareerMatchMenuTime = 0;
if (TheCareerTasks)
{
TheCareerTasks->Reset(false);
}
m_bSkipSpawn = false;
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *player = UTIL_PlayerByIndex(i);
if (!player || FNullEnt(player->pev))
continue;
if (!player->IsBot())
{
player->ForceClientDllUpdate();
}
}
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(IsMultiplayer)()
{
return TRUE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(IsDeathmatch)()
{
return TRUE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(IsCoOp)()
{
return gpGlobals->coop;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(BOOL, CHalfLifeMultiplay, CSGameRules, FShouldSwitchWeapon, (CBasePlayer *pPlayer, CBasePlayerItem *pWeapon), pPlayer, pWeapon)
BOOL EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(FShouldSwitchWeapon)(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon)
{
if (!pWeapon->CanDeploy())
return FALSE;
if (!pPlayer->m_pActiveItem)
return TRUE;
if (!pPlayer->m_iAutoWepSwitch)
return FALSE;
if (!pPlayer->m_pActiveItem->CanHolster())
return FALSE;
if (pWeapon->iWeight() > pPlayer->m_pActiveItem->iWeight())
return TRUE;
return FALSE;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(BOOL, CHalfLifeMultiplay, CSGameRules, GetNextBestWeapon, (CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon), pPlayer, pCurrentWeapon)
BOOL EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(GetNextBestWeapon)(CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon)
{
CBasePlayerItem *pCheck;
CBasePlayerItem *pBest; // this will be used in the event that we don't find a weapon in the same category.
int iBestWeight;
int i;
if (!pCurrentWeapon->CanHolster())
{
// can't put this gun away right now, so can't switch.
return FALSE;
}
iBestWeight = -1; // no weapon lower than -1 can be autoswitched to
pBest = NULL;
for (i = 0; i < MAX_ITEM_TYPES; ++i)
{
pCheck = pPlayer->m_rgpPlayerItems[i];
while (pCheck)
{
// don't reselect the weapon we're trying to get rid of
if (pCheck->iWeight() > iBestWeight && pCheck != pCurrentWeapon)
{
//ALERT (at_console, "Considering %s\n", STRING(pCheck->pev->classname));
// we keep updating the 'best' weapon just in case we can't find a weapon of the same weight
// that the player was using. This will end up leaving the player with his heaviest-weighted
// weapon.
if (pCheck->CanDeploy())
{
// if this weapon is useable, flag it as the best
iBestWeight = pCheck->iWeight();
pBest = pCheck;
}
}
pCheck = pCheck->m_pNext;
}
}
// if we make it here, we've checked all the weapons and found no useable
// weapon in the same catagory as the current weapon.
// if pBest is null, we didn't find ANYTHING. Shouldn't be possible- should always
// at least get the crowbar, but ya never know.
if (!pBest)
{
return FALSE;
}
pPlayer->SwitchWeapon(pBest);
return TRUE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(ClientCommand_DeadOrAlive)(CBasePlayer *pPlayer, const char *pcmd)
{
return m_VoiceGameMgr.ClientCommand(pPlayer, pcmd);
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(ClientCommand)(CBasePlayer *pPlayer, const char *pcmd)
{
return FALSE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(ClientConnected)(edict_t *pEntity, const char *pszName, const char *pszAddress, char *szRejectReason)
{
m_VoiceGameMgr.ClientConnected(pEntity);
return TRUE;
}
void CHalfLifeMultiplay::__MAKE_VHOOK(UpdateGameMode)(CBasePlayer *pPlayer)
{
MESSAGE_BEGIN(MSG_ONE, gmsgGameMode, NULL, pPlayer->edict());
WRITE_BYTE(1);
MESSAGE_END();
}
void CHalfLifeMultiplay::__MAKE_VHOOK(InitHUD)(CBasePlayer *pl)
{
int i;
// notify other clients of player joining the game
UTIL_LogPrintf("\"%s<%i><%s><>\" entered the game\n", STRING(pl->pev->netname), GETPLAYERUSERID(pl->edict()), GETPLAYERAUTHID(pl->edict()));
UpdateGameMode(pl);
if (!g_flWeaponCheat)
{
MESSAGE_BEGIN(MSG_ONE, gmsgViewMode, NULL, pl->edict());
MESSAGE_END();
}
// sending just one score makes the hud scoreboard active; otherwise
// it is just disabled for single play
MESSAGE_BEGIN(MSG_ONE, gmsgScoreInfo, NULL, pl->edict());
WRITE_BYTE(ENTINDEX(pl->edict()));
WRITE_SHORT(0);
WRITE_SHORT(0);
WRITE_SHORT(0);
WRITE_SHORT(pl->m_iTeam);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ONE, gmsgShadowIdx, NULL, pl->edict());
WRITE_LONG(g_iShadowSprite);
MESSAGE_END();
if (IsCareer())
{
MESSAGE_BEGIN(MSG_ONE, gmsgCZCareer, NULL, pl->edict());
WRITE_STRING("START");
WRITE_SHORT(m_iRoundTime);
MESSAGE_END();
}
else
SendMOTDToClient(pl->edict());
// loop through all active players and send their score info to the new client
for (i = 1; i <= gpGlobals->maxClients; ++i)
{
// FIXME: Probably don't need to cast this just to read m_iDeaths
CBasePlayer *plr = UTIL_PlayerByIndex(i);
if (!plr)
continue;
#ifdef REGAMEDLL_FIXES
if (plr->IsDormant())
continue;
#endif
MESSAGE_BEGIN(MSG_ONE, gmsgScoreInfo, NULL, pl->edict());
WRITE_BYTE(i); // client number
WRITE_SHORT(int(plr->pev->frags));
WRITE_SHORT(plr->m_iDeaths);
WRITE_SHORT(0);
WRITE_SHORT(plr->m_iTeam);
MESSAGE_END();
}
MESSAGE_BEGIN(MSG_ONE, gmsgTeamScore, NULL, pl->edict());
WRITE_STRING("TERRORIST");
WRITE_SHORT(m_iNumTerroristWins);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ONE, gmsgTeamScore, NULL, pl->edict());
WRITE_STRING("CT");
WRITE_SHORT(m_iNumCTWins);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ONE, gmsgAllowSpec, NULL, pl->edict());
WRITE_BYTE(int(allow_spectators.value));
MESSAGE_END();
MESSAGE_BEGIN(MSG_ONE, gmsgForceCam, NULL, pl->edict());
WRITE_BYTE(forcecamera.value != 0);
WRITE_BYTE(forcechasecam.value != 0);
WRITE_BYTE(fadetoblack.value != 0);
MESSAGE_END();
if (m_bGameOver)
{
MESSAGE_BEGIN(MSG_ONE, SVC_INTERMISSION, NULL, pl->edict());
MESSAGE_END();
}
for (i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *plr = UTIL_PlayerByIndex(i);
if (!plr)
continue;
#ifdef REGAMEDLL_FIXES
if (plr->IsDormant())
continue;
#endif
MESSAGE_BEGIN(MSG_ONE, gmsgTeamInfo, NULL, pl->edict());
WRITE_BYTE(plr->entindex());
WRITE_STRING(GetTeamName(plr->m_iTeam));
MESSAGE_END();
plr->SetScoreboardAttributes(pl);
if (pl->entindex() != i)
{
#ifndef REGAMEDLL_FIXES
if (plr->pev->flags == FL_DORMANT)
continue;
#endif
if (plr->pev->deadflag == DEAD_NO)
{
MESSAGE_BEGIN(MSG_ONE, gmsgRadar, NULL, pl->edict());
WRITE_BYTE(plr->entindex());
WRITE_COORD(plr->pev->origin.x);
WRITE_COORD(plr->pev->origin.y);
WRITE_COORD(plr->pev->origin.z);
MESSAGE_END();
}
}
}
auto SendMsgBombDrop = [&pl](const int flag, const Vector& pos)
{
MESSAGE_BEGIN(MSG_ONE, gmsgBombDrop, NULL, pl->edict());
WRITE_COORD(pos.x);
WRITE_COORD(pos.y);
WRITE_COORD(pos.z);
WRITE_BYTE(flag);
MESSAGE_END();
};
if (m_bBombDropped)
{
CBaseEntity *pWeaponC4 = UTIL_FindEntityByClassname(NULL, "weapon_c4");
if (pWeaponC4)
{
SendMsgBombDrop(BOMB_FLAG_DROPPED, pWeaponC4->pev->origin);
}
}
#ifdef REGAMEDLL_FIXES
else
{
CGrenade *bomb = nullptr;
while ((bomb = (CGrenade *)UTIL_FindEntityByClassname(bomb, "grenade")))
{
if (bomb->m_bIsC4)
{
// if the bomb was planted, which will trigger the round timer to hide.
SendMsgBombDrop(BOMB_FLAG_PLANTED, bomb->pev->origin);
if (m_iRoundTime > 0 || GetRoundRemainingTime() >= 1.0f)
{
MESSAGE_BEGIN(MSG_ONE, gmsgShowTimer, NULL, pl->pev);
MESSAGE_END();
}
else
{
// HACK HACK, we need to hide only the timer.
SendMsgBombDrop(BOMB_FLAG_PLANTED, g_vecZero);
MESSAGE_BEGIN(MSG_ONE, gmsgBombPickup, NULL, pl->pev);
MESSAGE_END();
}
break;
}
}
}
#endif
}
void CHalfLifeMultiplay::__MAKE_VHOOK(ClientDisconnected)(edict_t *pClient)
{
if (pClient)
{
CBasePlayer *pPlayer = static_cast<CBasePlayer *>(CBaseEntity::Instance(pClient));
if (pPlayer)
{
pPlayer->has_disconnected = true;
pPlayer->pev->deadflag = DEAD_DEAD;
pPlayer->SetScoreboardAttributes();
if (pPlayer->m_bHasC4)
{
pPlayer->DropPlayerItem("weapon_c4");
}
if (pPlayer->m_bHasDefuser)
{
pPlayer->DropPlayerItem("item_thighpack");
}
if (pPlayer->m_bIsVIP)
{
m_pVIP = NULL;
}
pPlayer->m_iCurrentKickVote = 0;
if (pPlayer->m_iMapVote)
{
--m_iMapVotes[ pPlayer->m_iMapVote ];
if (m_iMapVotes[ pPlayer->m_iMapVote ] < 0)
{
m_iMapVotes[ pPlayer->m_iMapVote ] = 0;
}
}
MESSAGE_BEGIN(MSG_ALL, gmsgScoreInfo);
WRITE_BYTE(ENTINDEX(pClient));
WRITE_SHORT(0);
WRITE_SHORT(0);
WRITE_SHORT(0);
WRITE_SHORT(0);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgTeamInfo);
WRITE_BYTE(ENTINDEX(pClient));
WRITE_STRING("UNASSIGNED");
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgLocation);
WRITE_BYTE(ENTINDEX(pClient));
WRITE_STRING("");
MESSAGE_END();
char *team = GetTeam(pPlayer->m_iTeam);
FireTargets("game_playerleave", pPlayer, pPlayer, USE_TOGGLE, 0);
UTIL_LogPrintf("\"%s<%i><%s><%s>\" disconnected\n", STRING(pPlayer->pev->netname), GETPLAYERUSERID(pPlayer->edict()), GETPLAYERAUTHID(pPlayer->edict()), team);
// destroy all of the players weapons and items
pPlayer->RemoveAllItems(TRUE);
if (pPlayer->m_pObserver)
{
pPlayer->m_pObserver->SUB_Remove();
}
CBasePlayer *client = NULL;
while ((client = (CBasePlayer *)UTIL_FindEntityByClassname(client, "player")))
{
if (FNullEnt(client->edict()))
break;
if (!client->pev || client == pPlayer)
continue;
if (client->m_hObserverTarget == pPlayer)
{
int iMode = client->pev->iuser1;
client->pev->iuser1 = OBS_NONE;
client->Observer_SetMode(iMode);
}
}
}
}
CheckWinConditions();
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(float, CHalfLifeMultiplay, CSGameRules, FlPlayerFallDamage, (CBasePlayer *pPlayer), pPlayer)
float EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(FlPlayerFallDamage)(CBasePlayer *pPlayer)
{
pPlayer->m_flFallVelocity -= PLAYER_MAX_SAFE_FALL_SPEED;
return pPlayer->m_flFallVelocity * DAMAGE_FOR_FALL_SPEED * 1.25;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(BOOL, CHalfLifeMultiplay, CSGameRules, FPlayerCanTakeDamage, (CBasePlayer *pPlayer, CBaseEntity *pAttacker), pPlayer, pAttacker)
BOOL EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(FPlayerCanTakeDamage)(CBasePlayer *pPlayer, CBaseEntity *pAttacker)
{
if (!pAttacker || PlayerRelationship(pPlayer, pAttacker) != GR_TEAMMATE)
{
return TRUE;
}
if (friendlyfire.value != 0.0f || pAttacker == pPlayer)
{
return TRUE;
}
return FALSE;
}
void CHalfLifeMultiplay::__MAKE_VHOOK(PlayerThink)(CBasePlayer *pPlayer)
{
if (m_bGameOver)
{
// check for button presses
if (!IsCareer() && (pPlayer->m_afButtonPressed & (IN_DUCK | IN_ATTACK | IN_ATTACK2 | IN_USE | IN_JUMP)))
{
m_iEndIntermissionButtonHit = TRUE;
}
// clear attack/use commands from player
pPlayer->m_afButtonPressed = 0;
pPlayer->pev->button = 0;
pPlayer->m_afButtonReleased = 0;
}
if (!pPlayer->m_bCanShoot && !IsFreezePeriod())
{
pPlayer->m_bCanShoot = true;
}
if (pPlayer->m_pActiveItem && pPlayer->m_pActiveItem->IsWeapon())
{
CBasePlayerWeapon *pWeapon = static_cast<CBasePlayerWeapon *>(pPlayer->m_pActiveItem->GetWeaponPtr());
if (pWeapon->m_iWeaponState & WPNSTATE_SHIELD_DRAWN)
{
pPlayer->m_bCanShoot = false;
}
}
if (pPlayer->m_iMenu != Menu_ChooseTeam && pPlayer->m_iJoiningState == SHOWTEAMSELECT)
{
int slot = MENU_SLOT_TEAM_UNDEFINED;
if (!Q_stricmp(humans_join_team.string, "T"))
{
slot = MENU_SLOT_TEAM_TERRORIST;
}
else if (!Q_stricmp(humans_join_team.string, "CT"))
{
slot = MENU_SLOT_TEAM_CT;
}
#ifdef REGAMEDLL_ADD
else if (!Q_stricmp(humans_join_team.string, "any") && auto_join_team.value != 0.0f)
{
slot = MENU_SLOT_TEAM_RANDOM;
}
else if (!Q_stricmp(humans_join_team.string, "SPEC") && auto_join_team.value != 0.0f)
{
slot = MENU_SLOT_TEAM_SPECT;
}
#endif
else
{
if (allow_spectators.value == 0.0f)
ShowVGUIMenu(pPlayer, VGUI_Menu_Team, (MENU_KEY_1 | MENU_KEY_2 | MENU_KEY_5), "#Team_Select");
else
ShowVGUIMenu(pPlayer, VGUI_Menu_Team, (MENU_KEY_1 | MENU_KEY_2 | MENU_KEY_5 | MENU_KEY_6), "#Team_Select_Spect");
}
pPlayer->m_iMenu = Menu_ChooseTeam;
pPlayer->m_iJoiningState = PICKINGTEAM;
if (slot != MENU_SLOT_TEAM_UNDEFINED && !pPlayer->IsBot())
{
#ifdef REGAMEDLL_ADD
m_bSkipShowMenu = (auto_join_team.value != 0.0f) && !(pPlayer->pev->flags & FL_FAKECLIENT);
if (HandleMenu_ChooseTeam(pPlayer, slot))
{
if (slot != MENU_SLOT_TEAM_SPECT && (IsCareer() || m_bSkipShowMenu))
{
// slot 6 - chooses randomize the appearance to model player
HandleMenu_ChooseAppearance(pPlayer, 6);
}
}
else
{
m_bSkipShowMenu = false;
if (allow_spectators.value == 0.0f)
ShowVGUIMenu(pPlayer, VGUI_Menu_Team, (MENU_KEY_1 | MENU_KEY_2 | MENU_KEY_5), "#Team_Select");
else
ShowVGUIMenu(pPlayer, VGUI_Menu_Team, (MENU_KEY_1 | MENU_KEY_2 | MENU_KEY_5 | MENU_KEY_6), "#Team_Select_Spect");
}
m_bSkipShowMenu = false;
#else
HandleMenu_ChooseTeam(pPlayer, slot);
if (slot != MENU_SLOT_TEAM_SPECT && IsCareer())
{
// slot 6 - chooses randomize the appearance to model player
HandleMenu_ChooseAppearance(pPlayer, 6);
}
#endif
}
}
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN(CHalfLifeMultiplay, CSGameRules, PlayerSpawn, (CBasePlayer *pPlayer), pPlayer)
// Purpose: Player has just spawned. Equip them.
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(PlayerSpawn)(CBasePlayer *pPlayer)
{
// This is tied to the joining state (m_iJoiningState).. add it when the joining state is there.
if (pPlayer->m_bJustConnected)
return;
pPlayer->pev->weapons |= (1 << WEAPON_SUIT);
pPlayer->OnSpawnEquip();
pPlayer->SetPlayerModel(false);
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(BOOL, CHalfLifeMultiplay, CSGameRules, FPlayerCanRespawn, (CBasePlayer *pPlayer), pPlayer)
BOOL EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(FPlayerCanRespawn)(CBasePlayer *pPlayer)
{
#ifdef REGAMEDLL_ADD
if (forcerespawn.value <= 0)
#endif
{
// Player cannot respawn twice in a round
if (pPlayer->m_iNumSpawns > 0)
{
return FALSE;
}
// Player cannot respawn until next round if more than 20 seconds in
// Tabulate the number of players on each team.
m_iNumCT = CountTeamPlayers(CT);
m_iNumTerrorist = CountTeamPlayers(TERRORIST);
if (m_iNumTerrorist > 0 && m_iNumCT > 0)
{
#ifdef REGAMEDLL_ADD
// means no time limit
if (GetRoundRespawnTime() != -1)
#endif
{
// TODO: to be correct, need use time the real one starts of round, m_fRoundStartTimeReal instead of it.
// m_fRoundStartTime able to extend the time to 60 seconds when there is a remaining time of round.
#ifdef REGAMEDLL_FIXES
if (gpGlobals->time > m_fRoundStartTimeReal + GetRoundRespawnTime())
#else
if (gpGlobals->time > m_fRoundStartTime + GetRoundRespawnTime())
#endif
{
// If this player just connected and fadetoblack is on, then maybe
// the server admin doesn't want him peeking around.
if (fadetoblack.value != 0.0f)
{
UTIL_ScreenFade(pPlayer, Vector(0, 0, 0), 3, 3, 255, (FFADE_OUT | FFADE_STAYOUT));
}
return FALSE;
}
}
}
}
// Player cannot respawn while in the Choose Appearance menu
if (pPlayer->m_iMenu == Menu_ChooseAppearance)
{
return FALSE;
}
return TRUE;
}
float CHalfLifeMultiplay::__MAKE_VHOOK(FlPlayerSpawnTime)(CBasePlayer *pPlayer)
{
return gpGlobals->time;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(AllowAutoTargetCrosshair)()
{
return FALSE;
}
// IPointsForKill - how many points awarded to anyone
// that kills this player?
int CHalfLifeMultiplay::__MAKE_VHOOK(IPointsForKill)(CBasePlayer *pAttacker, CBasePlayer *pKilled)
{
return 1;
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN(CHalfLifeMultiplay, CSGameRules, PlayerKilled, (CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor), pVictim, pKiller, pInflictor)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(PlayerKilled)(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor)
{
DeathNotice(pVictim, pKiller, pInflictor);
pVictim->m_afPhysicsFlags &= ~PFLAG_ONTRAIN;
pVictim->m_iDeaths++;
pVictim->m_bNotKilled = false;
pVictim->m_bEscaped = false;
pVictim->m_iTrain = (TRAIN_NEW | TRAIN_OFF);
SET_VIEW(ENT(pVictim->pev), ENT(pVictim->pev));
CBasePlayer *peKiller = NULL;
CBaseEntity *ktmp = CBaseEntity::Instance(pKiller);
if (ktmp && ktmp->Classify() == CLASS_PLAYER)
{
peKiller = static_cast<CBasePlayer *>(ktmp);
}
else if (ktmp && ktmp->Classify() == CLASS_VEHICLE)
{
CBasePlayer *pDriver = static_cast<CBasePlayer *>(((CFuncVehicle *)ktmp)->m_pDriver);
if (pDriver)
{
pKiller = pDriver->pev;
peKiller = static_cast<CBasePlayer *>(pDriver);
}
}
FireTargets("game_playerdie", pVictim, pVictim, USE_TOGGLE, 0);
// Did the player kill himself?
if (pVictim->pev == pKiller)
{
// Players lose a frag for killing themselves
pKiller->frags -= 1;
}
else if (peKiller && peKiller->IsPlayer())
{
// if a player dies in a deathmatch game and the killer is a client, award the killer some points
CBasePlayer *killer = GetClassPtr<CCSPlayer>((CBasePlayer *)pKiller);
bool killedByFFA = IsFreeForAll();
if (killer->m_iTeam == pVictim->m_iTeam && !killedByFFA)
{
// if a player dies by from teammate
pKiller->frags -= IPointsForKill(peKiller, pVictim);
killer->AddAccount(PAYBACK_FOR_KILLED_TEAMMATES, RT_TEAMMATES_KILLED);
killer->m_iTeamKills++;
killer->m_bJustKilledTeammate = true;
ClientPrint(killer->pev, HUD_PRINTCENTER, "#Killed_Teammate");
ClientPrint(killer->pev, HUD_PRINTCONSOLE, "#Game_teammate_kills", UTIL_dtos1(killer->m_iTeamKills));
#ifdef REGAMEDLL_ADD
if (autokick.value && max_teamkills.value && killer->m_iTeamKills >= (int)max_teamkills.value)
#else
if (autokick.value && killer->m_iTeamKills == 3)
#endif
{
#ifdef REGAMEDLL_FIXES
ClientPrint(killer->pev, HUD_PRINTCONSOLE, "#Banned_For_Killing_Teammates");
#else
ClientPrint(killer->pev, HUD_PRINTCONSOLE, "#Banned_For_Killing_Teamates");
#endif
int iUserID = GETPLAYERUSERID(killer->edict());
if (iUserID != -1)
{
SERVER_COMMAND(UTIL_VarArgs("kick # %d\n", iUserID));
}
}
if (!(killer->m_flDisplayHistory & DHF_FRIEND_KILLED))
{
killer->m_flDisplayHistory |= DHF_FRIEND_KILLED;
killer->HintMessage("#Hint_careful_around_teammates");
}
}
else
{
// if a player dies in a deathmatch game and the killer is a client, award the killer some points
pKiller->frags += IPointsForKill(peKiller, pVictim);
if (pVictim->m_bIsVIP)
{
killer->HintMessage("#Hint_reward_for_killing_vip", TRUE);
killer->AddAccount(REWARD_KILLED_VIP, RT_VIP_KILLED);
MESSAGE_BEGIN(MSG_SPEC, SVC_DIRECTOR);
WRITE_BYTE(9);
WRITE_BYTE(DRC_CMD_EVENT);
WRITE_SHORT(ENTINDEX(pVictim->edict()));
WRITE_SHORT(ENTINDEX(ENT(pInflictor)));
WRITE_LONG(DRC_FLAG_PRIO_MASK | DRC_FLAG_DRAMATIC | DRC_FLAG_FINAL);
MESSAGE_END();
UTIL_LogPrintf("\"%s<%i><%s><TERRORIST>\" triggered \"Assassinated_The_VIP\"\n", STRING(killer->pev->netname), GETPLAYERUSERID(killer->edict()), GETPLAYERAUTHID(killer->edict()));
}
else
killer->AddAccount(REWARD_KILLED_ENEMY, RT_ENEMY_KILLED);
if (!(killer->m_flDisplayHistory & DHF_ENEMY_KILLED))
{
killer->m_flDisplayHistory |= DHF_ENEMY_KILLED;
killer->HintMessage("#Hint_win_round_by_killing_enemy");
}
}
FireTargets("game_playerkill", peKiller, peKiller, USE_TOGGLE, 0);
}
else
{
// killed by the world
pKiller->frags -= 1;
}
// update the scores
// killed scores
#ifndef REGAMEDLL_FIXES
MESSAGE_BEGIN(MSG_BROADCAST, gmsgScoreInfo);
#else
MESSAGE_BEGIN(MSG_ALL, gmsgScoreInfo);
#endif
WRITE_BYTE(ENTINDEX(pVictim->edict()));
WRITE_SHORT(int(pVictim->pev->frags));
WRITE_SHORT(pVictim->m_iDeaths);
WRITE_SHORT(0);
WRITE_SHORT(pVictim->m_iTeam);
MESSAGE_END();
// killers score, if it's a player
CBaseEntity *ep = CBaseEntity::Instance(pKiller);
if (ep && ep->Classify() == CLASS_PLAYER)
{
CBasePlayer *PK = static_cast<CBasePlayer *>(ep);
MESSAGE_BEGIN(MSG_ALL, gmsgScoreInfo);
WRITE_BYTE(ENTINDEX(PK->edict()));
WRITE_SHORT(int(PK->pev->frags));
WRITE_SHORT(PK->m_iDeaths);
WRITE_SHORT(0);
WRITE_SHORT(PK->m_iTeam);
MESSAGE_END();
// let the killer paint another decal as soon as he'd like.
PK->m_flNextDecalTime = gpGlobals->time;
}
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN(CHalfLifeMultiplay, CSGameRules, DeathNotice, (CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pevInflictor), pVictim, pKiller, pevInflictor)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(DeathNotice)(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pevInflictor)
{
// Work out what killed the player, and send a message to all clients about it
// CBaseEntity *Killer = CBaseEntity::Instance(pKiller);
// by default, the player is killed by the world
const char *killer_weapon_name = "world";
int killer_index = 0;
#ifndef REGAMEDLL_FIXES
// Hack to fix name change
char *tau = "tau_cannon";
char *gluon = "gluon gun";
#endif
// Is the killer a client?
if (pKiller->flags & FL_CLIENT)
{
killer_index = ENTINDEX(ENT(pKiller));
if (pevInflictor)
{
if (pevInflictor == pKiller)
{
// If the inflictor is the killer, then it must be their current weapon doing the damage
CBasePlayer *pAttacker = CBasePlayer::Instance(pKiller);
if (pAttacker && pAttacker->IsPlayer())
{
if (pAttacker->m_pActiveItem)
killer_weapon_name = pAttacker->m_pActiveItem->pszName();
}
}
else
{
// it's just that easy
killer_weapon_name = STRING(pevInflictor->classname);
}
}
}
else
#ifdef REGAMEDLL_FIXES
if (pevInflictor)
#endif
{
killer_weapon_name = STRING(pevInflictor->classname);
}
// strip the monster_* or weapon_* from the inflictor's classname
const char cut_weapon[] = "weapon_";
const char cut_monster[] = "monster_";
const char cut_func[] = "func_";
if (!Q_strncmp(killer_weapon_name, cut_weapon, sizeof(cut_weapon) - 1))
killer_weapon_name += sizeof(cut_weapon) - 1;
else if (!Q_strncmp(killer_weapon_name, cut_monster, sizeof(cut_monster) - 1))
killer_weapon_name += sizeof(cut_monster) - 1;
else if (!Q_strncmp(killer_weapon_name, cut_func, sizeof(cut_func) - 1))
killer_weapon_name += sizeof(cut_func) - 1;
if (!TheTutor)
{
MESSAGE_BEGIN(MSG_ALL, gmsgDeathMsg);
WRITE_BYTE(killer_index); // the killer
WRITE_BYTE(ENTINDEX(pVictim->edict())); // the victim
WRITE_BYTE(pVictim->m_bHeadshotKilled); // is killed headshot
WRITE_STRING(killer_weapon_name); // what they were killed by (should this be a string?)
MESSAGE_END();
}
// This weapons from HL isn't it?
#ifndef REGAMEDLL_FIXES
// replace the code names with the 'real' names
if (!Q_strcmp(killer_weapon_name, "egon"))
killer_weapon_name = gluon;
else if (!Q_strcmp(killer_weapon_name, "gauss"))
killer_weapon_name = tau;
#endif
// Did he kill himself?
if (pVictim->pev == pKiller)
{
// killed self
char *team = GetTeam(pVictim->m_iTeam);
UTIL_LogPrintf("\"%s<%i><%s><%s>\" committed suicide with \"%s\"\n", STRING(pVictim->pev->netname), GETPLAYERUSERID(pVictim->edict()),
GETPLAYERAUTHID(pVictim->edict()), team, killer_weapon_name);
}
else if (pKiller->flags & FL_CLIENT)
{
CBasePlayer *pAttacker = CBasePlayer::Instance(pKiller);
const char *VictimTeam = GetTeam(pVictim->m_iTeam);
const char *KillerTeam = (pAttacker && pAttacker->IsPlayer()) ? GetTeam(pAttacker->m_iTeam) : "";
UTIL_LogPrintf("\"%s<%i><%s><%s>\" killed \"%s<%i><%s><%s>\" with \"%s\"\n", STRING(pKiller->netname), GETPLAYERUSERID(ENT(pKiller)), GETPLAYERAUTHID(ENT(pKiller)),
KillerTeam, STRING(pVictim->pev->netname), GETPLAYERUSERID(pVictim->edict()), GETPLAYERAUTHID(pVictim->edict()), VictimTeam, killer_weapon_name);
}
else
{
// killed by the world
char *team = GetTeam(pVictim->m_iTeam);
UTIL_LogPrintf("\"%s<%i><%s><%s>\" committed suicide with \"%s\" (world)\n", STRING(pVictim->pev->netname), GETPLAYERUSERID(pVictim->edict()),
GETPLAYERAUTHID(pVictim->edict()), team, killer_weapon_name);
}
// TODO: It is called in CBasePlayer::Killed too, most likely,
// an unnecessary call. (Need investigate)
CheckWinConditions();
MESSAGE_BEGIN(MSG_SPEC, SVC_DIRECTOR);
WRITE_BYTE(9); // command length in bytes
WRITE_BYTE(DRC_CMD_EVENT); // player killed
WRITE_SHORT(ENTINDEX(pVictim->edict())); // index number of primary entity
if (pevInflictor)
WRITE_SHORT(ENTINDEX(ENT(pevInflictor))); // index number of secondary entity
else
WRITE_SHORT(ENTINDEX(ENT(pKiller))); // index number of secondary entity
if (pVictim->m_bHeadshotKilled)
WRITE_LONG(9 | DRC_FLAG_DRAMATIC | DRC_FLAG_SLOWMOTION);
else
WRITE_LONG(7 | DRC_FLAG_DRAMATIC); // eventflags (priority and flags)
MESSAGE_END();
}
// PlayerGotWeapon - player has grabbed a weapon that was
// sitting in the world
void CHalfLifeMultiplay::__MAKE_VHOOK(PlayerGotWeapon)(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon)
{
;
}
// FlWeaponRespawnTime - what is the time in the future
// at which this weapon may spawn?
float CHalfLifeMultiplay::__MAKE_VHOOK(FlWeaponRespawnTime)(CBasePlayerItem *pWeapon)
{
return gpGlobals->time + WEAPON_RESPAWN_TIME;
}
// FlWeaponRespawnTime - Returns 0 if the weapon can respawn now,
// otherwise it returns the time at which it can try to spawn again.
float CHalfLifeMultiplay::__MAKE_VHOOK(FlWeaponTryRespawn)(CBasePlayerItem *pWeapon)
{
if (pWeapon && pWeapon->m_iId && (pWeapon->iFlags() & ITEM_FLAG_LIMITINWORLD))
{
if (NUMBER_OF_ENTITIES() < (gpGlobals->maxEntities - ENTITY_INTOLERANCE))
return 0;
// we're past the entity tolerance level, so delay the respawn
return FlWeaponRespawnTime(pWeapon);
}
return 0;
}
Vector CHalfLifeMultiplay::__MAKE_VHOOK(VecWeaponRespawnSpot)(CBasePlayerItem *pWeapon)
{
return pWeapon->pev->origin;
}
int CHalfLifeMultiplay::__MAKE_VHOOK(WeaponShouldRespawn)(CBasePlayerItem *pWeapon)
{
if (pWeapon->pev->spawnflags & SF_NORESPAWN)
{
return GR_WEAPON_RESPAWN_NO;
}
return GR_WEAPON_RESPAWN_YES;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(BOOL, CHalfLifeMultiplay, CSGameRules, CanHavePlayerItem, (CBasePlayer *pPlayer, CBasePlayerItem *pItem), pPlayer, pItem)
BOOL EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(CanHavePlayerItem)(CBasePlayer *pPlayer, CBasePlayerItem *pItem)
{
return CGameRules::CanHavePlayerItem(pPlayer, pItem);
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(CanHaveItem)(CBasePlayer *pPlayer, CItem *pItem)
{
return TRUE;
}
void CHalfLifeMultiplay::__MAKE_VHOOK(PlayerGotItem)(CBasePlayer *pPlayer, CItem *pItem)
{
;
}
int CHalfLifeMultiplay::__MAKE_VHOOK(ItemShouldRespawn)(CItem *pItem)
{
if (pItem->pev->spawnflags & SF_NORESPAWN)
{
return GR_ITEM_RESPAWN_NO;
}
return GR_ITEM_RESPAWN_YES;
}
float CHalfLifeMultiplay::__MAKE_VHOOK(FlItemRespawnTime)(CItem *pItem)
{
return gpGlobals->time + ITEM_RESPAWN_TIME;
}
Vector CHalfLifeMultiplay::__MAKE_VHOOK(VecItemRespawnSpot)(CItem *pItem)
{
return pItem->pev->origin;
}
void CHalfLifeMultiplay::__MAKE_VHOOK(PlayerGotAmmo)(CBasePlayer *pPlayer, char *szName, int iCount)
{
;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(IsAllowedToSpawn)(CBaseEntity *pEntity)
{
return TRUE;
}
int CHalfLifeMultiplay::__MAKE_VHOOK(AmmoShouldRespawn)(CBasePlayerAmmo *pAmmo)
{
if (pAmmo->pev->spawnflags & SF_NORESPAWN)
{
return GR_AMMO_RESPAWN_NO;
}
return GR_AMMO_RESPAWN_YES;
}
float CHalfLifeMultiplay::__MAKE_VHOOK(FlAmmoRespawnTime)(CBasePlayerAmmo *pAmmo)
{
return gpGlobals->time + 20.0f;
}
Vector CHalfLifeMultiplay::__MAKE_VHOOK(VecAmmoRespawnSpot)(CBasePlayerAmmo *pAmmo)
{
return pAmmo->pev->origin;
}
float CHalfLifeMultiplay::__MAKE_VHOOK(FlHealthChargerRechargeTime)()
{
return 60;
}
float CHalfLifeMultiplay::__MAKE_VHOOK(FlHEVChargerRechargeTime)()
{
return 30;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(int, CHalfLifeMultiplay, CSGameRules, DeadPlayerWeapons, (CBasePlayer *pPlayer), pPlayer)
int EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(DeadPlayerWeapons)(CBasePlayer *pPlayer)
{
return GR_PLR_DROP_GUN_ACTIVE;
}
int CHalfLifeMultiplay::__MAKE_VHOOK(DeadPlayerAmmo)(CBasePlayer *pPlayer)
{
return GR_PLR_DROP_AMMO_ACTIVE;
}
LINK_HOOK_CLASS_CUSTOM_CHAIN(edict_t *, CHalfLifeMultiplay, CSGameRules, GetPlayerSpawnSpot, (CBasePlayer *pPlayer), pPlayer)
edict_t *EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(GetPlayerSpawnSpot)(CBasePlayer *pPlayer)
{
// gat valid spawn point
edict_t *pentSpawnSpot = CGameRules::GetPlayerSpawnSpot(pPlayer);
if (IsMultiplayer())
{
if (pentSpawnSpot->v.target)
{
FireTargets(STRING(pentSpawnSpot->v.target), pPlayer, pPlayer, USE_TOGGLE, 0);
}
}
return pentSpawnSpot;
}
int CHalfLifeMultiplay::__MAKE_VHOOK(PlayerRelationship)(CBasePlayer *pPlayer, CBaseEntity *pTarget)
{
#ifdef REGAMEDLL_ADD
if (IsFreeForAll())
{
return GR_NOTTEAMMATE;
}
#endif
if (!pPlayer || !pTarget)
{
return GR_NOTTEAMMATE;
}
if (!pTarget->IsPlayer())
{
return GR_NOTTEAMMATE;
}
CBasePlayer *player = GetClassPtr<CCSPlayer>((CBasePlayer *)pPlayer->pev);
CBasePlayer *target = GetClassPtr<CCSPlayer>((CBasePlayer *)pTarget->pev);
if (player->m_iTeam != target->m_iTeam)
{
return GR_NOTTEAMMATE;
}
return GR_TEAMMATE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(FAllowFlashlight)()
{
static cvar_t *mp_flashlight = NULL;
if (!mp_flashlight)
mp_flashlight = CVAR_GET_POINTER("mp_flashlight");
if (mp_flashlight)
return mp_flashlight->value != 0;
return FALSE;
}
BOOL CHalfLifeMultiplay::__MAKE_VHOOK(FAllowMonsters)()
{
#ifdef REGAMEDLL_FIXES
return FALSE;
#else
return allowmonsters.value != 0.0f;
#endif
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, GoToIntermission)
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(GoToIntermission)()
{
if (m_bGameOver)
return;
UTIL_LogPrintf("Team \"CT\" scored \"%i\" with \"%i\" players\n", m_iNumCTWins, m_iNumCT);
UTIL_LogPrintf("Team \"TERRORIST\" scored \"%i\" with \"%i\" players\n", m_iNumTerroristWins, m_iNumTerrorist);
if (IsCareer())
{
MESSAGE_BEGIN(MSG_ALL, gmsgCZCareer);
WRITE_STRING("MATCH");
WRITE_LONG(m_iNumCTWins);
WRITE_LONG(m_iNumTerroristWins);
MESSAGE_END();
MESSAGE_BEGIN(MSG_ALL, gmsgCZCareerHUD);
WRITE_STRING("MATCH");
WRITE_LONG(m_iNumCTWins);
WRITE_LONG(m_iNumTerroristWins);
WRITE_BYTE(m_iCareerMatchWins);
WRITE_BYTE(m_iRoundWinDifference);
WRITE_BYTE(m_iRoundWinStatus);
MESSAGE_END();
if (TheCareerTasks)
{
UTIL_LogPrintf("Career Match %d %d %d %d\n", m_iRoundWinStatus, m_iNumCTWins, m_iNumTerroristWins, TheCareerTasks->AreAllTasksComplete());
}
}
MESSAGE_BEGIN(MSG_ALL, SVC_INTERMISSION);
MESSAGE_END();
if (IsCareer())
{
SERVER_COMMAND("setpause\n");
}
int time = int(CVAR_GET_FLOAT("mp_chattime"));
if (time < 1)
CVAR_SET_STRING("mp_chattime", "1");
else if (time > MAX_INTERMISSION_TIME)
CVAR_SET_STRING("mp_chattime", UTIL_dtos1(MAX_INTERMISSION_TIME));
m_flIntermissionEndTime = gpGlobals->time + int(mp_chattime.value);
m_flIntermissionStartTime = gpGlobals->time;
m_bGameOver = true;
m_iEndIntermissionButtonHit = FALSE;
m_iSpawnPointCount_Terrorist = 0;
m_iSpawnPointCount_CT = 0;
m_bLevelInitialized = false;
}
// Clean up memory used by mapcycle when switching it
void DestroyMapCycle(mapcycle_t *cycle)
{
mapcycle_item_t *p, *n, *start;
p = cycle->items;
if (p)
{
start = p;
p = p->next;
while (p != start)
{
n = p->next;
delete p;
p = n;
}
delete cycle->items;
}
cycle->items = NULL;
cycle->next_item = NULL;
}
char *MP_COM_GetToken()
{
return mp_com_token;
}
char *MP_COM_Parse(char *data)
{
int c;
int len;
len = 0;
mp_com_token[0] = '\0';
if (!data)
{
return NULL;
}
skipwhite:
// skip whitespace
while (*data <= ' ')
{
if (!data[0])
return NULL;
++data;
}
c = *data;
// skip // comments till the next line
if (c == '/' && data[1] == '/')
{
while (*data && *data != '\n')
++data;
goto skipwhite; // start over new line
}
// handle quoted strings specially: copy till the end or another quote
if (c == '\"')
{
++data; // skip starting quote
while (true)
{
// get char and advance
c = *data++;
if (c == '\"' || !c)
{
mp_com_token[ len ] = '\0';
return data;
}
mp_com_token[ len++ ] = c;
}
}
// parse single characters
if (c == '{' || c == '}'|| c == ')'|| c == '(' || c == '\'' || c == ',')
{
mp_com_token[ len++ ] = c;
mp_com_token[ len ] = '\0';
return data + 1;
}
// parse a regular word
do
{
mp_com_token[ len++ ] = c;
++data;
c = *data;
if (c == '{' || c == '}'|| c == ')'|| c == '(' || c == '\'' || c == ',')
break;
}
while (c > 32);
mp_com_token[ len ] = '\0';
return data;
}
int MP_COM_TokenWaiting(char *buffer)
{
char *p;
p = buffer;
while (*p && *p != '\n')
{
if (!Q_isspace(*p) || Q_isalnum(*p))
return 1;
++p;
}
return 0;
}
int ReloadMapCycleFile(char *filename, mapcycle_t *cycle)
{
char szBuffer[ MAX_RULE_BUFFER ];
char szMap[ 32 ];
int length;
char *pFileList;
char *aFileList = pFileList = (char *)LOAD_FILE_FOR_ME(filename, &length);
int hasbuffer;
mapcycle_item_s *item, *newlist = NULL, *next;
if (pFileList && length)
{
// the first map name in the file becomes the default
while (true)
{
hasbuffer = 0;
Q_memset(szBuffer, 0, sizeof(szBuffer));
pFileList = MP_COM_Parse(pFileList);
if (Q_strlen(mp_com_token) <= 0)
break;
Q_strcpy(szMap, mp_com_token);
// Any more tokens on this line?
if (MP_COM_TokenWaiting(pFileList))
{
pFileList = MP_COM_Parse(pFileList);
if (Q_strlen(mp_com_token) > 0)
{
hasbuffer = 1;
Q_strcpy(szBuffer, mp_com_token);
}
}
// Check map
if (IS_MAP_VALID(szMap))
{
// Create entry
char *s;
item = new mapcycle_item_s;
Q_strcpy(item->mapname, szMap);
item->minplayers = 0;
item->maxplayers = 0;
Q_memset(item->rulebuffer, 0, sizeof(item->rulebuffer));
if (hasbuffer)
{
s = GET_KEY_VALUE(szBuffer, "minplayers");
if (s && s[0] != '\0')
{
item->minplayers = Q_atoi(s);
item->minplayers = Q_max(item->minplayers, 0);
item->minplayers = Q_min(item->minplayers, gpGlobals->maxClients);
}
s = GET_KEY_VALUE(szBuffer, "maxplayers");
if (s && s[0] != '\0')
{
item->maxplayers = Q_atoi(s);
item->maxplayers = Q_max(item->maxplayers, 0);
item->maxplayers = Q_min(item->maxplayers, gpGlobals->maxClients);
}
// Remove keys
REMOVE_KEY_VALUE(szBuffer, "minplayers");
REMOVE_KEY_VALUE(szBuffer, "maxplayers");
Q_strcpy(item->rulebuffer, szBuffer);
}
item->next = cycle->items;
cycle->items = item;
}
else
ALERT(at_console, "Skipping %s from mapcycle, not a valid map\n", szMap);
}
FREE_FILE(aFileList);
}
// Fixup circular list pointer
item = cycle->items;
// Reverse it to get original order
while (item)
{
next = item->next;
item->next = newlist;
newlist = item;
item = next;
}
cycle->items = newlist;
item = cycle->items;
// Didn't parse anything
if (!item)
{
return 0;
}
while (item->next)
{
item = item->next;
}
item->next = cycle->items;
cycle->next_item = item->next;
return 1;
}
// Determine the current # of active players on the server for map cycling logic
int CountPlayers()
{
int nCount = 0;
for (int i = 1; i <= gpGlobals->maxClients; ++i)
{
CBasePlayer *pPlayer = UTIL_PlayerByIndex(i);
if (pPlayer)
{
nCount++;
}
}
return nCount;
}
// Parse commands/key value pairs to issue right after map xxx command is issued on server level transition
void ExtractCommandString(char *s, char *szCommand)
{
// Now make rules happen
char pkey[512];
char value[512]; // use two buffers so compares
// work without stomping on each other
char *o;
if (*s == '\\')
++s;
while (true)
{
o = pkey;
while (*s != '\\')
{
if (!*s)
{
return;
}
*o++ = *s++;
}
*o = '\0';
++s;
o = value;
while (*s != '\\' && *s)
{
if (!*s)
{
return;
}
*o++ = *s++;
}
*o = '\0';
Q_strcat(szCommand, pkey);
if (Q_strlen(value) > 0)
{
Q_strcat(szCommand, " ");
Q_strcat(szCommand, value);
}
Q_strcat(szCommand, "\n");
if (!*s)
{
return;
}
++s;
}
}
void CHalfLifeMultiplay::ResetAllMapVotes()
{
CBaseEntity *pTempEntity = NULL;
while ((pTempEntity = UTIL_FindEntityByClassname(pTempEntity, "player")))
{
if (FNullEnt(pTempEntity->edict()))
break;
CBasePlayer *pTempPlayer = GetClassPtr<CCSPlayer>((CBasePlayer *)pTempEntity->pev);
if (pTempPlayer->m_iTeam != UNASSIGNED)
{
pTempPlayer->m_iMapVote = 0;
}
}
for (int j = 0; j < MAX_VOTE_MAPS; ++j)
m_iMapVotes[j] = 0;
}
int GetMapCount()
{
static mapcycle_t mapcycle;
char *mapcfile = (char *)CVAR_GET_STRING("mapcyclefile");
DestroyMapCycle(&mapcycle);
ReloadMapCycleFile(mapcfile, &mapcycle);
int nCount = 0;
auto item = mapcycle.next_item;
do
{
if (!item)
break;
++nCount;
item = item->next;
} while (item != mapcycle.next_item);
return nCount;
}
void CHalfLifeMultiplay::DisplayMaps(CBasePlayer *player, int iVote)
{
static mapcycle_t mapcycle2;
char *mapcfile = (char *)CVAR_GET_STRING("mapcyclefile");
char *pszNewMap = NULL;
int iCount = 0, done = 0;
DestroyMapCycle(&mapcycle2);
ReloadMapCycleFile(mapcfile, &mapcycle2);
mapcycle_item_s *item = mapcycle2.next_item;
while (!done && item)
{
if (item->next == mapcycle2.next_item)
done = 1;
++iCount;
if (player)
{
if (m_iMapVotes[iCount] == 1)
{
ClientPrint(player->pev, HUD_PRINTCONSOLE, "#Vote", UTIL_dtos1(iCount), item->mapname, UTIL_dtos2(1));
}
else
ClientPrint(player->pev, HUD_PRINTCONSOLE, "#Votes", UTIL_dtos1(iCount), item->mapname, UTIL_dtos2(m_iMapVotes[iCount]));
}
if (iCount == iVote)
{
pszNewMap = item->mapname;
}
item = item->next;
}
if (!pszNewMap || !iVote)
{
return;
}
if (Q_strcmp(pszNewMap, STRING(gpGlobals->mapname)) != 0)
{
CHANGE_LEVEL(pszNewMap, NULL);
return;
}
if (timelimit.value)
{
timelimit.value += 30;
UTIL_ClientPrintAll(HUD_PRINTCENTER, "#Map_Vote_Extend");
}
ResetAllMapVotes();
}
void CHalfLifeMultiplay::ProcessMapVote(CBasePlayer *player, int iVote)
{
CBaseEntity *pTempEntity = NULL;
int iValidVotes = 0, iNumPlayers = 0;
while ((pTempEntity = UTIL_FindEntityByClassname(pTempEntity, "player")))
{
if (FNullEnt(pTempEntity->edict()))
break;
CBasePlayer *pTempPlayer = GetClassPtr<CCSPlayer>((CBasePlayer *)pTempEntity->pev);
if (pTempPlayer->m_iTeam != UNASSIGNED)
{
++iNumPlayers;
if (pTempPlayer->m_iMapVote == iVote)
++iValidVotes;
}
}
m_iMapVotes[iVote] = iValidVotes;
float ratio = mapvoteratio.value;
if (mapvoteratio.value > 1)
{
ratio = 1;
CVAR_SET_STRING("mp_mapvoteratio", "1.0");
}
else if (mapvoteratio.value < 0.35f)
{
ratio = 0.35f;
CVAR_SET_STRING("mp_mapvoteratio", "0.35");
}
int iRequiredVotes = 2;
if (iNumPlayers > 2)
{
iRequiredVotes = int(iNumPlayers * ratio + 0.5f);
}
if (iValidVotes < iRequiredVotes)
{
DisplayMaps(player, 0);
ClientPrint(player->pev, HUD_PRINTCONSOLE, "#Game_required_votes", UTIL_dtos1(iRequiredVotes));
}
else
DisplayMaps(NULL, iVote);
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN2(CHalfLifeMultiplay, CSGameRules, ChangeLevel);
// Server is changing to a new level, check mapcycle.txt for map name and setup info
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(ChangeLevel)()
{
static char szPreviousMapCycleFile[256];
static mapcycle_t mapcycle;
char szNextMap[32];
char szFirstMapInList[32];
char szCommands[1500];
char szRules[1500];
int minplayers = 0, maxplayers = 0;
#ifdef REGAMEDLL_FIXES
// the absolute default level is de_dust
Q_strcpy(szFirstMapInList, "de_dust");
#else
// the absolute default level is hldm1
Q_strcpy(szFirstMapInList, "hldm1");
#endif
int curplayers;
bool do_cycle = true;
// find the map to change to
char *mapcfile = (char *)CVAR_GET_STRING("mapcyclefile");
assert(mapcfile != NULL);
szCommands[0] = '\0';
szRules[0] = '\0';
curplayers = CountPlayers();
// Has the map cycle filename changed?
if (Q_stricmp(mapcfile, szPreviousMapCycleFile) != 0)
{
Q_strcpy(szPreviousMapCycleFile, mapcfile);
DestroyMapCycle(&mapcycle);
if (!ReloadMapCycleFile(mapcfile, &mapcycle) || !mapcycle.items)
{
ALERT(at_console, "Unable to load map cycle file %s\n", mapcfile);
do_cycle = false;
}
}
if (do_cycle && mapcycle.items)
{
bool keeplooking = false;
bool found = false;
mapcycle_item_s *item;
// Assume current map
Q_strcpy(szNextMap, STRING(gpGlobals->mapname));
Q_strcpy(szFirstMapInList, STRING(gpGlobals->mapname));
// Traverse list
for (item = mapcycle.next_item; item->next != mapcycle.next_item; item = item->next)
{
keeplooking = false;
assert(item != NULL);
if (item->minplayers != 0)
{
if (curplayers >= item->minplayers)
{
found = true;
minplayers = item->minplayers;
}
else
{
keeplooking = true;
}
}
if (item->maxplayers != 0)
{
if (curplayers <= item->maxplayers)
{
found = true;
maxplayers = item->maxplayers;
}
else
{
keeplooking = true;
}
}
if (keeplooking)
{
continue;
}
found = true;
break;
}
if (!found)
{
item = mapcycle.next_item;
}
// Increment next item pointer
mapcycle.next_item = item->next;
// Perform logic on current item
Q_strcpy(szNextMap, item->mapname);
ExtractCommandString(item->rulebuffer, szCommands);
Q_strcpy(szRules, item->rulebuffer);
}
if (!IS_MAP_VALID(szNextMap))
{
Q_strcpy(szNextMap, szFirstMapInList);
}
m_bGameOver = true;
ALERT(at_console, "CHANGE LEVEL: %s\n", szNextMap);
if (minplayers || maxplayers)
{
ALERT(at_console, "PLAYER COUNT: min %i max %i current %i\n", minplayers, maxplayers, curplayers);
}
if (Q_strlen(szRules) > 0)
{
ALERT(at_console, "RULES: %s\n", szRules);
}
CHANGE_LEVEL(szNextMap, NULL);
if (Q_strlen(szCommands) > 0)
{
SERVER_COMMAND(szCommands);
}
}
void CHalfLifeMultiplay::SendMOTDToClient(edict_t *client)
{
// read from the MOTD.txt file
int length, char_count = 0;
char *pFileList;
char *aFileList = pFileList = (char *)LOAD_FILE_FOR_ME((char *)CVAR_GET_STRING("motdfile"), &length);
// send the server name
MESSAGE_BEGIN(MSG_ONE, gmsgServerName, NULL, client);
WRITE_STRING(CVAR_GET_STRING("hostname"));
MESSAGE_END();
// Send the message of the day
// read it chunk-by-chunk, and send it in parts
while (pFileList && *pFileList && char_count < MAX_MOTD_LENGTH)
{
char chunk[MAX_MOTD_CHUNK + 1];
if (Q_strlen(pFileList) < sizeof(chunk))
{
Q_strcpy(chunk, pFileList);
}
else
{
Q_strncpy(chunk, pFileList, sizeof(chunk) - 1);
// Q_strncpy doesn't always append the null terminator
chunk[sizeof(chunk) - 1] = '\0';
}
char_count += Q_strlen(chunk);
if (char_count < MAX_MOTD_LENGTH)
pFileList = aFileList + char_count;
else
*pFileList = '\0';
MESSAGE_BEGIN(MSG_ONE, gmsgMOTD, NULL, client);
WRITE_BYTE((*pFileList != '\0') ? FALSE : TRUE); // FALSE means there is still more message to come
WRITE_STRING(chunk);
MESSAGE_END();
}
FREE_FILE(aFileList);
}
LINK_HOOK_CLASS_VOID_CUSTOM_CHAIN(CHalfLifeMultiplay, CSGameRules, ClientUserInfoChanged, (CBasePlayer *pPlayer, char *infobuffer), pPlayer, infobuffer);
void EXT_FUNC CHalfLifeMultiplay::__API_VHOOK(ClientUserInfoChanged)(CBasePlayer *pPlayer, char *infobuffer)
{
pPlayer->SetPlayerModel(pPlayer->m_bHasC4);
pPlayer->SetPrefsFromUserinfo(infobuffer);
}
void CHalfLifeMultiplay::ServerActivate()
{
// Check to see if there's a mapping info paramater entity
if (g_pMapInfo)
g_pMapInfo->CheckMapInfo();
ReadMultiplayCvars();
CheckMapConditions();
}
TeamName CHalfLifeMultiplay::SelectDefaultTeam()
{
TeamName team = UNASSIGNED;
if (m_iNumTerrorist < m_iNumCT)
{
team = TERRORIST;
}
else if (m_iNumTerrorist > m_iNumCT)
{
team = CT;
}
// Choose the team that's losing
else if (m_iNumTerroristWins < m_iNumCTWins)
{
team = TERRORIST;
}
else if (m_iNumCTWins < m_iNumTerroristWins)
{
team = CT;
}
else
{
// Teams and scores are equal, pick a random team
team = (RANDOM_LONG(0, 1) == 0) ? CT : TERRORIST;
}
if (TeamFull(team))
{
// Pick the opposite team
team = (team == TERRORIST) ? CT : TERRORIST;
// No choices left
if (TeamFull(team))
{
return UNASSIGNED;
}
}
return team;
}
| gpl-3.0 |
FH-Complete/FHC-Core | vilesci/cronjobs/matrikelnummern.php | 3846 | <?php
/* Copyright (C) 2018 fhcomplete.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 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* Authors: Andreas Oesterreicher < andreas.oesterreicher@technikum-wien.at >
*/
/**
* Erfragt die Matrikelnummern von Personen beim Datenverbund
* Wenn keine bestehende Matrikelnummer gefunden wird, wird eine neue Matrikelnummer angefordert
*/
require_once(dirname(__FILE__).'/../../config/vilesci.config.inc.php');
require_once(dirname(__FILE__).'/../../include/basis_db.class.php');
require_once(dirname(__FILE__).'/../../include/dvb.class.php');
require_once(dirname(__FILE__).'/../../include/benutzerberechtigung.class.php');
require_once(dirname(__FILE__).'/../../include/datum.class.php');
require_once(dirname(__FILE__).'/../../include/errorhandler.class.php');
if (!$db = new basis_db())
die('Es konnte keine Verbindung zum Server aufgebaut werden.');
$limit = '';
$debug = false;
$softrun = false;
// Wenn das Script nicht ueber Commandline gestartet wird, muss eine
// Authentifizierung stattfinden
if (php_sapi_name() != 'cli')
{
$nl = '<br>';
// Benutzerdefinierte Variablen laden
$user = get_uid();
loadVariables($user);
// Berechtigungen pruefen
$rechte = new benutzerberechtigung();
$rechte->getBerechtigungen($user);
if (!$rechte->isBerechtigt('admin', null, 'suid'))
die('Sie haben keine Berechtigung für diese Seite');
if (isset($_GET['debug']))
$debug = ($_GET['debug'] == 'true'?true:false);
if (isset($_GET['limit']) && is_numeric($_GET['limit']))
$limit = $_GET['limit'];
if (isset($_GET['softrun']))
$debug = ($_GET['softrun'] == 'true'?true:false);
}
else
{
$nl = "\n";
// Commandline Paramter parsen bei Aufruf ueber Cronjob
// zb php matrikelnummer.php --limit 100 --debug true
$longopt = array(
"limit:",
"debug:",
"softrun:"
);
$commandlineparams = getopt('', $longopt);
if (isset($commandlineparams['limit']) && is_numeric($commandlineparams['limit']))
$limit = $commandlineparams['limit'];
if (isset($commandlineparams['debug']))
$debug = ($commandlineparams['debug'] == 'true'?true:false);
if (isset($commandlineparams['softrun']))
$softrun = ($commandlineparams['softrun'] == 'true'?true:false);
}
$matrikelnummer_added = 0;
$webservice = new dvb(DVB_USERNAME, DVB_PASSWORD, $debug);
$qry = "
SELECT
distinct person_id, vorname, nachname
FROM
public.tbl_person
JOIN public.tbl_benutzer USING(person_id)
JOIN public.tbl_student ON(tbl_student.student_uid=tbl_benutzer.uid)
WHERE
public.tbl_benutzer.aktiv = true
AND tbl_person.matr_nr is null
AND studiengang_kz<10000
AND EXISTS(SELECT 1 FROM public.tbl_prestudent WHERE person_id=tbl_person.person_id AND bismelden=true)
AND (svnr is not null OR ersatzkennzeichen is not null)";
if ($limit != '')
$qry .= " LIMIT ".$limit;
$db = new basis_db();
if ($result = $db->db_query($qry))
{
while ($row = $db->db_fetch_object($result))
{
echo $nl."Pruefe $row->person_id $row->vorname $row->nachname";
$data = $webservice->assignMatrikelnummer($row->person_id, $softrun);
if (ErrorHandler::isSuccess($data))
echo ' OK';
else
echo ' Failed:'.$webservice->errormsg;
}
}
if($debug)
echo $webservice->debug_output;
| gpl-3.0 |
sg-s/xolotl | c++/conductances/liu-temperature/CaT.hpp | 2328 | // _ _ ____ _ ____ ___ _
// \/ | | | | | | |
// _/\_ |__| |___ |__| | |___
//
// Fast Calcium CONDUCTANCE
// http://www.jneurosci.org/content/jneuro/18/7/2309.full.pdf
#pragma once
//inherit conductance class spec
class CaT: public conductance {
private:
double delta_temp = 0;
double pow_Q_tau_m_delta_temp = 1;
double pow_Q_tau_h_delta_temp = 1;
double pow_Q_g = 1;
public:
double Q_g;
double Q_tau_m;
double Q_tau_h;
// specify parameters + initial conditions
CaT(double gbar_, double E_, double m_, double h_, double Q_g_, double Q_tau_m_, double Q_tau_h_)
{
gbar = gbar_;
E = E_;
m = m_;
h = h_;
Q_g = Q_g_;
Q_tau_m = Q_tau_m_;
Q_tau_h = Q_tau_h_;
// defaults
if (isnan(gbar)) { gbar = 0; }
if (isnan (Q_g)) { Q_g = 1; }
if (isnan (Q_tau_m)) { Q_tau_m = 2; }
if (isnan (Q_tau_h)) { Q_tau_h = 2; }
if (isnan (E)) { E = 30; }
is_calcium = true;
name = "CaT";
p = 3;
q = 1;
}
void integrate(double, double);
void integrateLangevin(double, double);
void connect(compartment*);
double m_inf(double, double);
double h_inf(double, double);
double tau_m(double, double);
double tau_h(double, double);
};
void CaT::connect(compartment *pcomp_) {
// call super class method
conductance::connect(pcomp_);
// also set up some useful things
delta_temp = (temperature - temperature_ref)/10;
pow_Q_tau_m_delta_temp = 1/(pow(Q_tau_m, delta_temp));
pow_Q_tau_h_delta_temp = 1/(pow(Q_tau_h, delta_temp));
pow_Q_g = pow(Q_g, delta_temp);
}
void CaT::integrate(double V, double Ca) {
conductance::integrate(V,Ca);
g = pow_Q_g*g;
}
void CaT::integrateLangevin(double V, double Ca) {
conductance::integrateLangevin(V,Ca);
g = pow_Q_g*g;
}
double CaT::m_inf(double V, double Ca) {return 1.0/(1.0 + exp((V+27.1)/-7.2));}
double CaT::h_inf(double V, double Ca) {return 1.0/(1.0 + exp((V+32.1)/5.5));}
double CaT::tau_m(double V, double Ca) {return pow_Q_tau_m_delta_temp*(21.7 - 21.3/(1.0 + exp((V+68.1)/-20.5)));}
double CaT::tau_h(double V, double Ca) {return pow_Q_tau_h_delta_temp*(105.0 - 89.8/(1.0 + exp((V+55.0)/-16.9)));}
| gpl-3.0 |
PuzzlesLab/UVA | King/00417 Word Index.java | 847 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
class Main {
public static void main (String [] abc) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
HashMap<String,Integer> map=new HashMap<>();
int idCount=1;
LinkedList<String> stk=new LinkedList<>();
stk.add("");
//bfs
while (!stk.isEmpty() && idCount<=83681) {
String str=stk.removeFirst();
if (str.length()>0) map.put(str,idCount++);
if (str.length()<5) {
int start='a';
if (str.length()>0) start=str.charAt(str.length()-1)+1;
for (;start<='z';start++) stk.addLast(str+((char)(start)+""));
}
}
while ((s=br.readLine())!=null) {
System.out.println(map.getOrDefault(s,0));
}
}
} | gpl-3.0 |
vibhorsingh-netcore/HSMART_SERVERS | src/main/java/com/netcore/hsmart/InsecureHostnameVerifier.java | 491 | /*
* 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.netcore.hsmart;
/**
*
* @author root
*/
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class InsecureHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
| gpl-3.0 |
CeON/saos | saos-webapp/src/main/java/pl/edu/icm/saos/webapp/judgment/search/PagingConverter.java | 752 | package pl.edu.icm.saos.webapp.judgment.search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import pl.edu.icm.saos.search.search.model.Paging;
import pl.edu.icm.saos.search.search.model.Sorting;
/**
* @author Łukasz Pawełczak
*
*/
@Service
public class PagingConverter {
@Autowired
private SortingConverter sortingConverter;
//------------------------ LOGIC --------------------------
public Paging convert(Pageable pageable) {
Sorting sorting = sortingConverter.convert(pageable.getSort());
Paging paging = new Paging(pageable.getPageNumber(), pageable.getPageSize(), sorting);
return paging;
}
}
| gpl-3.0 |
Ircam-RnD/xmm | src/models/kmeans/xmmKMeansParameters.hpp | 3256 | /*
* xmmKMeansParameters.hpp
*
* Parameters of the K-Means clustering Algorithm
*
* Contact:
* - Jules Francoise <jules.francoise@ircam.fr>
*
* This code has been initially authored by Jules Francoise
* <http://julesfrancoise.com> during his PhD thesis, supervised by Frederic
* Bevilacqua <href="http://frederic-bevilacqua.net>, in the Sound Music
* Movement Interaction team <http://ismm.ircam.fr> of the
* STMS Lab - IRCAM, CNRS, UPMC (2011-2015).
*
* Copyright (C) 2015 UPMC, Ircam-Centre Pompidou.
*
* This File is part of XMM.
*
* XMM 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.
*
* XMM 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 XMM. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef xmmKMeansParameters_hpp
#define xmmKMeansParameters_hpp
#include "../../core/model/xmmModelParameters.hpp"
namespace xmm {
/**
@defgroup KMeans [Models] K-Means Algorithm
*/
/**
Dummy structure for template specialization
*/
class KMeans;
/**
@ingroup KMeans
@brief Parameters specific to each class of a K-Means Algorithm
*/
template <>
class ClassParameters<KMeans> : public Writable {
public:
/**
@brief Default Constructor
*/
ClassParameters();
/**
@brief Copy Constructor
@param src Source Object
*/
ClassParameters(ClassParameters<KMeans> const& src);
/**
@brief Constructor from Json Structure
@param root Json Value
*/
explicit ClassParameters(Json::Value const& root);
/**
@brief Assignment
@param src Source Object
*/
ClassParameters& operator=(ClassParameters<KMeans> const& src);
virtual ~ClassParameters() {}
/** @name Json I/O */
///@{
/**
@brief Write the object to a JSON Structure
@return Json value containing the object's information
*/
Json::Value toJson() const;
/**
@brief Read the object from a JSON Structure
@param root JSON value containing the object's information
@throws JsonException if the JSON value has a wrong format
*/
virtual void fromJson(Json::Value const& root);
///@}
/**
@brief specifies if parameters have changed (model is invalid)
*/
bool changed = false;
/**
@brief Number of Gaussian Mixture Components
*/
Attribute<unsigned int> clusters;
/**
@brief Maximum number of iterations of the training update
*/
Attribute<unsigned int> max_iterations;
/**
@brief threshold (as relative distance between cluster) required to define
convergence
*/
Attribute<float> relative_distance_threshold;
protected:
/**
@brief notification function called when a member attribute is changed
*/
virtual void onAttributeChange(AttributeBase* attr_pointer);
};
}
#endif
| gpl-3.0 |
greudysgodoy/oansa | app/Providers/AuthServiceProvider.php | 700 | <?php
namespace Oansa\Providers;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'Oansa\Model' => 'Oansa\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
//
}
}
| gpl-3.0 |
plutext/OpenDoPE-Model | OpenDoPEModel/IdGenerator.cs | 3429 | /*
* OpenDoPE authoring Word AddIn
Copyright (C) Plutext Pty Ltd, 2012
*
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/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OpenDoPEModel
{
/// <summary>
/// NOT USED ANYMORE,
/// since:
/// 1. need to keep the ID short, given max Tag length
/// 2. want it to be unique across documents, for easy re-use
/// So see instead IdHelper.
/// </summary>
public class IdGenerator
{
public static string dropNonAlpha(string incoming) {
StringBuilder sb = new StringBuilder();
char[] chars = incoming.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (char.IsLetter(c))
{
// Not letters and numbers .. consider count(foo)>1
sb.Append(c);
}
else
{
sb.Append(" ");
}
}
String result = sb.ToString();
return result.Trim();
}
/// <summary>
/// Generate an ID which is unique (not in the dictionary supplied).
/// </summary>
/// <param name="xpathsPart"></param>
/// <param name="partPrefix">if the user has several custom xml parts, pass some prefix so the names can distinguish </param>
/// <param name="strXPath"></param>
/// <returns></returns>
public static string generateIdForXPath(Dictionary<string, string> xpathsById,
string partPrefix, string typeSuffix, string strXPath)
{
string name = dropNonAlpha(strXPath);
// get last segment of XPath
int pos = name.LastIndexOf(" ");
if (pos > 0)
{
name = name.Substring(pos + 1);
}
if (partPrefix != null && !partPrefix.Equals(""))
name = partPrefix + "_" + name;
if (typeSuffix != null && !typeSuffix.Equals(""))
name = name + "_" + typeSuffix;
if (!idExists(name, xpathsById))
{
return name;
}
// Now just increment a number until it is unique
int i = 1;
do
{
i++;
} while (idExists(name + i, xpathsById));
return name + i;
}
private static bool idExists(string id, Dictionary<string, string> xpathsById)
{
try
{
string foo = xpathsById[id];
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
}
}
| gpl-3.0 |
nexdatas/recselector | test/TestServerSetUp.py | 11185 | #!/usr/bin/env python
# This file is part of nexdatas - Tango Server for NeXus data writer
#
# Copyright (C) 2012-2014 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
# nexdatas 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.
#
# nexdatas 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 nexdatas. If not, see <http://www.gnu.org/licenses/>.
# \package test nexdatas
# \file ServerSetUp.py
# class with server settings
#
import os
import sys
import subprocess
import PyTango
import time
try:
import TestServer
except Exception:
from . import TestServer
# test fixture
class TestServerSetUp(object):
# constructor
# \brief defines server parameters
def __init__(self, device="ttestp09/testts/t1r228", instance="S1"):
# information about tango writer
self.new_device_info_writer = PyTango.DbDevInfo()
# information about tango writer class
self.new_device_info_writer._class = "TestServer"
# information about tango writer server
self.new_device_info_writer.server = "TestServer/%s" % instance
# information about tango writer name
self.new_device_info_writer.name = device
# server instance
self.instance = instance
self._psub = None
# device proxy
self.dp = None
# device properties
self.device_prop = {
'DeviceBoolean': False,
'DeviceShort': 12,
'DeviceLong': 1234566,
'DeviceFloat': 12.4345,
'DeviceDouble': 3.453456,
'DeviceUShort': 1,
'DeviceULong': 23234,
'DeviceString': "My Sting"
}
# class properties
self.class_prop = {
'ClassBoolean': True,
'ClassShort': 1,
'ClassLong': -123555,
'ClassFloat': 12.345,
'ClassDouble': 1.23445,
'ClassUShort': 1,
'ClassULong': 12343,
'ClassString': "My ClassString",
}
# test starter
# \brief Common set up of Tango Server
def setUp(self):
print("\nsetting up...")
self.add()
self.start()
def add(self):
db = PyTango.Database()
db.add_device(self.new_device_info_writer)
db.add_server(self.new_device_info_writer.server,
self.new_device_info_writer)
db.put_device_property(self.new_device_info_writer.name,
self.device_prop)
db.put_class_property(self.new_device_info_writer._class,
self.class_prop)
# starts server
def start(self):
db = PyTango.Database()
path = os.path.dirname(TestServer.__file__)
if not path:
path = '.'
if sys.version_info > (3,):
self._psub = subprocess.call(
"cd %s; python3 ./TestServer.py %s &" %
(path, self.instance), stdout=None,
stderr=None, shell=True)
else:
self._psub = subprocess.call(
"cd %s; python ./TestServer.py %s &" %
(path, self.instance), stdout=None,
stderr=None, shell=True)
sys.stdout.write("waiting for simple server")
found = False
cnt = 0
dvname = self.new_device_info_writer.name
while not found and cnt < 1000:
try:
sys.stdout.write(".")
sys.stdout.flush()
exl = db.get_device_exported(dvname)
if dvname not in exl.value_string:
time.sleep(0.01)
cnt += 1
continue
self.dp = PyTango.DeviceProxy(dvname)
time.sleep(0.01)
if self.dp.state() == PyTango.DevState.ON:
found = True
except Exception:
found = False
cnt += 1
print("")
# test closer
# \brief Common tear down of Tango Server
def tearDown(self):
print("tearing down ...")
self.delete()
self.stop()
def delete(self):
db = PyTango.Database()
db.delete_server(self.new_device_info_writer.server)
# stops server
def stop(self):
if sys.version_info > (3,):
with subprocess.Popen(
"ps -ef | grep 'TestServer.py %s' | grep -v grep" %
self.instance,
stdout=subprocess.PIPE, shell=True) as proc:
pipe = proc.stdout
res = str(pipe.read(), "utf8").split("\n")
for r in res:
sr = r.split()
if len(sr) > 2:
subprocess.call(
"kill -9 %s" % sr[1], stderr=subprocess.PIPE,
shell=True)
pipe.close()
else:
pipe = subprocess.Popen(
"ps -ef | grep 'TestServer.py %s' | grep -v grep" %
self.instance,
stdout=subprocess.PIPE, shell=True).stdout
res = str(pipe.read()).split("\n")
for r in res:
sr = r.split()
if len(sr) > 2:
subprocess.call(
"kill -9 %s" % sr[1], stderr=subprocess.PIPE,
shell=True)
pipe.close()
# test fixture
class MultiTestServerSetUp(object):
# constructor
# \brief defines server parameters
def __init__(self, instance="MTS01", devices=None):
if not isinstance(devices, list):
devices = ["ttestp09/testts/mt1r228"]
# information about tango writer
self.server = "TestServer/%s" % instance
self.ts = {}
# device proxy
self.dps = {}
for dv in devices:
self.ts[dv] = PyTango.DbDevInfo()
self.ts[dv]._class = "TestServer"
self.ts[dv].server = self.server
self.ts[dv].name = dv
# server instance
self.instance = instance
self._psub = None
# device properties
self.device_prop = {
'DeviceBoolean': False,
'DeviceShort': 12,
'DeviceLong': 1234566,
'DeviceFloat': 12.4345,
'DeviceDouble': 3.453456,
'DeviceUShort': 1,
'DeviceULong': 23234,
'DeviceString': "My Sting"
}
# class properties
self.class_prop = {
'ClassBoolean': True,
'ClassShort': 1,
'ClassLong': -123555,
'ClassFloat': 12.345,
'ClassDouble': 1.23445,
'ClassUShort': 1,
'ClassULong': 12343,
'ClassString': "My ClassString",
}
# test starter
# \brief Common set up of Tango Server
def setUp(self):
print("\nsetting up...")
self.add()
self.start()
def add(self):
db = PyTango.Database()
devices = list(self.ts.values())
for dv in devices:
db.add_device(dv)
# print dv.name
db.put_device_property(dv.name, self.device_prop)
db.put_class_property(dv._class, self.class_prop)
if devices:
db.add_server(self.server, devices)
# starts server
def start(self):
db = PyTango.Database()
path = os.path.dirname(TestServer.__file__)
if not path:
path = '.'
if sys.version_info > (3,):
self._psub = subprocess.call(
"cd %s; python3 ./TestServer.py %s &" % (path, self.instance),
stdout=None, stderr=None, shell=True)
else:
self._psub = subprocess.call(
"cd %s; python ./TestServer.py %s &" % (path, self.instance),
stdout=None, stderr=None, shell=True)
sys.stdout.write("waiting for simple server")
found = False
cnt = 0
devices = list(self.ts.values())
while not found and cnt < 1000:
try:
sys.stdout.write(".")
sys.stdout.flush()
dpcnt = 0
for dv in devices:
exl = db.get_device_exported(dv.name)
if dv.name not in exl.value_string:
time.sleep(0.01)
cnt += 1
continue
self.dps[dv.name] = PyTango.DeviceProxy(dv.name)
time.sleep(0.01)
if self.dps[dv.name].state() == PyTango.DevState.ON:
dpcnt += 1
if dpcnt == len(devices):
found = True
except Exception:
found = False
cnt += 1
print("")
# test closer
# \brief Common tear down of Tango Server
def tearDown(self):
print("tearing down ...")
self.delete()
self.stop()
def delete(self):
db = PyTango.Database()
db.delete_server(self.server)
# stops server
def stop(self):
if sys.version_info > (3,):
with subprocess.Popen(
"ps -ef | grep 'TestServer.py %s' | grep -v grep" %
self.instance,
stdout=subprocess.PIPE, shell=True) as proc:
pipe = proc.stdout
res = str(pipe.read(), "utf8").split("\n")
for r in res:
sr = r.split()
if len(sr) > 2:
subprocess.call(
"kill -9 %s" % sr[1], stderr=subprocess.PIPE,
shell=True)
pipe.close()
else:
pipe = subprocess.Popen(
"ps -ef | grep 'TestServer.py %s' | grep -v grep" %
self.instance,
stdout=subprocess.PIPE, shell=True).stdout
res = str(pipe.read()).split("\n")
for r in res:
sr = r.split()
if len(sr) > 2:
subprocess.call(
"kill -9 %s" % sr[1], stderr=subprocess.PIPE,
shell=True)
pipe.close()
if __name__ == "__main__":
simps = TestServerSetUp()
simps.setUp()
print(simps.dp.status())
simps.tearDown()
simps = MultiTestServerSetUp()
simps.setUp()
for dp in simps.dps.values():
print(dp.status())
simps.tearDown()
simps = MultiTestServerSetUp(devices=[
"tm2/dd/sr", "dsf/44/fgg", "sdffd/sdfsd/sfd"])
simps.setUp()
for dp in simps.dps.values():
print(dp.status())
simps.tearDown()
| gpl-3.0 |
shtayerc/Labirint | class/player.js | 34479 | function playerInit()
{
player={
color:"#0000FF",
mapCoord:new coord(8,2), //koordinati v polju labirinta
hp:100,
dmg:20,
speed:5,
img:map.block['playerDown1'],
movingInterval:0,
state:0,
isMoving:false,
dir:'down',
canAttack:true,
lastDir:'',
fall:false,
attack:function(dir)
{
var speed=120;
var cd=1000;
var vmes='';
if(player.canAttack==true)
{
var nextBlock=new coord(0,0);
switch(dir)
{
case 'up':
nextBlock.x=player.mapCoord.x;
nextBlock.y=player.mapCoord.y-1;
vmes='F';
break;
case 'down':
nextBlock.x=player.mapCoord.x;
nextBlock.y=player.mapCoord.y+1;
vmes='B';
break;
case 'left':
nextBlock.x=player.mapCoord.x-1;
nextBlock.y=player.mapCoord.y;
vmes='L';
break;
case 'right':
nextBlock.x=player.mapCoord.x+1;
nextBlock.y=player.mapCoord.y;
vmes='R';
break;
}
if(map.level[nextBlock.y][nextBlock.x]==11 || map.level[nextBlock.y][nextBlock.x]==12 || map.level[nextBlock.y][nextBlock.x]==13)
{
switch(map.level[nextBlock.y][nextBlock.x])
{
case 11:
enemy01.list[enemy01.findByCoord(nextBlock.x,nextBlock.y)].hp-=player.dmg;
console.log(enemy01.list[enemy01.findByCoord(nextBlock.x,nextBlock.y)].hp);
break;
case 12:
enemy02.list[enemy02.findByCoord(nextBlock.x,nextBlock.y)].hp-=player.dmg;
console.log(enemy02.findByCoord(nextBlock.x,nextBlock.y));
break;
case 13:
enemy03.list[enemy03.findByCoord(nextBlock.x,nextBlock.y)].hp-=2*player.dmg;
console.log(enemy03.findByCoord(nextBlock.x,nextBlock.y));
break;
}
}
player.canAttack=false;
player.img=map.block['playerA'+vmes+'0'];
setTimeout(function (vmes){player.img=map.block['playerA'+vmes+'1'];},speed,vmes);
setTimeout(function (dir){
player.img=map.block['player'+dir.charAt(0).toUpperCase()+dir.slice(1)+'0'];player.canAttack=true;},cd,dir);
}
},
animation:{
isPlaying:false,
speed:160,
interval:0,
num:0,
thirdImg:false,
start:function (img1,img2,img3)
{
player.animation.num=0;
if(player.animation.isPlaying==false)
{
player.animation.isPlaying=true;
}else
{
clearInterval(player.animation.interval);
}
player.animation.nextFrame(img1,img2,img3);
player.animation.interval=setInterval(function (){
player.animation.nextFrame(img1,img2,img3);
},player.animation.speed);
},
nextFrame:function (img1,img2,img3)
{
if(player.animation.num%2==0)
{
player.img=img1;
}else
{
if((player.mapCoord.y+player.mapCoord.x)%2==0)
{
player.img=img3;
}else
{
player.img=img2;
}
}
player.animation.num+=1;
player.draw();
if(player.animation.num==3)
{
player.animation.num=0;
player.animation.isPlaying=false;
clearInterval(player.animation.interval);
}
}
},
movingFrame:{
xCh:0, //x change
yCh:0, //y change
start:new coord(0,0),
firstLine:0,
midLine:0,
lastLine:0,
exitCount:0,
interval:0 // tu je shranjen interval premikanja igralca
},
inventory:{
canvasCoord:new coord(655,400),
drawSize:new coord(125,80),
start:new coord(660,500),
slot:[],
size:new coord(5,2),
maxItems:10,
cellSize:new coord(25,40),
color:"#d3d3d3",
clear:function()
{
screen.clearRect(650,400,150,200);
},
draw:function()
{
screen.beginPath();
for (var x = 0; x <= player.inventory.drawSize.x; x += player.inventory.cellSize.x) {
screen.moveTo(0.5 + x + player.inventory.start.x, player.inventory.start.y);
screen.lineTo(0.5 + x + player.inventory.start.x, player.inventory.drawSize.y + player.inventory.start.y);
}
for (var x = 0; x <= player.inventory.drawSize.y; x += player.inventory.cellSize.y) {
screen.moveTo(player.inventory.start.x, 0.5 + x + player.inventory.start.y);
screen.lineTo(player.inventory.drawSize.x + player.inventory.start.x, 0.5 + x + player.inventory.start.y);
}
screen.strokeStyle = player.inventory.color;
screen.stroke();
screen.fillStyle="white";
screen.font="12px Arial";
var k=0;
var i=0;
for(var c=0;c<player.inventory.maxItems;c=c+1)
{
if(typeof(player.inventory.slot[c]) != 'undefined' && player.inventory.slot[c] != null)
{
screen.drawImage(player.inventory.slot[c].img,player.inventory.start.x+i*player.inventory.cellSize.x,
player.inventory.start.y+k*player.inventory.cellSize.y);
screen.fillText(player.inventory.slot[c].num,player.inventory.start.x+i*player.inventory.cellSize.x+3,
player.inventory.start.y+k*player.inventory.cellSize.y+35);
}
i=i+1;
if(i==5)
{
i=0;
k=k+1;
}
}
},
add:function(img,num)
{
for(var i=0;i<player.inventory.maxItems;i=i+1)
{
if(player.inventory.slot[i] == null)
{
player.inventory.slot[i]={
img:img,
num:num
};
break;
}
}
},
update:function(i,num)
{
player.inventory.slot[i].num=num;
},
remove:function(i)
{
player.inventory.slot[i]=null;
},
getIndex:function(string)
{
for(var i=0;i<player.inventory.maxItems;i=i+1)
{
if(typeof(player.inventory.slot[i]) != 'undefined' && player.inventory.slot[i] != null)
{
if(player.inventory.slot[i].img.src.includes(string))
{
return i;
}
}
}
}
},
getStartCoord:function()
{
var curPos=new coord(0,0); //current position
var mapa = new coord(1,1); //zacetna pozicija risanja v dvodimenzionalnem polju
var limit = new coord(32,25); // meja polja po sirini, po visini
while(mapa.y < limit.y) //zanka gre od 0,0 do limit.x, limit.y
{
mapa.x=1;
curPos.x=0;
while(mapa.x <= limit.x)
{
switch(map.level[mapa.y][mapa.x]) //preverja polje map.level in narise ustrezen blok
{
case 11:
enemy01.add(mapa.x,mapa.y);
break;
case 12:
enemy02.add(mapa.x,mapa.y);
break;
case 13:
enemy03.add(mapa.x,mapa.y);
break;
case 1:
player.canvasCoord.x=6* map.blockSize;
player.canvasCoord.y=6 * map.blockSize;
player.mapCoord.x = mapa.x;
player.mapCoord.y = mapa.y;
player.movingFrame.start=new coord(mapa.x-6,mapa.y-6);
break;
}
mapa.x = mapa.x + 1;
curPos.x = curPos.x + map.blockSize;
}
mapa.y = mapa.y +1;
curPos.y = curPos.y + map.blockSize;
}
},
slide:function(dir)
{
player.isMoving=true;
clearInterval(player.animation.interval);
if(player.lastDir==dir)
{
player.movingFrame.start.y=player.movingFrame.start.y+player.movingFrame.yCh;
player.movingFrame.start.x=player.movingFrame.start.x+player.movingFrame.xCh;
}
if(dir=='up')
{
player.img=map.block['playerUp1'];
if(player.lastDir=='right')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
player.movingFrame.start.x=player.movingFrame.start.x+1;
}
if(player.lastDir=='left')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
}
if(player.lastDir=='')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
}
player.lastDir='up';
player.movingFrame.lastLine=0;
player.movingFrame.midLine=0;
player.movingFrame.firstLine=50;
player.movingFrame.yCh=-1;
player.movingFrame.xCh=0;
}
if(dir=='down')
{
player.img=map.block['playerDown1'];
player.movingFrame.yCh=+1;
if(player.lastDir=='right')
{
player.movingFrame.start.x=player.movingFrame.start.x+1;
}
player.lastDir='down';
player.movingFrame.lastLine=-50;
player.movingFrame.midLine=-50;
player.movingFrame.firstLine=0;
player.movingFrame.xCh=0;
}
if(dir=='left')
{
player.img=map.block['playerLeft1'];
player.movingFrame.xCh=-1;
if(player.lastDir=='down')
{
player.movingFrame.start.y=player.movingFrame.start.y+1;
}
if(player.lastDir!='left' && player.lastDir!='right')
{
player.movingFrame.start.x=player.movingFrame.start.x+player.movingFrame.xCh;
}
player.lastDir='left';
player.movingFrame.midLine=0;
player.movingFrame.firstLine=50;
player.movingFrame.lastLine=0;
player.movingFrame.yCh=0;
}
if(dir== 'right')
{
player.img=map.block['playerRight1'];
if(player.lastDir=='down')
{
player.movingFrame.start.y=player.movingFrame.start.y+1;
}
player.lastDir='right';
player.movingFrame.firstLine=0;
player.movingFrame.midLine=-50;
player.movingFrame.lastLine=-50;
player.movingFrame.xCh=1;
player.movingFrame.yCh=0;
}
player.movingFrame.exitCount=0;
player.mapCoord.x=player.mapCoord.x+player.movingFrame.xCh;
player.mapCoord.y=player.mapCoord.y+player.movingFrame.yCh;
player.isMoving=true;
player.movingFrame.interval=setInterval(function (){
if(player.movingFrame.exitCount>=map.blockSize){
player.isMoving=false;
switch(player.lastDir)
{
case 'left':
player.img=map.block['playerLeft0'];
break;
case 'right':
player.img=map.block['playerRight0'];
break;
}
clearInterval(player.movingFrame.interval);
}
player.movingFrame.firstLine=player.movingFrame.firstLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.lastLine=player.movingFrame.lastLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.midLine=player.movingFrame.midLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.exitCount+=1;
},player.speed);
},
move:function(dir)
{
sound.play('walk');
if(player.lastDir==dir)
{
player.movingFrame.start.y=player.movingFrame.start.y+player.movingFrame.yCh;
player.movingFrame.start.x=player.movingFrame.start.x+player.movingFrame.xCh;
}
if(dir=='up')
{
player.dir='up';
player.animation.start(map.block['playerUp0'],map.block['playerUp2'],map.block['playerUp1']);
if(player.lastDir=='right')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
player.movingFrame.start.x=player.movingFrame.start.x+1;
}
if(player.lastDir=='left')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
}
if(player.lastDir=='')
{
player.movingFrame.start.y=player.movingFrame.start.y-1;
}
player.lastDir='up';
player.movingFrame.lastLine=0;
player.movingFrame.midLine=0;
player.movingFrame.firstLine=50;
player.movingFrame.yCh=-1;
player.movingFrame.xCh=0;
}
if(dir=='down')
{
player.dir='down';
player.animation.start(map.block['playerDown0'],map.block['playerDown2'],map.block['playerDown1']);
player.movingFrame.yCh=+1;
if(player.lastDir=='right')
{
player.movingFrame.start.x=player.movingFrame.start.x+1;
}
player.lastDir='down';
player.movingFrame.lastLine=-50;
player.movingFrame.midLine=-50;
player.movingFrame.firstLine=0;
player.movingFrame.xCh=0;
}
if(dir=='left')
{
player.dir='left';
player.animation.start(map.block['playerLeft0'],map.block['playerLeft2'],map.block['playerLeft1']);
player.movingFrame.xCh=-1;
if(player.lastDir=='down')
{
player.movingFrame.start.y=player.movingFrame.start.y+1;
}
if(player.lastDir!='left' && player.lastDir!='right')
{
player.movingFrame.start.x=player.movingFrame.start.x+player.movingFrame.xCh;
}
player.lastDir='left';
player.movingFrame.midLine=0;
player.movingFrame.firstLine=50;
player.movingFrame.lastLine=0;
player.movingFrame.yCh=0;
}
if(dir== 'right')
{
player.dir='right';
player.animation.start(map.block['playerRight0'],map.block['playerRight2'],map.block['playerRight1']);
if(player.lastDir=='down')
{
player.movingFrame.start.y=player.movingFrame.start.y+1;
}
player.lastDir='right';
player.movingFrame.firstLine=0;
player.movingFrame.midLine=-50;
player.movingFrame.lastLine=-50;
player.movingFrame.xCh=1;
player.movingFrame.yCh=0;
}
player.movingFrame.exitCount=0;
player.mapCoord.x=player.mapCoord.x+player.movingFrame.xCh;
player.mapCoord.y=player.mapCoord.y+player.movingFrame.yCh;
player.isMoving=true;
player.movingFrame.interval=setInterval(function (){
if(player.movingFrame.exitCount>=map.blockSize){
player.isMoving=false;
clearInterval(player.movingFrame.interval);
}
player.movingFrame.firstLine=player.movingFrame.firstLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.lastLine=player.movingFrame.lastLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.midLine=player.movingFrame.midLine+player.movingFrame.yCh+player.movingFrame.xCh;
player.movingFrame.exitCount+=1;
},player.speed);
},
drawMovingFrame:function()
{
map.clear();
screen.drawImage(map.block['floorBig'], 0, 0);
var curPos=new coord(0,0);
var canLimit=new coord(601,551);
var mapCoord=new coord(player.movingFrame.start.x,player.movingFrame.start.y);
if(player.movingFrame.xCh!=0) //levo ali desno
{
for(curPos.y=0;curPos.y<canLimit.y;curPos.y=curPos.y+map.blockSize)//leva vrsta
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.firstLine,
0,map.blockSize, map.blockSize, 0, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.firstLine,
0,map.blockSize, map.blockSize, 0, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage( enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.firstLine,
0,map.blockSize, map.blockSize, 0, curPos.y, map.blockSize, map.blockSize);
}else
{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)],player.movingFrame.firstLine,
0, map.blockSize, map.blockSize, 0, curPos.y, map.blockSize, map.blockSize);
}
mapCoord.y=mapCoord.y+1;
}
mapCoord.y=player.movingFrame.start.y;
mapCoord.x=mapCoord.x+1;
for(curPos.x=0;curPos.x<canLimit.x-map.blockSize;curPos.x=curPos.x+map.blockSize)//ostali bloki vmes
{
mapCoord.y=player.movingFrame.start.y;
for(curPos.y=0;curPos.y<canLimit.y;curPos.y=curPos.y+map.blockSize)//ostali bloki vmes
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,0,
0,map.blockSize, map.blockSize, curPos.x+player.movingFrame.midLine*-1, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,0,
0,map.blockSize, map.blockSize, curPos.x+player.movingFrame.midLine*-1, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage( enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,0,
0,map.blockSize, map.blockSize, curPos.x+player.movingFrame.midLine*-1, curPos.y, map.blockSize, map.blockSize);
}else{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)], 0,
0,map.blockSize, map.blockSize, curPos.x+player.movingFrame.midLine*-1, curPos.y, map.blockSize, map.blockSize);
}
mapCoord.y=mapCoord.y+1;
}
mapCoord.x=mapCoord.x+1;
}
mapCoord.y=player.movingFrame.start.y;
for(curPos.y=0;curPos.y<canLimit.y;curPos.y=curPos.y+map.blockSize)//desna vrsta
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.lastLine,
0,map.blockSize, map.blockSize, 600, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.lastLine,
0,map.blockSize, map.blockSize, 600, curPos.y, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage(enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,player.movingFrame.lastLine,
0,map.blockSize,map.blockSize,600,curPos.y,map.blockSize,map.blockSize);
}else{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)],player.movingFrame.lastLine,
0,map.blockSize,map.blockSize,600,curPos.y,map.blockSize,map.blockSize);
}
mapCoord.y=mapCoord.y+1;
}
}
if(player.movingFrame.yCh!=0) //gor ali dol
{
for(curPos.x=0;curPos.x<canLimit.x;curPos.x=curPos.x+map.blockSize)//zgornja vrsta
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.firstLine,map.blockSize, map.blockSize, curPos.x, 0, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.firstLine,map.blockSize, map.blockSize, curPos.x, 0, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage(enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.firstLine, map.blockSize, map.blockSize, curPos.x, 0, map.blockSize, map.blockSize);
}else{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)],0,
player.movingFrame.firstLine, map.blockSize, map.blockSize, curPos.x, 0, map.blockSize, map.blockSize);
}
mapCoord.x=mapCoord.x+1;
}
mapCoord.y=mapCoord.y+1;
mapCoord.x=player.movingFrame.start.x;
for(curPos.y=0;curPos.y<canLimit.y-map.blockSize;curPos.y=curPos.y+map.blockSize)//ostali bloki vmes
{
mapCoord.x=player.movingFrame.start.x;
for(curPos.x=0;curPos.x<canLimit.x;curPos.x=curPos.x+map.blockSize)//ostali bloki vmes
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,0,0,
map.blockSize, map.blockSize, curPos.x, curPos.y+player.movingFrame.midLine*-1, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,0,0,
map.blockSize, map.blockSize, curPos.x, curPos.y+player.movingFrame.midLine*-1, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage(enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,0,0,
map.blockSize, map.blockSize, curPos.x, curPos.y+player.movingFrame.midLine*-1, map.blockSize, map.blockSize);
}else{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)], 0,
0,map.blockSize, map.blockSize, curPos.x, curPos.y+player.movingFrame.midLine*-1, map.blockSize, map.blockSize);
}
mapCoord.x=mapCoord.x+1;
}
mapCoord.y=mapCoord.y+1;
}
mapCoord.x=player.movingFrame.start.x;
for(curPos.x=0;curPos.x<canLimit.x;curPos.x=curPos.x+map.blockSize)//spodnja vrsta
{
if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy03')
{
screen.drawImage( enemy03.list[enemy03.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.lastLine,map.blockSize, map.blockSize, curPos.x, 550, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy02')
{
screen.drawImage( enemy02.list[enemy02.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.lastLine,map.blockSize, map.blockSize, curPos.x, 550, map.blockSize, map.blockSize);
}else if(map.getBlock50(mapCoord.x,mapCoord.y)=='enemy01')
{
screen.drawImage(enemy01.list[enemy01.findByCoord(mapCoord.x,mapCoord.y)].img,0,
player.movingFrame.lastLine,map.blockSize,map.blockSize,curPos.x,550,map.blockSize,map.blockSize);
}else
{
screen.drawImage(map.block[map.getBlock50(mapCoord.x,mapCoord.y)],0,
player.movingFrame.lastLine,map.blockSize,map.blockSize,curPos.x,550,map.blockSize,map.blockSize);
}
mapCoord.x=mapCoord.x+1;
}
}
player.draw();
},
canvasCoord:function() //dejanski koordinati v canvasu, v funkciji se izracunajo iz player.mapCoord in map.blockSize
{
player.canvasCoord=new coord((this.mapCoord.x-1)*map.blockSize, (this.mapCoord.y-1)* map.blockSize);
},
draw:function()
{
if(player.fall==false)
{
screen.drawImage(player.img, player.canvasCoord.x, player.canvasCoord.y);
}
},
drawHp:function()
{
screen.fillStyle="red";
screen.fillRect(215, 607,player.hp/100*365, 10);
screen.drawImage(map.block['hp'], 200, 603);
},
isDead:function()
{
if(player.hp<=0)
{
return true;
}else
{
return false;
}
},
isHit:function()
{
var lastDir=new coord(player.mapCoord.x,player.mapCoord.y);
if(player.isMoving==true)
{
switch(player.lastDir)
{
case 'up':
lastDir.y=lastDir.y+1;
break;
case 'down':
lastDir.y=lastDir.y-1;
break;
case 'left':
lastDir.x=lastDir.x+1;
break;
case 'right':
lastDir.x=lastDir.x-1;
break;
}
}
if(map.level[lastDir.y][lastDir.x]==12)
{
player.hp=player.hp-enemy02.dmg;
}
if(map.level[lastDir.y][lastDir.x]==11)
{
player.hp=player.hp-enemy01.dmg;
}
},
getCloseEnemy:function()
{
var dist=new coord(0,0);
var pos=new coord(0,0);
var len=enemy01.list.length;
for(var i=0;i<len;i=i+1)
{
if(i==0)
{
dist.x=Math.abs(enemy01.list[i].canvasCoord.x-player.canvasCoord.x);
dist.y=Math.abs(enemy01.list[i].canvasCoord.y-player.canvasCoord.y);
pos.x=enemy01.list[i].canvasCoord.x;
pos.y=enemy01.list[i].canvasCoord.y;
}
if(Math.abs(enemy01.list[i].canvasCoord.x-player.canvasCoord.x)<dist.x && Math.abs(enemy01.list[i].canvasCoord.y-player.canvasCoord.y)<dist.y)
{
dist.x=Math.abs(enemy01.list[i].canvasCoord.x-player.canvasCoord.x);
dist.y=Math.abs(enemy01.list[i].canvasCoord.y-player.canvasCoord.y);
pos.x=enemy01.list[i].canvasCoord.x;
pos.y=enemy01.list[i].canvasCoord.y;
}
}
return pos;
},
canMove:function(dir) //funkcija vrne true ce igralec lahko premakne v zeljeno smer(ce ni ovir), false ce se ne more
{
var next2Block=new coord(0,0);
var nextBlock=new coord(0,0); //tu so shranjeni koordinati naslednjega bloka, ki se bo preverjal
switch(dir)
{
case 'up':
nextBlock.x=player.mapCoord.x;
nextBlock.y=player.mapCoord.y-1;
next2Block.x=player.mapCoord.x;
next2Block.y=player.mapCoord.y-2;
break;
case 'down':
nextBlock.x=player.mapCoord.x;
nextBlock.y=player.mapCoord.y+1;
next2Block.x=player.mapCoord.x;
next2Block.y=player.mapCoord.y+2;
break;
case 'left':
nextBlock.x=player.mapCoord.x-1;
nextBlock.y=player.mapCoord.y;
next2Block.x=player.mapCoord.x-2;
next2Block.y=player.mapCoord.y;
break;
case 'right':
nextBlock.x=player.mapCoord.x+1;
nextBlock.y=player.mapCoord.y;
next2Block.x=player.mapCoord.x+2;
next2Block.y=player.mapCoord.y;
break;
}
//2 - wall 6 - keylock_2 8 - keylock_1
if(map.level[nextBlock.y][nextBlock.x]==3 && map.level[next2Block.y][next2Block.x] !=0)
{
return false;
}
if (map.level[nextBlock.y][nextBlock.x] != 2 && map.level[nextBlock.y][nextBlock.x] != 8
&& map.level[nextBlock.y][nextBlock.x] != 6 && map.level[nextBlock.y][nextBlock.x] != 13)
//ce naslednji blok ni zid, ali kljucavnica vrne true
{
return true;
}else if ((map.level[nextBlock.y][nextBlock.x] == 8 && map.keys.key_1.taken == true) ||
(map.level[nextBlock.y][nextBlock.x]==6 && map.keys.key_2.taken == true))
//ce naslednje blok je klucavnica in ima igralec ustrezen kljuc vrne true
{
return true;
}
return false;
}
};
player.onload=player.canvasCoord(); // funkcija ki izracuna player.canvasCoord se izvede ko se objekt player nalozi
}
| gpl-3.0 |
MonokuroInzanaito/ygopro-777DIY | expansions/script/c18706053.lua | 1220 | --艾莉丝的提灯
function c18706053.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c18706053.cost)
e1:SetTarget(c18706053.target)
e1:SetOperation(c18706053.activate)
c:RegisterEffect(e1)
end
function c18706053.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c18706053.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsAbleToHand() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToHand,tp,LOCATION_MZONE,LOCATION_MZONE,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,LOCATION_MZONE,LOCATION_MZONE,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,2,0,0)
end
function c18706053.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
Duel.SendtoHand(g,nil,REASON_EFFECT)
end
| gpl-3.0 |
projectestac/alexandria | html/langpacks/sv/repository_flickr_public.php | 3267 | <?php
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
/**
* Strings for component 'repository_flickr_public', language 'sv', version '3.11'.
*
* @package repository_flickr_public
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['all'] = 'Alla';
$string['apikey'] = 'API-nyckel';
$string['backtosearch'] = 'Tillbaka till söksidan';
$string['by'] = '';
$string['by-nc'] = 'Attribution-NonCommercial license';
$string['by-nc-nd'] = 'Attribution-NonCommercial-NoDerivs license';
$string['by-nc-sa'] = 'Attribution-NonCommercial-ShareAlike license';
$string['by-nd'] = 'Attribution-NoDerivs license';
$string['by-sa'] = 'Attribution-ShareAlike license';
$string['callbackurl'] = 'Återkopplings-URL';
$string['commercialuse'] = 'Jag vill använda bilderna kommersiellt';
$string['configplugin'] = 'Publik Flickr-konfiguration';
$string['creativecommonscommercial'] = 'Only creative commons commercial';
$string['emailaddress'] = 'E-post';
$string['flickr_public:view'] = 'Använd publika Flickr-lagringsplatsen i filväljaren';
$string['fulltext'] = 'Hela texten';
$string['information'] = '<div>Hämta en<a href="http://www.flickr.com/services/api/keys/">Flickr API-nyckel</a> för din Moodle-webbplats. </div>';
$string['invalidemail'] = 'Ogiltig e-postadress för Flickr';
$string['license'] = 'Licens';
$string['modification'] = 'Jag vill kunna modifiera bilderna';
$string['notitle'] = 'ingentitel';
$string['nullphotolist'] = 'Det finns inga bilder i detta konto';
$string['pluginname'] = 'Flickr public';
$string['pluginname_help'] = 'Flickr-lagringsplats';
$string['privacy:metadata:repository_flickr_public'] = 'Pluginmodulen Publik Flickr lagrar ingen personinformation, men överför användardata från Moodle till fjärrsystemet.';
$string['privacy:metadata:repository_flickr_public:author'] = 'Innehållsförfattaren för innehållet på Publika Flickr.';
$string['privacy:metadata:repository_flickr_public:email_address'] = 'Användarens e-postadress på Publika Flickr.';
$string['privacy:metadata:repository_flickr_public:text'] = 'Användarens sökfråga på Publika Flickr.';
$string['privacy:metadata:repository_flickr_public:user_id'] = 'Användar-ID på Publika Flickr.';
$string['remember'] = 'Kom ihåg mig';
$string['secret'] = 'Hemlighet';
$string['sharealike'] = 'Ja, så länge andra delar likadant';
$string['tag'] = 'Etikett';
$string['username'] = 'E-postadress för Flickr-kontot';
$string['watermark'] = 'Lägg till vattenmärke i foton';
| gpl-3.0 |
QuSwense/Website_Scrapper | WebsiteScrapper/WebsiteScrapper/CountryApp/CIAFactbookCountryCapitalsModel.cs | 314 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebsiteScrapper.Model;
namespace WebsiteScrapper.CountryApp
{
public class CIAFactbookCountryCapitalsModel : ScrapObject<object>
{
public string Name { get; set; }
}
}
| gpl-3.0 |
pepzi/pahimod | src/main/java/org/pepzi/pahimod/block/BlockPMod.java | 1219 | package org.pepzi.pahimod.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemStack;
import org.pepzi.pahimod.creativetab.CreativeTabPMod;
import org.pepzi.pahimod.reference.Reference;
public class BlockPMod extends Block {
public BlockPMod(Material material) {
super(material);
this.setCreativeTab(CreativeTabPMod.PMOD_TAB);
}
public BlockPMod() {
this(Material.rock);
}
@Override
public String getUnlocalizedName() {
return String.format("tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
blockIcon = iconRegister.registerIcon(String.format("%s", getUnwrappedUnlocalizedName(this.getUnlocalizedName())));
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
}
| gpl-3.0 |
timpalpant/calibre | src/calibre/ebooks/oeb/polish/cover.py | 18171 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import shutil, re, os
from calibre.ebooks.oeb.base import OPF, OEB_DOCS, XPath, XLINK, xml2text
from calibre.ebooks.oeb.polish.replace import replace_links, get_recommended_folders
from calibre.utils.imghdr import identify
def set_azw3_cover(container, cover_path, report, options=None):
existing_image = options is not None and options.get('existing_image', False)
name = None
found = True
for gi in container.opf_xpath('//opf:guide/opf:reference[@href and contains(@type, "cover")]'):
href = gi.get('href')
name = container.href_to_name(href, container.opf_name)
container.remove_from_xml(gi)
if existing_image:
name = cover_path
found = False
else:
if name is None or not container.has_name(name):
item = container.generate_item(name='cover.jpeg', id_prefix='cover')
name = container.href_to_name(item.get('href'), container.opf_name)
found = False
href = container.name_to_href(name, container.opf_name)
guide = container.opf_xpath('//opf:guide')[0]
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), href=href, type='cover'))
if not existing_image:
with lopen(cover_path, 'rb') as src, container.open(name, 'wb') as dest:
shutil.copyfileobj(src, dest)
container.dirty(container.opf_name)
report(_('Cover updated') if found else _('Cover inserted'))
def get_azw3_raster_cover_name(container):
items = container.opf_xpath('//opf:guide/opf:reference[@href and contains(@type, "cover")]')
if items:
return container.href_to_name(items[0].get('href'))
def mark_as_cover_azw3(container, name):
href = container.name_to_href(name, container.opf_name)
found = False
for item in container.opf_xpath('//opf:guide/opf:reference[@href and contains(@type, "cover")]'):
item.set('href', href)
found = True
if not found:
for guide in container.opf_xpath('//opf:guide'):
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), href=href, type='cover'))
container.dirty(container.opf_name)
def get_raster_cover_name(container):
if container.book_type == 'azw3':
return get_azw3_raster_cover_name(container)
return find_cover_image(container, strict=True)
def get_cover_page_name(container):
if container.book_type == 'azw3':
return
return find_cover_page(container)
def set_cover(container, cover_path, report=None, options=None):
'''
Set the cover of the book to the image pointed to by cover_path.
:param cover_path: Either the absolute path to an image file or the
canonical name of an image in the book. When using an image in the book,
you must also set options, see below.
:param report: An optional callable that takes a single argument. It will
be called with information about the tasks being processed.
:param options: None or a dictionary that controls how the cover is set. The dictionary can have entries:
**keep_aspect**: True or False (Preserve aspect ratio of covers in EPUB)
**no_svg**: True or False (Use an SVG cover wrapper in the EPUB titlepage)
**existing**: True or False (``cover_path`` refers to an existing image in the book)
'''
report = report or (lambda x:x)
if container.book_type == 'azw3':
set_azw3_cover(container, cover_path, report, options=options)
else:
set_epub_cover(container, cover_path, report, options=options)
def mark_as_cover(container, name):
'''
Mark the specified image as the cover image.
'''
if name not in container.mime_map:
raise ValueError('Cannot mark %s as cover as it does not exist' % name)
mt = container.mime_map[name]
if not is_raster_image(mt):
raise ValueError('Cannot mark %s as the cover image as it is not a raster image' % name)
if container.book_type == 'azw3':
mark_as_cover_azw3(container, name)
else:
mark_as_cover_epub(container, name)
###############################################################################
# The delightful EPUB cover processing
def is_raster_image(media_type):
return media_type and media_type.lower() in {
'image/png', 'image/jpeg', 'image/jpg', 'image/gif'}
COVER_TYPES = {
'coverimagestandard', 'other.ms-coverimage-standard',
'other.ms-titleimage-standard', 'other.ms-titleimage',
'other.ms-coverimage', 'other.ms-thumbimage-standard',
'other.ms-thumbimage', 'thumbimagestandard', 'cover'}
def find_cover_image(container, strict=False):
'Find a raster image marked as a cover in the OPF'
manifest_id_map = container.manifest_id_map
mm = container.mime_map
for meta in container.opf_xpath('//opf:meta[@name="cover" and @content]'):
item_id = meta.get('content')
name = manifest_id_map.get(item_id, None)
media_type = mm.get(name, None)
if is_raster_image(media_type):
return name
# First look for a guide item with type == 'cover'
guide_type_map = container.guide_type_map
for ref_type, name in guide_type_map.iteritems():
if ref_type.lower() == 'cover' and is_raster_image(mm.get(name, None)):
return name
if strict:
return
# Find the largest image from all possible guide cover items
largest_cover = (None, 0)
for ref_type, name in guide_type_map.iteritems():
if ref_type.lower() in COVER_TYPES and is_raster_image(mm.get(name, None)):
path = container.name_path_map.get(name, None)
if path:
sz = os.path.getsize(path)
if sz > largest_cover[1]:
largest_cover = (name, sz)
if largest_cover[0]:
return largest_cover[0]
def get_guides(container):
guides = container.opf_xpath('//opf:guide')
if not guides:
container.insert_into_xml(container.opf, container.opf.makeelement(
OPF('guide')))
guides = container.opf_xpath('//opf:guide')
return guides
def mark_as_cover_epub(container, name):
mmap = {v:k for k, v in container.manifest_id_map.iteritems()}
if name not in mmap:
raise ValueError('Cannot mark %s as cover as it is not in manifest' % name)
mid = mmap[name]
# Remove all entries from the opf that identify a raster image as cover
for meta in container.opf_xpath('//opf:meta[@name="cover" and @content]'):
container.remove_from_xml(meta)
for ref in container.opf_xpath('//opf:guide/opf:reference[@href and @type]'):
if ref.get('type').lower() not in COVER_TYPES:
continue
name = container.href_to_name(ref.get('href'), container.opf_name)
mt = container.mime_map.get(name, None)
if is_raster_image(mt):
container.remove_from_xml(ref)
# Add reference to image in <metadata>
for metadata in container.opf_xpath('//opf:metadata'):
m = metadata.makeelement(OPF('meta'), name='cover', content=mid)
container.insert_into_xml(metadata, m)
# If no entry for titlepage exists in guide, insert one that points to this
# image
if not container.opf_xpath('//opf:guide/opf:reference[@type="cover"]'):
for guide in get_guides(container):
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), type='cover', href=container.name_to_href(name, container.opf_name)))
container.dirty(container.opf_name)
def mark_as_titlepage(container, name, move_to_start=True):
'''
Mark the specified HTML file as the titlepage of the EPUB.
:param move_to_start: If True the HTML file is moved to the start of the spine
'''
if move_to_start:
for item, q, linear in container.spine_iter:
if name == q:
break
if not linear:
item.set('linear', 'yes')
if item.getparent().index(item) > 0:
container.insert_into_xml(item.getparent(), item, 0)
for ref in container.opf_xpath('//opf:guide/opf:reference[@type="cover"]'):
ref.getparent().remove(ref)
for guide in get_guides(container):
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), type='cover', href=container.name_to_href(name, container.opf_name)))
container.dirty(container.opf_name)
def find_cover_page(container):
'Find a document marked as a cover in the OPF'
mm = container.mime_map
guide_type_map = container.guide_type_map
for ref_type, name in guide_type_map.iteritems():
if ref_type.lower() == 'cover' and mm.get(name, '').lower() in OEB_DOCS:
return name
def find_cover_image_in_page(container, cover_page):
root = container.parsed(cover_page)
body = XPath('//h:body')(root)
if len(body) != 1:
return
body = body[0]
images = []
for img in XPath('descendant::h:img[@src]|descendant::svg:svg/descendant::svg:image')(body):
href = img.get('src') or img.get(XLINK('href'))
if href:
name = container.href_to_name(href, base=cover_page)
images.append(name)
text = re.sub(r'\s+', '', xml2text(body))
if text or len(images) > 1:
# Document has more content than a single image
return
if images:
return images[0]
def clean_opf(container):
'Remove all references to covers from the OPF'
manifest_id_map = container.manifest_id_map
for meta in container.opf_xpath('//opf:meta[@name="cover" and @content]'):
name = manifest_id_map.get(meta.get('content', None), None)
container.remove_from_xml(meta)
if name and name in container.name_path_map:
yield name
gtm = container.guide_type_map
for ref in container.opf_xpath('//opf:guide/opf:reference[@type]'):
typ = ref.get('type', '')
if typ.lower() in COVER_TYPES:
container.remove_from_xml(ref)
name = gtm.get(typ, None)
if name and name in container.name_path_map:
yield name
container.dirty(container.opf_name)
def create_epub_cover(container, cover_path, existing_image, options=None):
from calibre.ebooks.conversion.config import load_defaults
from calibre.ebooks.oeb.transforms.cover import CoverManager
try:
ext = cover_path.rpartition('.')[-1].lower()
except Exception:
ext = 'jpeg'
cname, tname = 'cover.' + ext, 'titlepage.xhtml'
recommended_folders = get_recommended_folders(container, (cname, tname))
if existing_image:
raster_cover = existing_image
manifest_id = {v:k for k, v in container.manifest_id_map.iteritems()}[existing_image]
raster_cover_item = container.opf_xpath('//opf:manifest/*[@id="%s"]' % manifest_id)[0]
else:
folder = recommended_folders[cname]
if folder:
cname = folder + '/' + cname
raster_cover_item = container.generate_item(cname, id_prefix='cover')
raster_cover = container.href_to_name(raster_cover_item.get('href'), container.opf_name)
with container.open(raster_cover, 'wb') as dest:
if callable(cover_path):
cover_path('write_image', dest)
else:
with lopen(cover_path, 'rb') as src:
shutil.copyfileobj(src, dest)
if options is None:
opts = load_defaults('epub_output')
keep_aspect = opts.get('preserve_cover_aspect_ratio', False)
no_svg = opts.get('no_svg_cover', False)
else:
keep_aspect = options.get('keep_aspect', False)
no_svg = options.get('no_svg', False)
if no_svg:
style = 'style="height: 100%%"'
templ = CoverManager.NONSVG_TEMPLATE.replace('__style__', style)
else:
if callable(cover_path):
templ = (options or {}).get('template', CoverManager.SVG_TEMPLATE)
else:
width, height = 600, 800
try:
if existing_image:
width, height = identify(container.raw_data(existing_image, decode=False))[1:]
else:
with lopen(cover_path, 'rb') as csrc:
width, height = identify(csrc)[1:]
except:
container.log.exception("Failed to get width and height of cover")
ar = 'xMidYMid meet' if keep_aspect else 'none'
templ = CoverManager.SVG_TEMPLATE.replace('__ar__', ar)
templ = templ.replace('__viewbox__', '0 0 %d %d'%(width, height))
templ = templ.replace('__width__', str(width))
templ = templ.replace('__height__', str(height))
folder = recommended_folders[tname]
if folder:
tname = folder + '/' + tname
titlepage_item = container.generate_item(tname, id_prefix='titlepage')
titlepage = container.href_to_name(titlepage_item.get('href'),
container.opf_name)
raw = templ%container.name_to_href(raster_cover, titlepage).encode('utf-8')
with container.open(titlepage, 'wb') as f:
f.write(raw)
# We have to make sure the raster cover item has id="cover" for the moron
# that wrote the Nook firmware
if raster_cover_item.get('id') != 'cover':
from calibre.ebooks.oeb.base import uuid_id
newid = uuid_id()
for item in container.opf_xpath('//*[@id="cover"]'):
item.set('id', newid)
for item in container.opf_xpath('//*[@idref="cover"]'):
item.set('idref', newid)
raster_cover_item.set('id', 'cover')
spine = container.opf_xpath('//opf:spine')[0]
ref = spine.makeelement(OPF('itemref'), idref=titlepage_item.get('id'))
container.insert_into_xml(spine, ref, index=0)
guide = container.opf_get_or_create('guide')
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), type='cover', title=_('Cover'),
href=container.name_to_href(titlepage, base=container.opf_name)))
metadata = container.opf_get_or_create('metadata')
meta = metadata.makeelement(OPF('meta'), name='cover')
meta.set('content', raster_cover_item.get('id'))
container.insert_into_xml(metadata, meta)
return raster_cover, titlepage
def remove_cover_image_in_page(container, page, cover_images):
for img in container.parsed(page).xpath('//*[local-name()="img" and @src]'):
href = img.get('src')
name = container.href_to_name(href, page)
if name in cover_images:
img.getparent().remove(img)
break
def set_epub_cover(container, cover_path, report, options=None):
existing_image = options is not None and options.get('existing_image', False)
if existing_image:
existing_image = cover_path
cover_image = find_cover_image(container)
cover_page = find_cover_page(container)
wrapped_image = extra_cover_page = None
updated = False
log = container.log
possible_removals = set(clean_opf(container))
possible_removals
# TODO: Handle possible_removals and also iterate over links in the removed
# pages and handle possibly removing stylesheets referred to by them.
spine_items = tuple(container.spine_items)
if cover_page is None:
# Check if the first item in the spine is a simple cover wrapper
candidate = container.abspath_to_name(spine_items[0])
if find_cover_image_in_page(container, candidate) is not None:
cover_page = candidate
if cover_page is not None:
log('Found existing cover page')
wrapped_image = find_cover_image_in_page(container, cover_page)
if len(spine_items) > 1:
# Look for an extra cover page
c = container.abspath_to_name(spine_items[1])
if c != cover_page:
candidate = find_cover_image_in_page(container, c)
if candidate and candidate in {wrapped_image, cover_image}:
log('Found an extra cover page that is a simple wrapper, removing it')
# This page has only a single image and that image is the
# cover image, remove it.
container.remove_item(c)
extra_cover_page = c
spine_items = spine_items[:1] + spine_items[2:]
elif candidate is None:
# Remove the cover image if it is the first image in this
# page
remove_cover_image_in_page(container, c, {wrapped_image,
cover_image})
if wrapped_image is not None:
# The cover page is a simple wrapper around a single cover image,
# we can remove it safely.
log('Existing cover page is a simple wrapper, removing it')
container.remove_item(cover_page)
if wrapped_image != existing_image:
container.remove_item(wrapped_image)
updated = True
if cover_image and cover_image != wrapped_image:
# Remove the old cover image
if cover_image != existing_image:
container.remove_item(cover_image)
# Insert the new cover
raster_cover, titlepage = create_epub_cover(container, cover_path, existing_image, options=options)
report(_('Cover updated') if updated else _('Cover inserted'))
# Replace links to the old cover image/cover page
link_sub = {s:d for s, d in {
cover_page:titlepage, wrapped_image:raster_cover,
cover_image:raster_cover, extra_cover_page:titlepage}.iteritems()
if s is not None and s != d}
if link_sub:
replace_links(container, link_sub, frag_map=lambda x, y:None)
return raster_cover, titlepage
| gpl-3.0 |
entrepidea/projects | java/java.core/src/test/java/com/entrepidea/algo/leetcode/easy/LE167TwoSums.java | 1207 | package com.entrepidea.algo.leetcode.easy;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: find out the index of two elements in a sorted array, the sum of which will be equal to the given number.
* @Source: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
* @Date: on 9/12/2019.
*/
public class LE167TwoSums {
@Before
public void setup(){
}
class Pair{
public int i;
public int j;
public Pair(int ii, int jj){
i = ii;
j=jj;
}
}
private List<Pair> findPairs(int[] array, int sum){
List<Pair> l = new ArrayList<>();
for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if((array[i]+array[j])==sum){
l.add(new Pair(i+1,j+1));
}
}
}
return l;
}
@Test
public void test(){
int[] numbers = new int[]{2,7,11,15};
List<Pair> l = findPairs(numbers,9);
Assert.assertTrue(l.size()==1);
Assert.assertTrue(l.get(0).i==1 && l.get(0).j == 2);
}
}
| gpl-3.0 |
vitalisator/librenms | database/migrations/2018_07_03_091314_create_transport_group_transport_table.php | 1522 | <?php
/**
* 2018_07_03_091314_create_transport_group_transport_table.php
*
* -Description-
*
* 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/>.
*
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTransportGroupTransportTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('transport_group_transport', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('transport_group_id');
$table->unsignedInteger('transport_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('transport_group_transport');
}
}
| gpl-3.0 |
iLUB/ILIAS-Etherpad-Lite-Plugin | js/ilEtherpadLite.js | 1959 | /**
* etherpadliteJsClass
*
* @author Timon Amstutz <timon.amstutz@ilub.unibe.ch>
* **/
function etherpadliteJsClass() {
/** "Private" variables **/
var fullscreenPad = false;
var height = 0;
var extraForChatVisibility = 300;
/** "Public" functions **/
this.toggleFullscreen = function () {
fullscreenPad = !fullscreenPad;
this.resizePad();
}
this.resizePad = function () {
if (fullscreenPad) {
height = $(window).height();
}
else {
height = $(window).height() - ($("#fsxMainHeader").height() + $("div.il_Header").height() + $("div.ilLocator.xsmall").height()+extraForChatVisibility);
}
repaintPad();
}
/** Constructor actions **/
this.resizePad();
$("#leaveFullscreenPad").hide();
/** "Private" functions **/
function repaintPad() {
if (fullscreenPad) {
$("#etherpad-lite").addClass("etherpad-liteFullscreen").removeClass("etherpad-liteRegular");
$("html").scrollTop(0);
$("body").addClass("hiddenOverflow");
$("#enterFullscreenPad").hide();
$("#leaveFullscreenPad").show();
}
else {
$("#etherpad-lite").addClass("etherpad-liteRegular").removeClass("etherpad-liteFullscreen");
$("body").removeClass("hiddenOverflow");
$("#enterFullscreenPad").show();
$("#leaveFullscreenPad").hide();
}
$("#etherpad-lite").css({'height':height + "px"});
$("#etherpad-liteFrame").css({'height':$("#etherpad-lite").height() - $(".labeFullscreenPad").height()-1 + "px"});
}
}
/** Actions done when Document is loaded **/
$(function () {
var etherpadlite = new etherpadliteJsClass();
$(window).resize(function () {
etherpadlite.resizePad();
});
$(".labeFullscreenPad").click(function () {
etherpadlite.toggleFullscreen();
});
});
| gpl-3.0 |
ernestbuffington/PHP-Nuke-Titanium | includes/wysiwyg/ckeditor/plugins/magicline/lang/he.js | 268 | /**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'magicline', 'he', {
title: 'הכנס פסקה כאן'
} );
| gpl-3.0 |
resamsel/translatr | app/models/Scope.java | 2195 | package models;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
/**
* @author resamsel
* @version 21 Oct 2016
*/
public enum Scope {
UserRead(ScopeSection.User, ScopeType.Read),
UserWrite(ScopeSection.User, ScopeType.Write),
AccessTokenRead(ScopeSection.AccessToken, ScopeType.Read),
AccessTokenWrite(ScopeSection.AccessToken, ScopeType.Write),
ProjectRead(ScopeSection.Project, ScopeType.Read),
ProjectWrite(ScopeSection.Project, ScopeType.Write),
LocaleRead(ScopeSection.Locale, ScopeType.Read),
LocaleWrite(ScopeSection.Locale, ScopeType.Write),
KeyRead(ScopeSection.Key, ScopeType.Read),
KeyWrite(ScopeSection.Key, ScopeType.Write),
MessageRead(ScopeSection.Message, ScopeType.Read),
MessageWrite(ScopeSection.Message, ScopeType.Write),
MemberRead(ScopeSection.Member, ScopeType.Read),
MemberWrite(ScopeSection.Member, ScopeType.Write),
NotificationRead(ScopeSection.Notification, ScopeType.Read),
NotificationWrite(ScopeSection.Notification, ScopeType.Write),
FeatureFlagRead(ScopeSection.FeatureFlag, ScopeType.Read),
FeatureFlagWrite(ScopeSection.FeatureFlag, ScopeType.Write);
private static final Map<String, Scope> MAP = new HashMap<>();
private final ScopeSection section;
private final ScopeType type;
static {
for (Scope scope : Scope.values())
MAP.put(scope.scope(), scope);
}
/**
*
*/
Scope(ScopeSection section, ScopeType type) {
this.section = section;
this.type = type;
}
@JsonValue
public String scope() {
return String.format("%s:%s", type, section).toLowerCase();
}
public ScopeSection getSection() {
return section;
}
public ScopeType getType() {
return type;
}
public static Scope fromString(String scope) {
return MAP.get(scope);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("%s:%s", type.name().toLowerCase(), section.name().toLowerCase());
}
public static void main(String[] args) {
Stream.of(Scope.values()).forEach(scope -> System.out.printf("Scope.%s,%n", scope.name()));
}
}
| gpl-3.0 |
dpendl00/headphones | headphones/cache.py | 15931 | # This file is part of Headphones.
#
# Headphones 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.
#
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
import os
import glob
import urllib
import headphones
from headphones import db, helpers, logger, lastfm, request
LASTFM_API_KEY = "690e1ed3bc00bc91804cd8f7fe5ed6d4"
class Cache(object):
"""
This class deals with getting, storing and serving up artwork (album
art, artist images, etc) and info/descriptions (album info, artist descrptions)
to and from the cache folder. This can be called from within a web interface,
for example, using the helper functions getInfo(id) and getArtwork(id), to utilize the cached
images rather than having to retrieve them every time the page is reloaded.
So you can call cache.getArtwork(id) which will return an absolute path
to the image file on the local machine, or if the cache directory
doesn't exist, or can not be written to, it will return a url to the image.
Call cache.getInfo(id) to grab the artist/album info; will return the text description
The basic format for art in the cache is <musicbrainzid>.<date>.<ext>
and for info it is <musicbrainzid>.<date>.txt
"""
path_to_art_cache = os.path.join(headphones.CACHE_DIR, 'artwork')
def __init__(self):
self.id = None
self.id_type = None # 'artist' or 'album' - set automatically depending on whether ArtistID or AlbumID is passed
self.query_type = None # 'artwork','thumb' or 'info' - set automatically
self.artwork_files = []
self.thumb_files = []
self.artwork_errors = False
self.artwork_url = None
self.thumb_errors = False
self.thumb_url = None
self.info_summary = None
self.info_content = None
def _findfilesstartingwith(self,pattern,folder):
files = []
if os.path.exists(folder):
for fname in os.listdir(folder):
if fname.startswith(pattern):
files.append(os.path.join(folder,fname))
return files
def _exists(self, type):
self.artwork_files = []
self.thumb_files = []
if type == 'artwork':
self.artwork_files = self._findfilesstartingwith(self.id,self.path_to_art_cache)
if self.artwork_files:
return True
else:
return False
elif type == 'thumb':
self.thumb_files = self._findfilesstartingwith("T_" + self.id,self.path_to_art_cache)
if self.thumb_files:
return True
else:
return False
def _get_age(self, date):
# There's probably a better way to do this
split_date = date.split('-')
days_old = int(split_date[0])*365 + int(split_date[1])*30 + int(split_date[2])
return days_old
def _is_current(self, filename=None, date=None):
if filename:
base_filename = os.path.basename(filename)
date = base_filename.split('.')[1]
# Calculate how old the cached file is based on todays date & file date stamp
# helpers.today() returns todays date in yyyy-mm-dd format
if self._get_age(helpers.today()) - self._get_age(date) < 30:
return True
else:
return False
def _get_thumb_url(self, data):
thumb_url = None
try:
images = data[self.id_type]['image']
except KeyError:
return None
for image in images:
if image['size'] == 'medium':
thumb_url = image['#text']
break
return thumb_url
def get_artwork_from_cache(self, ArtistID=None, AlbumID=None):
"""
Pass a musicbrainz id to this function (either ArtistID or AlbumID)
"""
self.query_type = 'artwork'
if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
else:
self.id = AlbumID
self.id_type = 'album'
if self._exists('artwork') and self._is_current(filename=self.artwork_files[0]):
return self.artwork_files[0]
else:
self._update_cache()
# If we failed to get artwork, either return the url or the older file
if self.artwork_errors and self.artwork_url:
return self.artwork_url
elif self._exists('artwork'):
return self.artwork_files[0]
else:
return None
def get_thumb_from_cache(self, ArtistID=None, AlbumID=None):
"""
Pass a musicbrainz id to this function (either ArtistID or AlbumID)
"""
self.query_type = 'thumb'
if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
else:
self.id = AlbumID
self.id_type = 'album'
if self._exists('thumb') and self._is_current(filename=self.thumb_files[0]):
return self.thumb_files[0]
else:
self._update_cache()
# If we failed to get artwork, either return the url or the older file
if self.thumb_errors and self.thumb_url:
return self.thumb_url
elif self._exists('thumb'):
return self.thumb_files[0]
else:
return None
def get_info_from_cache(self, ArtistID=None, AlbumID=None):
self.query_type = 'info'
myDB = db.DBConnection()
if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ArtistID=?', [self.id]).fetchone()
else:
self.id = AlbumID
self.id_type = 'album'
db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ReleaseGroupID=?', [self.id]).fetchone()
if not db_info or not db_info['LastUpdated'] or not self._is_current(date=db_info['LastUpdated']):
self._update_cache()
info_dict = { 'Summary' : self.info_summary, 'Content' : self.info_content }
return info_dict
else:
info_dict = { 'Summary' : db_info['Summary'], 'Content' : db_info['Content'] }
return info_dict
def get_image_links(self, ArtistID=None, AlbumID=None):
'''
Here we're just going to open up the last.fm url, grab the image links and return them
Won't save any image urls, or save the artwork in the cache. Useful for search results, etc.
'''
if ArtistID:
self.id_type = 'artist'
data = lastfm.request_lastfm("artist.getinfo", mbid=ArtistID, api_key=LASTFM_API_KEY)
if not data:
return
try:
image_url = data['artist']['image'][-1]['#text']
except (KeyError, IndexError):
logger.debug('No artist image found')
image_url = None
thumb_url = self._get_thumb_url(data)
if not thumb_url:
logger.debug('No artist thumbnail image found')
else:
self.id_type = 'album'
data = lastfm.request_lastfm("album.getinfo", mbid=AlbumID, api_key=LASTFM_API_KEY)
if not data:
return
try:
image_url = data['album']['image'][-1]['#text']
except (KeyError, IndexError):
logger.debug('No album image found on last.fm')
image_url = None
thumb_url = self._get_thumb_url(data)
if not thumb_url:
logger.debug('No album thumbnail image found on last.fm')
return {'artwork' : image_url, 'thumbnail' : thumb_url }
def _update_cache(self):
'''
Since we call the same url for both info and artwork, we'll update both at the same time
'''
myDB = db.DBConnection()
# Since lastfm uses release ids rather than release group ids for albums, we have to do a artist + album search for albums
if self.id_type == 'artist':
data = lastfm.request_lastfm("artist.getinfo", mbid=self.id, api_key=LASTFM_API_KEY)
if not data:
return
try:
self.info_summary = data['artist']['bio']['summary']
except KeyError:
logger.debug('No artist bio summary found')
self.info_summary = None
try:
self.info_content = data['artist']['bio']['content']
except KeyError:
logger.debug('No artist bio found')
self.info_content = None
try:
image_url = data['artist']['image'][-1]['#text']
except KeyError:
logger.debug('No artist image found')
image_url = None
thumb_url = self._get_thumb_url(data)
if not thumb_url:
logger.debug('No artist thumbnail image found')
else:
dbartist = myDB.action('SELECT ArtistName, AlbumTitle FROM albums WHERE AlbumID=?', [self.id]).fetchone()
data = lastfm.request_lastfm("album.getinfo", artist=dbartist['ArtistName'], album=dbartist['AlbumTitle'], api_key=LASTFM_API_KEY)
if not data:
return
try:
self.info_summary = data['album']['wiki']['summary']
except KeyError:
logger.debug('No album summary found')
self.info_summary = None
try:
self.info_content = data['album']['wiki']['content']
except KeyError:
logger.debug('No album infomation found')
self.info_content = None
try:
image_url = data['album']['image'][-1]['#text']
except KeyError:
logger.debug('No album image link found')
image_url = None
thumb_url = self._get_thumb_url(data)
if not thumb_url:
logger.debug('No album thumbnail image found')
#Save the content & summary to the database no matter what if we've opened up the url
if self.id_type == 'artist':
controlValueDict = {"ArtistID": self.id}
else:
controlValueDict = {"ReleaseGroupID": self.id}
newValueDict = {"Summary": self.info_summary,
"Content": self.info_content,
"LastUpdated": helpers.today()}
myDB.upsert("descriptions", newValueDict, controlValueDict)
# Save the image URL to the database
if image_url:
if self.id_type == 'artist':
myDB.action('UPDATE artists SET ArtworkURL=? WHERE ArtistID=?', [image_url, self.id])
else:
myDB.action('UPDATE albums SET ArtworkURL=? WHERE AlbumID=?', [image_url, self.id])
# Save the thumb URL to the database
if thumb_url:
if self.id_type == 'artist':
myDB.action('UPDATE artists SET ThumbURL=? WHERE ArtistID=?', [thumb_url, self.id])
else:
myDB.action('UPDATE albums SET ThumbURL=? WHERE AlbumID=?', [thumb_url, self.id])
# Should we grab the artwork here if we're just grabbing thumbs or info?? Probably not since the files can be quite big
if image_url and self.query_type == 'artwork':
artwork = request.request_content(image_url, timeout=20)
if artwork:
# Make sure the artwork dir exists:
if not os.path.isdir(self.path_to_art_cache):
try:
os.makedirs(self.path_to_art_cache)
except Exception, e:
logger.error('Unable to create artwork cache dir. Error: %s', e)
self.artwork_errors = True
self.artwork_url = image_url
#Delete the old stuff
for artwork_file in self.artwork_files:
try:
os.remove(artwork_file)
except:
logger.error('Error deleting file from the cache: %s', artwork_file)
ext = os.path.splitext(image_url)[1]
artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + ext)
try:
with open(artwork_path, 'wb') as f:
f.write(artwork)
except IOError as e:
logger.error('Unable to write to the cache dir: %s', e)
self.artwork_errors = True
self.artwork_url = image_url
# Grab the thumbnail as well if we're getting the full artwork (as long as it's missing/outdated
if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])):
artwork = request.request_content(thumb_url, timeout=20)
if artwork:
# Make sure the artwork dir exists:
if not os.path.isdir(self.path_to_art_cache):
try:
os.makedirs(self.path_to_art_cache)
except Exception as e:
logger.error('Unable to create artwork cache dir. Error: %s' + e)
self.thumb_errors = True
self.thumb_url = thumb_url
#Delete the old stuff
for thumb_file in self.thumb_files:
try:
os.remove(thumb_file)
except Exception as e:
logger.error('Error deleting file from the cache: %s', thumb_file)
ext = os.path.splitext(image_url)[1]
thumb_path = os.path.join(self.path_to_art_cache, 'T_' + self.id + '.' + helpers.today() + ext)
try:
with open(thumb_path, 'wb') as f:
f.write(artwork)
except IOError as e:
logger.error('Unable to write to the cache dir: %s', e)
self.thumb_errors = True
self.thumb_url = image_url
def getArtwork(ArtistID=None, AlbumID=None):
c = Cache()
artwork_path = c.get_artwork_from_cache(ArtistID, AlbumID)
if not artwork_path:
return None
if artwork_path.startswith('http://'):
return artwork_path
else:
artwork_file = os.path.basename(artwork_path)
return "cache/artwork/" + artwork_file
def getThumb(ArtistID=None, AlbumID=None):
c = Cache()
artwork_path = c.get_thumb_from_cache(ArtistID, AlbumID)
if not artwork_path:
return None
if artwork_path.startswith('http://'):
return artwork_path
else:
thumbnail_file = os.path.basename(artwork_path)
return "cache/artwork/" + thumbnail_file
def getInfo(ArtistID=None, AlbumID=None):
c = Cache()
info_dict = c.get_info_from_cache(ArtistID, AlbumID)
return info_dict
def getImageLinks(ArtistID=None, AlbumID=None):
c = Cache()
image_links = c.get_image_links(ArtistID, AlbumID)
return image_links
| gpl-3.0 |
sangster/knowtime-server | config/environments/development.rb | 1237 | BustedRuby::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.cache_store = :dalli_store, "127.0.0.1:11211"
config.action_controller.perform_caching = true
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
#config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
config.active_support.encode_big_decimal_as_string = false
end
| gpl-3.0 |
pantelis60/L2Scripts_Underground | commons/src/main/java/l2s/commons/text/PrintfFormat.java | 96833 | //
// (c) 2000 Sun Microsystems, Inc.
// ALL RIGHTS RESERVED
//
// License Grant-
//
//
// Permission to use, copy, modify, and distribute this Software and its
// documentation for NON-COMMERCIAL or COMMERCIAL purposes and without fee is
// hereby granted.
//
// This Software is provided "AS IS". All express warranties, including any
// implied warranty of merchantability, satisfactory quality, fitness for a
// particular purpose, or non-infringement, are disclaimed, except to the extent
// that such disclaimers are held to be legally invalid.
//
// You acknowledge that Software is not designed, licensed or intended for use in
// the design, construction, operation or maintenance of any nuclear facility
// ("High Risk Activities"). Sun disclaims any express or implied warranty of
// fitness for such uses.
//
// Please refer to the file http://www.sun.com/policies/trademarks/ for further
// important trademark information and to
// http://java.sun.com/nav/business/index.html for further important licensing
// information for the Java Technology.
//
package l2s.commons.text;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* PrintfFormat allows the formatting of an array of
* objects embedded within a string. Primitive types
* must be passed using wrapper types. The formatting
* is controlled by a control string.
*<p>
* A control string is a Java string that contains a
* control specification. The control specification
* starts at the first percent sign (%) in the string,
* provided that this percent sign
*<ol>
*<li>is not escaped protected by a matching % or is
* not an escape % character,
*<li>is not at the end of the format string, and
*<li>precedes a sequence of characters that parses as
* a valid control specification.
*</ol>
*</p><p>
* A control specification usually takes the form:
*<pre> % ['-+ #0]* [0..9]* { . [0..9]* }+
* { [hlL] }+ [idfgGoxXeEcs]
*</pre>
* There are variants of this basic form that are
* discussed below.</p>
*<p>
* The format is composed of zero or more directives
* defined as follows:
*<ul>
*<li>ordinary characters, which are simply copied to
* the output stream;
*<li>escape sequences, which represent non-graphic
* characters; and
*<li>conversion specifications, each of which
* results in the fetching of zero or more arguments.
*</ul></p>
*<p>
* The results are undefined if there are insufficient
* arguments for the format. Usually an unchecked
* exception will be thrown. If the format is
* exhausted while arguments remain, the excess
* arguments are evaluated but are otherwise ignored.
* In format strings containing the % form of
* conversion specifications, each argument in the
* argument list is used exactly once.</p>
* <p>
* Conversions can be applied to the <code>n</code>th
* argument after the format in the argument list,
* rather than to the next unused argument. In this
* case, the conversion characer % is replaced by the
* sequence %<code>n</code>$, where <code>n</code> is
* a decimal integer giving the position of the
* argument in the argument list.</p>
* <p>
* In format strings containing the %<code>n</code>$
* form of conversion specifications, each argument
* in the argument list is used exactly once.</p>
*
*<h4>Escape Sequences</h4>
*<p>
* The following table lists escape sequences and
* associated actions on display devices capable of
* the action.
*<table>
*<tr><th align=left>Sequence</th>
* <th align=left>Name</th>
* <th align=left>Description</th></tr>
*<tr><td>\\</td><td>backlash</td><td>None.
*</td></tr>
*<tr><td>\a</td><td>alert</td><td>Attempts to alert
* the user through audible or visible
* notification.
*</td></tr>
*<tr><td>\b</td><td>backspace</td><td>Moves the
* printing position to one column before
* the current position, unless the
* current position is the start of a line.
*</td></tr>
*<tr><td>\f</td><td>form-feed</td><td>Moves the
* printing position to the initial
* printing position of the next logical
* page.
*</td></tr>
*<tr><td>\n</td><td>newline</td><td>Moves the
* printing position to the start of the
* next line.
*</td></tr>
*<tr><td>\r</td><td>carriage-return</td><td>Moves
* the printing position to the start of
* the current line.
*</td></tr>
*<tr><td>\t</td><td>tab</td><td>Moves the printing
* position to the next implementation-
* defined horizontal tab position.
*</td></tr>
*<tr><td>\v</td><td>vertical-tab</td><td>Moves the
* printing position to the start of the
* next implementation-defined vertical
* tab position.
*</td></tr>
*</table></p>
*<h4>Conversion Specifications</h4>
*<p>
* Each conversion specification is introduced by
* the percent sign character (%). After the character
* %, the following appear in sequence:</p>
*<p>
* Zero or more flags (in any order), which modify the
* meaning of the conversion specification.</p>
*<p>
* An optional minimum field width. If the converted
* value has fewer characters than the field width, it
* will be padded with spaces by default on the left;
* t will be padded on the right, if the left-
* adjustment flag (-), described below, is given to
* the field width. The field width takes the form
* of a decimal integer. If the conversion character
* is s, the field width is the the minimum number of
* characters to be printed.</p>
*<p>
* An optional precision that gives the minumum number
* of digits to appear for the d, i, o, x or X
* conversions (the field is padded with leading
* zeros); the number of digits to appear after the
* radix character for the e, E, and f conversions,
* the maximum number of significant digits for the g
* and G conversions; or the maximum number of
* characters to be written from a string is s and S
* conversions. The precision takes the form of an
* optional decimal digit string, where a null digit
* string is treated as 0. If a precision appears
* with a c conversion character the precision is
* ignored.
* </p>
*<p>
* An optional h specifies that a following d, i, o,
* x, or X conversion character applies to a type
* short argument (the argument will be promoted
* according to the integral promotions and its value
* converted to type short before printing).</p>
*<p>
* An optional l (ell) specifies that a following
* d, i, o, x, or X conversion character applies to a
* type long argument.</p>
*<p>
* A field width or precision may be indicated by an
* asterisk (*) instead of a digit string. In this
* case, an integer argument supplised the field width
* precision. The argument that is actually converted
* is not fetched until the conversion letter is seen,
* so the the arguments specifying field width or
* precision must appear before the argument (if any)
* to be converted. If the precision argument is
* negative, it will be changed to zero. A negative
* field width argument is taken as a - flag, followed
* by a positive field width.</p>
* <p>
* In format strings containing the %<code>n</code>$
* form of a conversion specification, a field width
* or precision may be indicated by the sequence
* *<code>m</code>$, where m is a decimal integer
* giving the position in the argument list (after the
* format argument) of an integer argument containing
* the field width or precision.</p>
* <p>
* The format can contain either numbered argument
* specifications (that is, %<code>n</code>$ and
* *<code>m</code>$), or unnumbered argument
* specifications (that is % and *), but normally not
* both. The only exception to this is that %% can
* be mixed with the %<code>n</code>$ form. The
* results of mixing numbered and unnumbered argument
* specifications in a format string are undefined.</p>
*
*<h4>Flag Characters</h4>
*<p>
* The flags and their meanings are:</p>
*<dl>
* <dt>'<dd> integer portion of the result of a
* decimal conversion (%i, %d, %f, %g, or %G) will
* be formatted with thousands' grouping
* characters. For other conversions the flag
* is ignored. The non-monetary grouping
* character is used.
* <dt>-<dd> result of the conversion is left-justified
* within the field. (It will be right-justified
* if this flag is not specified).</td></tr>
* <dt>+<dd> result of a signed conversion always
* begins with a sign (+ or -). (It will begin
* with a sign only when a negative value is
* converted if this flag is not specified.)
* <dt><space><dd> If the first character of a
* signed conversion is not a sign, a space
* character will be placed before the result.
* This means that if the space character and +
* flags both appear, the space flag will be
* ignored.
* <dt>#<dd> value is to be converted to an alternative
* form. For c, d, i, and s conversions, the flag
* has no effect. For o conversion, it increases
* the precision to force the first digit of the
* result to be a zero. For x or X conversion, a
* non-zero result has 0x or 0X prefixed to it,
* respectively. For e, E, f, g, and G
* conversions, the result always contains a radix
* character, even if no digits follow the radix
* character (normally, a decimal point appears in
* the result of these conversions only if a digit
* follows it). For g and G conversions, trailing
* zeros will not be removed from the result as
* they normally are.
* <dt>0<dd> d, i, o, x, X, e, E, f, g, and G
* conversions, leading zeros (following any
* indication of sign or base) are used to pad to
* the field width; no space padding is
* performed. If the 0 and - flags both appear,
* the 0 flag is ignored. For d, i, o, x, and X
* conversions, if a precision is specified, the
* 0 flag will be ignored. For c conversions,
* the flag is ignored.
*</dl>
*
*<h4>Conversion Characters</h4>
*<p>
* Each conversion character results in fetching zero
* or more arguments. The results are undefined if
* there are insufficient arguments for the format.
* Usually, an unchecked exception will be thrown.
* If the format is exhausted while arguments remain,
* the excess arguments are ignored.</p>
*
*<p>
* The conversion characters and their meanings are:
*</p>
*<dl>
* <dt>d,i<dd>The int argument is converted to a
* signed decimal in the style [-]dddd. The
* precision specifies the minimum number of
* digits to appear; if the value being
* converted can be represented in fewer
* digits, it will be expanded with leading
* zeros. The default precision is 1. The
* result of converting 0 with an explicit
* precision of 0 is no characters.
* <dt>o<dd> The int argument is converted to unsigned
* octal format in the style ddddd. The
* precision specifies the minimum number of
* digits to appear; if the value being
* converted can be represented in fewer
* digits, it will be expanded with leading
* zeros. The default precision is 1. The
* result of converting 0 with an explicit
* precision of 0 is no characters.
* <dt>x<dd> The int argument is converted to unsigned
* hexadecimal format in the style dddd; the
* letters abcdef are used. The precision
* specifies the minimum numberof digits to
* appear; if the value being converted can be
* represented in fewer digits, it will be
* expanded with leading zeros. The default
* precision is 1. The result of converting 0
* with an explicit precision of 0 is no
* characters.
* <dt>X<dd> Behaves the same as the x conversion
* character except that letters ABCDEF are
* used instead of abcdef.
* <dt>f<dd> The floating point number argument is
* written in decimal notation in the style
* [-]ddd.ddd, where the number of digits after
* the radix character (shown here as a decimal
* point) is equal to the precision
* specification. A Locale is used to determine
* the radix character to use in this format.
* If the precision is omitted from the
* argument, six digits are written after the
* radix character; if the precision is
* explicitly 0 and the # flag is not specified,
* no radix character appears. If a radix
* character appears, at least 1 digit appears
* before it. The value is rounded to the
* appropriate number of digits.
* <dt>e,E<dd>The floating point number argument is
* written in the style [-]d.ddde{+-}dd
* (the symbols {+-} indicate either a plus or
* minus sign), where there is one digit before
* the radix character (shown here as a decimal
* point) and the number of digits after it is
* equal to the precision. A Locale is used to
* determine the radix character to use in this
* format. When the precision is missing, six
* digits are written after the radix character;
* if the precision is 0 and the # flag is not
* specified, no radix character appears. The
* E conversion will produce a number with E
* instead of e introducing the exponent. The
* exponent always contains at least two digits.
* However, if the value to be written requires
* an exponent greater than two digits,
* additional exponent digits are written as
* necessary. The value is rounded to the
* appropriate number of digits.
* <dt>g,G<dd>The floating point number argument is
* written in style f or e (or in sytle E in the
* case of a G conversion character), with the
* precision specifying the number of
* significant digits. If the precision is
* zero, it is taken as one. The style used
* depends on the value converted: style e
* (or E) will be used only if the exponent
* resulting from the conversion is less than
* -4 or greater than or equal to the precision.
* Trailing zeros are removed from the result.
* A radix character appears only if it is
* followed by a digit.
* <dt>c,C<dd>The integer argument is converted to a
* char and the result is written.
*
* <dt>s,S<dd>The argument is taken to be a string and
* bytes from the string are written until the
* end of the string or the number of bytes
* indicated by the precision specification of
* the argument is reached. If the precision
* is omitted from the argument, it is taken to
* be infinite, so all characters up to the end
* of the string are written.
* <dt>%<dd>Write a % character; no argument is
* converted.
*</dl>
*<p>
* If a conversion specification does not match one of
* the above forms, an IllegalArgumentException is
* thrown and the instance of PrintfFormat is not
* created.</p>
*<p>
* If a floating point value is the internal
* representation for infinity, the output is
* [+]Infinity, where Infinity is either Infinity or
* Inf, depending on the desired output string length.
* Printing of the sign follows the rules described
* above.</p>
*<p>
* If a floating point value is the internal
* representation for "not-a-number," the output is
* [+]NaN. Printing of the sign follows the rules
* described above.</p>
*<p>
* In no case does a non-existent or small field width
* cause truncation of a field; if the result of a
* conversion is wider than the field width, the field
* is simply expanded to contain the conversion result.
*</p>
*<p>
* The behavior is like printf. One exception is that
* the minimum number of exponent digits is 3 instead
* of 2 for e and E formats when the optional L is used
* before the e, E, g, or G conversion character. The
* optional L does not imply conversion to a long long
* double. </p>
* <p>
* The biggest divergence from the C printf
* specification is in the use of 16 bit characters.
* This allows the handling of characters beyond the
* small ASCII character set and allows the utility to
* interoperate correctly with the rest of the Java
* runtime environment.</p>
*<p>
* Omissions from the C printf specification are
* numerous. All the known omissions are present
* because Java never uses bytes to represent
* characters and does not have pointers:</p>
*<ul>
* <li>%c is the same as %C.
* <li>%s is the same as %S.
* <li>u, p, and n conversion characters.
* <li>%ws format.
* <li>h modifier applied to an n conversion character.
* <li>l (ell) modifier applied to the c, n, or s
* conversion characters.
* <li>ll (ell ell) modifier to d, i, o, u, x, or X
* conversion characters.
* <li>ll (ell ell) modifier to an n conversion
* character.
* <li>c, C, d,i,o,u,x, and X conversion characters
* apply to Byte, Character, Short, Integer, Long
* types.
* <li>f, e, E, g, and G conversion characters apply
* to Float and Double types.
* <li>s and S conversion characters apply to String
* types.
* <li>All other reference types can be formatted
* using the s or S conversion characters only.
*</ul>
* <p>
* Most of this specification is quoted from the Unix
* man page for the sprintf utility.</p>
*
* @author Allan Jacobs
* @version 1
* Release 1: Initial release.
* Release 2: Asterisk field widths and precisions
* %n$ and *m$
* Bug fixes
* g format fix (2 digits in e form corrupt)
* rounding in f format implemented
* round up when digit not printed is 5
* formatting of -0.0f
* round up/down when last digits are 50000...
*/
public class PrintfFormat {
/**
* Constructs an array of control specifications
* possibly preceded, separated, or followed by
* ordinary strings. Control strings begin with
* unpaired percent signs. A pair of successive
* percent signs designates a single percent sign in
* the format.
* @param fmtArg Control string.
* @exception IllegalArgumentException if the control
* string is null, zero length, or otherwise
* malformed.
*/
public PrintfFormat(String fmtArg)
throws IllegalArgumentException {
this(Locale.getDefault(),fmtArg);
}
/**
* Constructs an array of control specifications
* possibly preceded, separated, or followed by
* ordinary strings. Control strings begin with
* unpaired percent signs. A pair of successive
* percent signs designates a single percent sign in
* the format.
* @param fmtArg Control string.
* @exception IllegalArgumentException if the control
* string is null, zero length, or otherwise
* malformed.
*/
public PrintfFormat(Locale locale,String fmtArg)
throws IllegalArgumentException {
dfs = new DecimalFormatSymbols(locale);
int ePos=0;
ConversionSpecification sFmt=null;
String unCS = this.nonControl(fmtArg,0);
if (unCS!=null) {
sFmt = new ConversionSpecification();
sFmt.setLiteral(unCS);
vFmt.add(sFmt);
}
while(cPos!=-1 && cPos<fmtArg.length()) {
for (ePos=cPos+1; ePos<fmtArg.length();
ePos++) {
char c=0;
c = fmtArg.charAt(ePos);
if (c == 'i') break;
if (c == 'd') break;
if (c == 'f') break;
if (c == 'g') break;
if (c == 'G') break;
if (c == 'o') break;
if (c == 'x') break;
if (c == 'X') break;
if (c == 'e') break;
if (c == 'E') break;
if (c == 'c') break;
if (c == 's') break;
if (c == '%') break;
}
ePos=Math.min(ePos+1,fmtArg.length());
sFmt = new ConversionSpecification(
fmtArg.substring(cPos,ePos));
vFmt.add(sFmt);
unCS = this.nonControl(fmtArg,ePos);
if (unCS!=null) {
sFmt = new ConversionSpecification();
sFmt.setLiteral(unCS);
vFmt.add(sFmt);
}
}
}
/**
* Return a substring starting at
* <code>start</code> and ending at either the end
* of the String <code>s</code>, the next unpaired
* percent sign, or at the end of the String if the
* last character is a percent sign.
* @param s Control string.
* @param start Position in the string
* <code>s</code> to begin looking for the start
* of a control string.
* @return the substring from the start position
* to the beginning of the control string.
*/
private String nonControl(String s,int start) {
cPos=s.indexOf("%",start);
if (cPos==-1) cPos=s.length();
return s.substring(start,cPos);
}
/**
* Format an array of objects. Byte, Short,
* Integer, Long, Float, Double, and Character
* arguments are treated as wrappers for primitive
* types.
* @param o The array of objects to format.
* @return The formatted String.
*/
public String sprintf(Object... o) {
char c = 0;
int i=0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else {
if (cs.isPositionalSpecification()) {
i=cs.getArgumentPosition()-1;
if (cs.isPositionalFieldWidth()) {
int ifw=cs.getArgumentPositionForFieldWidth()-1;
cs.setFieldWidthWithArg(((Integer)o[ifw]).intValue());
}
if (cs.isPositionalPrecision()) {
int ipr=cs.getArgumentPositionForPrecision()-1;
cs.setPrecisionWithArg(((Integer)o[ipr]).intValue());
}
}
else {
if (cs.isVariableFieldWidth()) {
cs.setFieldWidthWithArg(((Integer)o[i]).intValue());
i++;
}
if (cs.isVariablePrecision()) {
cs.setPrecisionWithArg(((Integer)o[i]).intValue());
i++;
}
}
if (o[i] instanceof Byte)
sb.append(cs.internalsprintf(
((Byte)o[i]).byteValue()));
else if (o[i] instanceof Short)
sb.append(cs.internalsprintf(
((Short)o[i]).shortValue()));
else if (o[i] instanceof Integer)
sb.append(cs.internalsprintf(
((Integer)o[i]).intValue()));
else if (o[i] instanceof Long)
sb.append(cs.internalsprintf(
((Long)o[i]).longValue()));
else if (o[i] instanceof Float)
sb.append(cs.internalsprintf(
((Float)o[i]).floatValue()));
else if (o[i] instanceof Double)
sb.append(cs.internalsprintf(
((Double)o[i]).doubleValue()));
else if (o[i] instanceof Character)
sb.append(cs.internalsprintf(
((Character)o[i]).charValue()));
else if (o[i] instanceof String)
sb.append(cs.internalsprintf(
(String)o[i]));
else
sb.append(cs.internalsprintf(
o[i]));
if (!cs.isPositionalSpecification())
i++;
}
}
return sb.toString();
}
/**
* Format nothing. Just use the control string.
* @return the formatted String.
*/
public String sprintf() {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
}
return sb.toString();
}
/**
* Format an int.
* @param x The int to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, G, s,
* or S.
*/
public String sprintf(int x)
throws IllegalArgumentException {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format an long.
* @param x The long to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, G, s,
* or S.
*/
public String sprintf(long x)
throws IllegalArgumentException {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format a double.
* @param x The double to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is c, C, s, S,
* d, d, x, X, or o.
*/
public String sprintf(double x)
throws IllegalArgumentException {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format a String.
* @param x The String to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
public String sprintf(String x)
throws IllegalArgumentException {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format an Object. Convert wrapper types to
* their primitive equivalents and call the
* appropriate internal formatting method. Convert
* Strings using an internal formatting method for
* Strings. Otherwise use the default formatter
* (use toString).
* @param x the Object to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is inappropriate for
* formatting an unwrapped value.
*/
public String sprintf(Object x)
throws IllegalArgumentException {
char c = 0;
StringBuilder sb=new StringBuilder();
for (ConversionSpecification cs : vFmt) {
c = cs.getConversionCharacter();
if (c=='\0') sb.append(cs.getLiteral());
else if (c=='%') sb.append("%");
else {
if (x instanceof Byte)
sb.append(cs.internalsprintf(
((Byte)x).byteValue()));
else if (x instanceof Short)
sb.append(cs.internalsprintf(
((Short)x).shortValue()));
else if (x instanceof Integer)
sb.append(cs.internalsprintf(
((Integer)x).intValue()));
else if (x instanceof Long)
sb.append(cs.internalsprintf(
((Long)x).longValue()));
else if (x instanceof Float)
sb.append(cs.internalsprintf(
((Float)x).floatValue()));
else if (x instanceof Double)
sb.append(cs.internalsprintf(
((Double)x).doubleValue()));
else if (x instanceof Character)
sb.append(cs.internalsprintf(
((Character)x).charValue()));
else if (x instanceof String)
sb.append(cs.internalsprintf(
(String)x));
else
sb.append(cs.internalsprintf(x));
}
}
return sb.toString();
}
/**
*<p>
* ConversionSpecification allows the formatting of
* a single primitive or object embedded within a
* string. The formatting is controlled by a
* format string. Only one Java primitive or
* object can be formatted at a time.
*<p>
* A format string is a Java string that contains
* a control string. The control string starts at
* the first percent sign (%) in the string,
* provided that this percent sign
*<ol>
*<li>is not escaped protected by a matching % or
* is not an escape % character,
*<li>is not at the end of the format string, and
*<li>precedes a sequence of characters that parses
* as a valid control string.
*</ol>
*<p>
* A control string takes the form:
*<pre> % ['-+ #0]* [0..9]* { . [0..9]* }+
* { [hlL] }+ [idfgGoxXeEcs]
*</pre>
*<p>
* The behavior is like printf. One (hopefully the
* only) exception is that the minimum number of
* exponent digits is 3 instead of 2 for e and E
* formats when the optional L is used before the
* e, E, g, or G conversion character. The
* optional L does not imply conversion to a long
* long double.
*/
private class ConversionSpecification {
/**
* Constructor. Used to prepare an instance
* to hold a literal, not a control string.
*/
ConversionSpecification() { }
/**
* Constructor for a conversion specification.
* The argument must begin with a % and end
* with the conversion character for the
* conversion specification.
* @param fmtArg String specifying the
* conversion specification.
* @exception IllegalArgumentException if the
* input string is null, zero length, or
* otherwise malformed.
*/
ConversionSpecification(String fmtArg)
throws IllegalArgumentException {
if (fmtArg==null)
throw new NullPointerException();
if (fmtArg.length()==0)
throw new IllegalArgumentException(
"Control strings must have positive"+
" lengths.");
if (fmtArg.charAt(0)=='%') {
fmt = fmtArg;
pos=1;
setArgPosition();
setFlagCharacters();
setFieldWidth();
setPrecision();
setOptionalHL();
if (setConversionCharacter()) {
if (pos==fmtArg.length()) {
if(leadingZeros&&leftJustify)
leadingZeros=false;
if(precisionSet&&leadingZeros){
if(conversionCharacter=='d'
||conversionCharacter=='i'
||conversionCharacter=='o'
||conversionCharacter=='x')
{
leadingZeros=false;
}
}
}
else
throw new IllegalArgumentException(
"Malformed conversion specification="+
fmtArg);
}
else
throw new IllegalArgumentException(
"Malformed conversion specification="+
fmtArg);
}
else
throw new IllegalArgumentException(
"Control strings must begin with %.");
}
/**
* Set the String for this instance.
* @param s the String to store.
*/
void setLiteral(String s) {
fmt = s;
}
/**
* Get the String for this instance. Translate
* any escape sequences.
*
* @return s the stored String.
*/
String getLiteral() {
StringBuilder sb=new StringBuilder();
int i=0;
while (i<fmt.length()) {
if (fmt.charAt(i)=='\\') {
i++;
if (i<fmt.length()) {
char c=fmt.charAt(i);
switch(c) {
case 'a':
sb.append((char)0x07);
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case 'n':
sb.append(System.getProperty("line.separator"));
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'v':
sb.append((char)0x0b);
break;
case '\\':
sb.append('\\');
break;
}
i++;
}
else
sb.append('\\');
}
else
i++;
}
return fmt;
}
/**
* Get the conversion character that tells what
* type of control character this instance has.
*
* @return the conversion character.
*/
char getConversionCharacter() {
return conversionCharacter;
}
/**
* Check whether the specifier has a variable
* field width that is going to be set by an
* argument.
* @return <code>true</code> if the conversion
* uses an * field width; otherwise
* <code>false</code>.
*/
boolean isVariableFieldWidth() {
return variableFieldWidth;
}
/**
* Set the field width with an argument. A
* negative field width is taken as a - flag
* followed by a positive field width.
* @param fw the field width.
*/
void setFieldWidthWithArg(int fw) {
if (fw<0) leftJustify = true;
fieldWidthSet = true;
fieldWidth = Math.abs(fw);
}
/**
* Check whether the specifier has a variable
* precision that is going to be set by an
* argument.
* @return <code>true</code> if the conversion
* uses an * precision; otherwise
* <code>false</code>.
*/
boolean isVariablePrecision() {
return variablePrecision;
}
/**
* Set the precision with an argument. A
* negative precision will be changed to zero.
* @param pr the precision.
*/
void setPrecisionWithArg(int pr) {
precisionSet = true;
precision = Math.max(pr,0);
}
/**
* Format an int argument using this conversion
* specification.
* @param s the int to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, or G.
*/
String internalsprintf(int s)
throws IllegalArgumentException {
String s2 = "";
switch(conversionCharacter) {
case 'd':
case 'i':
if (optionalh)
s2 = printDFormat((short)s);
else if (optionall)
s2 = printDFormat((long)s);
else
s2 = printDFormat(s);
break;
case 'x':
case 'X':
if (optionalh)
s2 = printXFormat((short)s);
else if (optionall)
s2 = printXFormat((long)s);
else
s2 = printXFormat(s);
break;
case 'o':
if (optionalh)
s2 = printOFormat((short)s);
else if (optionall)
s2 = printOFormat((long)s);
else
s2 = printOFormat(s);
break;
case 'c':
case 'C':
s2 = printCFormat((char)s);
break;
default:
throw new IllegalArgumentException(
"Cannot format a int with a format using a "+
conversionCharacter+
" conversion character.");
}
return s2;
}
/**
* Format a long argument using this conversion
* specification.
* @param s the long to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, or G.
*/
String internalsprintf(long s)
throws IllegalArgumentException {
String s2 = "";
switch(conversionCharacter) {
case 'd':
case 'i':
if (optionalh)
s2 = printDFormat((short)s);
else if (optionall)
s2 = printDFormat(s);
else
s2 = printDFormat((int)s);
break;
case 'x':
case 'X':
if (optionalh)
s2 = printXFormat((short)s);
else if (optionall)
s2 = printXFormat(s);
else
s2 = printXFormat((int)s);
break;
case 'o':
if (optionalh)
s2 = printOFormat((short)s);
else if (optionall)
s2 = printOFormat(s);
else
s2 = printOFormat((int)s);
break;
case 'c':
case 'C':
s2 = printCFormat((char)s);
break;
default:
throw new IllegalArgumentException(
"Cannot format a long with a format using a "+
conversionCharacter+" conversion character.");
}
return s2;
}
/**
* Format a double argument using this conversion
* specification.
* @param s the double to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is c, C, s, S, i, d,
* x, X, or o.
*/
String internalsprintf(double s)
throws IllegalArgumentException {
String s2 = "";
switch(conversionCharacter) {
case 'f':
s2 = printFFormat(s);
break;
case 'E':
case 'e':
s2 = printEFormat(s);
break;
case 'G':
case 'g':
s2 = printGFormat(s);
break;
default:
throw new IllegalArgumentException("Cannot "+
"format a double with a format using a "+
conversionCharacter+" conversion character.");
}
return s2;
}
/**
* Format a String argument using this conversion
* specification.
* @param s the String to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
String internalsprintf(String s)
throws IllegalArgumentException {
String s2 = "";
if(conversionCharacter=='s'
|| conversionCharacter=='S')
s2 = printSFormat(s);
else
throw new IllegalArgumentException("Cannot "+
"format a String with a format using a "+
conversionCharacter+" conversion character.");
return s2;
}
/**
* Format an Object argument using this conversion
* specification.
* @param s the Object to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
String internalsprintf(Object s) {
String s2 = "";
if(conversionCharacter=='s'
|| conversionCharacter=='S')
s2 = printSFormat(s.toString());
else
throw new IllegalArgumentException(
"Cannot format a String with a format using"+
" a "+conversionCharacter+
" conversion character.");
return s2;
}
/**
* For f format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both
* a '+' and a ' ' are specified, the blank flag
* is ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the number of digits
* to appear after the radix character. Padding is
* with trailing 0s.
*/
private char[] fFormatDigits(double x) {
// int defaultDigits=6;
String sx;
int i,j,k;
int n1In,n2In;
int expon=0;
boolean minusSign=false;
if (x>0.0)
sx = Double.toString(x);
else if (x<0.0) {
sx = Double.toString(-x);
minusSign=true;
}
else {
sx = Double.toString(x);
if (sx.charAt(0)=='-') {
minusSign=true;
sx=sx.substring(1);
}
}
int ePos = sx.indexOf('E');
int rPos = sx.indexOf('.');
if (rPos!=-1) n1In=rPos;
else if (ePos!=-1) n1In=ePos;
else n1In=sx.length();
if (rPos!=-1) {
if (ePos!=-1) n2In = ePos-rPos-1;
else n2In = sx.length()-rPos-1;
}
else
n2In = 0;
if (ePos!=-1) {
int ie=ePos+1;
expon=0;
if (sx.charAt(ie)=='-') {
for (++ie; ie<sx.length(); ie++)
if (sx.charAt(ie)!='0') break;
if (ie<sx.length())
expon=-Integer.parseInt(sx.substring(ie));
}
else {
if (sx.charAt(ie)=='+') ++ie;
for (; ie<sx.length(); ie++)
if (sx.charAt(ie)!='0') break;
if (ie<sx.length())
expon=Integer.parseInt(sx.substring(ie));
}
}
int p;
if (precisionSet) p = precision;
else p = defaultDigits-1;
char[] ca1 = sx.toCharArray();
char[] ca2 = new char[n1In+n2In];
char[] ca3,ca4,ca5;
for (j=0; j<n1In; j++)
ca2[j] = ca1[j];
i = j+1;
for (k=0; k<n2In; j++,i++,k++)
ca2[j] = ca1[i];
if (n1In+expon<=0) {
ca3 = new char[-expon+n2In];
for (j=0,k=0; k<(-n1In-expon); k++,j++)
ca3[j]='0';
for (i=0; i<(n1In+n2In); i++,j++)
ca3[j]=ca2[i];
}
else
ca3 = ca2;
boolean carry=false;
if (p<-expon+n2In) {
if (expon<0) i = p;
else i = p+n1In;
carry=checkForCarry(ca3,i);
if (carry)
carry=startSymbolicCarry(ca3,i-1,0);
}
if (n1In+expon<=0) {
ca4 = new char[2+p];
if (!carry) ca4[0]='0';
else ca4[0]='1';
if(alternateForm||!precisionSet||precision!=0){
ca4[1]='.';
for(i=0,j=2;i<Math.min(p,ca3.length);i++,j++)
ca4[j]=ca3[i];
for (; j<ca4.length; j++) ca4[j]='0';
}
}
else {
if (!carry) {
if(alternateForm||!precisionSet
||precision!=0)
ca4 = new char[n1In+expon+p+1];
else
ca4 = new char[n1In+expon];
j=0;
}
else {
if(alternateForm||!precisionSet
||precision!=0)
ca4 = new char[n1In+expon+p+2];
else
ca4 = new char[n1In+expon+1];
ca4[0]='1';
j=1;
}
for (i=0; i<Math.min(n1In+expon,ca3.length); i++,j++)
ca4[j]=ca3[i];
for (; i<n1In+expon; i++,j++)
ca4[j]='0';
if(alternateForm||!precisionSet||precision!=0){
ca4[j]='.'; j++;
for (k=0; i<ca3.length && k<p; i++,j++,k++)
ca4[j]=ca3[i];
for (; j<ca4.length; j++) ca4[j]='0';
}
}
int nZeros=0;
if (!leftJustify && leadingZeros) {
int xThousands=0;
if (thousands) {
int xlead=0;
if (ca4[0]=='+'||ca4[0]=='-'||ca4[0]==' ')
xlead=1;
int xdp=xlead;
for (; xdp<ca4.length; xdp++)
if (ca4[xdp]=='.') break;
xThousands=(xdp-xlead)/3;
}
if (fieldWidthSet)
nZeros = fieldWidth-ca4.length;
if ((!minusSign&&(leadingSign||leadingSpace))||minusSign)
nZeros--;
nZeros-=xThousands;
if (nZeros<0) nZeros=0;
}
j=0;
if ((!minusSign&&(leadingSign||leadingSpace))||minusSign) {
ca5 = new char[ca4.length+nZeros+1];
j++;
}
else
ca5 = new char[ca4.length+nZeros];
if (!minusSign) {
if (leadingSign) ca5[0]='+';
if (leadingSpace) ca5[0]=' ';
}
else
ca5[0]='-';
for (i=0; i<nZeros; i++,j++)
ca5[j]='0';
for (i=0; i<ca4.length; i++,j++) ca5[j]=ca4[i];
int lead=0;
if (ca5[0]=='+'||ca5[0]=='-'||ca5[0]==' ')
lead=1;
int dp=lead;
for (; dp<ca5.length; dp++)
if (ca5[dp]=='.') break;
int nThousands=(dp-lead)/3;
// Localize the decimal point.
if (dp<ca5.length)
ca5[dp]=dfs.getDecimalSeparator();
char[] ca6 = ca5;
if (thousands && nThousands>0) {
ca6 = new char[ca5.length+nThousands+lead];
ca6[0]=ca5[0];
for (i=lead,k=lead; i<dp; i++) {
if (i>0 && (dp-i)%3==0) {
// ca6[k]=',';
ca6[k]=dfs.getGroupingSeparator();
ca6[k+1]=ca5[i];
k+=2;
}
else {
ca6[k]=ca5[i]; k++;
}
}
for (; i<ca5.length; i++,k++) {
ca6[k]=ca5[i];
}
}
return ca6;
}
/**
* An intermediate routine on the way to creating
* an f format String. The method decides whether
* the input double value is an infinity,
* not-a-number, or a finite double and formats
* each type of input appropriately.
* @param x the double value to be formatted.
* @return the converted double value.
*/
private String fFormatString(double x) {
char[] ca6,ca7;
if (Double.isInfinite(x)) {
if (x==Double.POSITIVE_INFINITY) {
if (leadingSign) ca6 = "+Inf".toCharArray();
else if (leadingSpace)
ca6 = " Inf".toCharArray();
else ca6 = "Inf".toCharArray();
}
else
ca6 = "-Inf".toCharArray();
}
else if (Double.isNaN(x)) {
if (leadingSign) ca6 = "+NaN".toCharArray();
else if (leadingSpace)
ca6 = " NaN".toCharArray();
else ca6 = "NaN".toCharArray();
}
else
ca6 = fFormatDigits(x);
ca7 = applyFloatPadding(ca6,false);
return new String(ca7);
}
/**
* For e format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear after the radix character.
* Padding is with trailing 0s.
*
* The behavior is like printf. One (hopefully the
* only) exception is that the minimum number of
* exponent digits is 3 instead of 2 for e and E
* formats when the optional L is used before the
* e, E, g, or G conversion character. The optional
* L does not imply conversion to a long long
* double.
*/
private char[] eFormatDigits(double x,char eChar) {
char[] ca1,ca2,ca3;
// int defaultDigits=6;
String sx;
int i,j,k,p;
int expon=0;
int ePos,rPos,eSize;
boolean minusSign=false;
if (x>0.0)
sx = Double.toString(x);
else if (x<0.0) {
sx = Double.toString(-x);
minusSign=true;
}
else {
sx = Double.toString(x);
if (sx.charAt(0)=='-') {
minusSign=true;
sx=sx.substring(1);
}
}
ePos = sx.indexOf('E');
if (ePos==-1) ePos = sx.indexOf('e');
rPos = sx.indexOf('.');
if (ePos!=-1) {
int ie=ePos+1;
expon=0;
if (sx.charAt(ie)=='-') {
for (++ie; ie<sx.length(); ie++)
if (sx.charAt(ie)!='0') break;
if (ie<sx.length())
expon=-Integer.parseInt(sx.substring(ie));
}
else {
if (sx.charAt(ie)=='+') ++ie;
for (; ie<sx.length(); ie++)
if (sx.charAt(ie)!='0') break;
if (ie<sx.length())
expon=Integer.parseInt(sx.substring(ie));
}
}
if (rPos!=-1) expon += rPos-1;
if (precisionSet) p = precision;
else p = defaultDigits-1;
if (rPos!=-1 && ePos!=-1)
ca1=(sx.substring(0,rPos)+
sx.substring(rPos+1,ePos)).toCharArray();
else if (rPos!=-1)
ca1 = (sx.substring(0,rPos)+
sx.substring(rPos+1)).toCharArray();
else if (ePos!=-1)
ca1 = sx.substring(0,ePos).toCharArray();
else
ca1 = sx.toCharArray();
boolean carry=false;
int i0=0;
if (ca1[0]!='0')
i0 = 0;
else
for (i0=0; i0<ca1.length; i0++)
if (ca1[i0]!='0') break;
if (i0+p<ca1.length-1) {
carry=checkForCarry(ca1,i0+p+1);
if (carry)
carry = startSymbolicCarry(ca1,i0+p,i0);
if (carry) {
ca2 = new char[i0+p+1];
ca2[i0]='1';
for (j=0; j<i0; j++) ca2[j]='0';
for (i=i0,j=i0+1; j<p+1; i++,j++)
ca2[j] = ca1[i];
expon++;
ca1 = ca2;
}
}
if (Math.abs(expon)<100 && !optionalL) eSize=4;
else eSize=5;
if (alternateForm||!precisionSet||precision!=0)
ca2 = new char[2+p+eSize];
else
ca2 = new char[1+eSize];
if (ca1[0]!='0') {
ca2[0] = ca1[0];
j=1;
}
else {
for (j=1; j<(ePos==-1?ca1.length:ePos); j++)
if (ca1[j]!='0') break;
if ((ePos!=-1 && j<ePos)||
(ePos==-1 && j<ca1.length)) {
ca2[0] = ca1[j];
expon -= j;
j++;
}
else {
ca2[0]='0';
j=2;
}
}
if (alternateForm||!precisionSet||precision!=0) {
ca2[1] = '.';
i=2;
}
else
i=1;
for (k=0; k<p && j<ca1.length; j++,i++,k++)
ca2[i] = ca1[j];
for (;i<ca2.length-eSize; i++)
ca2[i] = '0';
ca2[i++] = eChar;
if (expon<0) ca2[i++]='-';
else ca2[i++]='+';
expon = Math.abs(expon);
if (expon>=100) {
switch(expon/100) {
case 1: ca2[i]='1'; break;
case 2: ca2[i]='2'; break;
case 3: ca2[i]='3'; break;
case 4: ca2[i]='4'; break;
case 5: ca2[i]='5'; break;
case 6: ca2[i]='6'; break;
case 7: ca2[i]='7'; break;
case 8: ca2[i]='8'; break;
case 9: ca2[i]='9'; break;
}
i++;
}
switch((expon%100)/10) {
case 0: ca2[i]='0'; break;
case 1: ca2[i]='1'; break;
case 2: ca2[i]='2'; break;
case 3: ca2[i]='3'; break;
case 4: ca2[i]='4'; break;
case 5: ca2[i]='5'; break;
case 6: ca2[i]='6'; break;
case 7: ca2[i]='7'; break;
case 8: ca2[i]='8'; break;
case 9: ca2[i]='9'; break;
}
i++;
switch(expon%10) {
case 0: ca2[i]='0'; break;
case 1: ca2[i]='1'; break;
case 2: ca2[i]='2'; break;
case 3: ca2[i]='3'; break;
case 4: ca2[i]='4'; break;
case 5: ca2[i]='5'; break;
case 6: ca2[i]='6'; break;
case 7: ca2[i]='7'; break;
case 8: ca2[i]='8'; break;
case 9: ca2[i]='9'; break;
}
int nZeros=0;
if (!leftJustify && leadingZeros) {
int xThousands=0;
if (thousands) {
int xlead=0;
if (ca2[0]=='+'||ca2[0]=='-'||ca2[0]==' ')
xlead=1;
int xdp=xlead;
for (; xdp<ca2.length; xdp++)
if (ca2[xdp]=='.') break;
xThousands=(xdp-xlead)/3;
}
if (fieldWidthSet)
nZeros = fieldWidth-ca2.length;
if ((!minusSign&&(leadingSign||leadingSpace))||minusSign)
nZeros--;
nZeros-=xThousands;
if (nZeros<0) nZeros=0;
}
j=0;
if ((!minusSign&&(leadingSign || leadingSpace))||minusSign) {
ca3 = new char[ca2.length+nZeros+1];
j++;
}
else
ca3 = new char[ca2.length+nZeros];
if (!minusSign) {
if (leadingSign) ca3[0]='+';
if (leadingSpace) ca3[0]=' ';
}
else
ca3[0]='-';
for (k=0; k<nZeros; j++,k++)
ca3[j]='0';
for (i=0; i<ca2.length && j<ca3.length; i++,j++)
ca3[j]=ca2[i];
int lead=0;
if (ca3[0]=='+'||ca3[0]=='-'||ca3[0]==' ')
lead=1;
int dp=lead;
for (; dp<ca3.length; dp++)
if (ca3[dp]=='.') break;
int nThousands=dp/3;
// Localize the decimal point.
if (dp < ca3.length)
ca3[dp] = dfs.getDecimalSeparator();
char[] ca4 = ca3;
if (thousands && nThousands>0) {
ca4 = new char[ca3.length+nThousands+lead];
ca4[0]=ca3[0];
for (i=lead,k=lead; i<dp; i++) {
if (i>0 && (dp-i)%3==0) {
// ca4[k]=',';
ca4[k]=dfs.getGroupingSeparator();
ca4[k+1]=ca3[i];
k+=2;
}
else {
ca4[k]=ca3[i]; k++;
}
}
for (; i<ca3.length; i++,k++)
ca4[k]=ca3[i];
}
return ca4;
}
/**
* Check to see if the digits that are going to
* be truncated because of the precision should
* force a round in the preceding digits.
* @param ca1 the array of digits
* @param icarry the index of the first digit that
* is to be truncated from the print
* @return <code>true</code> if the truncation forces
* a round that will change the print
*/
private boolean checkForCarry(char[] ca1,int icarry) {
boolean carry=false;
if (icarry<ca1.length) {
if (ca1[icarry]=='6'||ca1[icarry]=='7'
||ca1[icarry]=='8'||ca1[icarry]=='9') carry=true;
else if (ca1[icarry]=='5') {
int ii=icarry+1;
for (;ii<ca1.length; ii++)
if (ca1[ii]!='0') break;
carry=ii<ca1.length;
if (!carry&&icarry>0) {
carry=(ca1[icarry-1]=='1'||ca1[icarry-1]=='3'
||ca1[icarry-1]=='5'||ca1[icarry-1]=='7'
||ca1[icarry-1]=='9');
}
}
}
return carry;
}
/**
* Start the symbolic carry process. The process
* is not quite finished because the symbolic
* carry may change the length of the string and
* change the exponent (in e format).
* @param cLast index of the last digit changed
* by the round
* @param cFirst index of the first digit allowed
* to be changed by this phase of the round
* @return <code>true</code> if the carry forces
* a round that will change the print still
* more
*/
private boolean startSymbolicCarry(
char[] ca,int cLast,int cFirst) {
boolean carry=true;
for (int i=cLast; carry && i>=cFirst; i--) {
carry = false;
switch(ca[i]) {
case '0': ca[i]='1'; break;
case '1': ca[i]='2'; break;
case '2': ca[i]='3'; break;
case '3': ca[i]='4'; break;
case '4': ca[i]='5'; break;
case '5': ca[i]='6'; break;
case '6': ca[i]='7'; break;
case '7': ca[i]='8'; break;
case '8': ca[i]='9'; break;
case '9': ca[i]='0'; carry=true; break;
}
}
return carry;
}
/**
* An intermediate routine on the way to creating
* an e format String. The method decides whether
* the input double value is an infinity,
* not-a-number, or a finite double and formats
* each type of input appropriately.
* @param x the double value to be formatted.
* @param eChar an 'e' or 'E' to use in the
* converted double value.
* @return the converted double value.
*/
private String eFormatString(double x,char eChar) {
char[] ca4,ca5;
if (Double.isInfinite(x)) {
if (x==Double.POSITIVE_INFINITY) {
if (leadingSign) ca4 = "+Inf".toCharArray();
else if (leadingSpace)
ca4 = " Inf".toCharArray();
else ca4 = "Inf".toCharArray();
}
else
ca4 = "-Inf".toCharArray();
}
else if (Double.isNaN(x)) {
if (leadingSign) ca4 = "+NaN".toCharArray();
else if (leadingSpace)
ca4 = " NaN".toCharArray();
else ca4 = "NaN".toCharArray();
}
else
ca4 = eFormatDigits(x,eChar);
ca5 = applyFloatPadding(ca4,false);
return new String(ca5);
}
/**
* Apply zero or blank, left or right padding.
* @param ca4 array of characters before padding is
* finished
* @param noDigits NaN or signed Inf
* @return a padded array of characters
*/
private char[] applyFloatPadding(
char[] ca4,boolean noDigits) {
char[] ca5 = ca4;
if (fieldWidthSet) {
int i,j,nBlanks;
if (leftJustify) {
nBlanks = fieldWidth-ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length+nBlanks];
for (i=0; i<ca4.length; i++)
ca5[i] = ca4[i];
for (j=0; j<nBlanks; j++,i++)
ca5[i] = ' ';
}
}
else if (!leadingZeros || noDigits) {
nBlanks = fieldWidth-ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length+nBlanks];
for (i=0; i<nBlanks; i++)
ca5[i] = ' ';
for (j=0; j<ca4.length; i++,j++)
ca5[i] = ca4[j];
}
}
else if (leadingZeros) {
nBlanks = fieldWidth-ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length+nBlanks];
i=0; j=0;
if (ca4[0]=='-') { ca5[0]='-'; i++; j++; }
for (int k=0; k<nBlanks; i++,k++)
ca5[i] = '0';
for (; j<ca4.length; i++,j++)
ca5[i] = ca4[j];
}
}
}
return ca5;
}
/**
* Format method for the f conversion character.
* @param x the double to format.
* @return the formatted String.
*/
private String printFFormat(double x) {
return fFormatString(x);
}
/**
* Format method for the e or E conversion
* character.
* @param x the double to format.
* @return the formatted String.
*/
private String printEFormat(double x) {
if (conversionCharacter=='e')
return eFormatString(x,'e');
else
return eFormatString(x,'E');
}
/**
* Format method for the g conversion character.
*
* For g format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear after the radix character.
* Padding is with trailing 0s.
* @param x the double to format.
* @return the formatted String.
*/
private String printGFormat(double x) {
String sx,sy,sz,ret;
int savePrecision=precision;
int i;
char[] ca4,ca5;
if (Double.isInfinite(x)) {
if (x==Double.POSITIVE_INFINITY) {
if (leadingSign) ca4 = "+Inf".toCharArray();
else if (leadingSpace)
ca4 = " Inf".toCharArray();
else ca4 = "Inf".toCharArray();
}
else
ca4 = "-Inf".toCharArray();
}
else if (Double.isNaN(x)) {
if (leadingSign) ca4 = "+NaN".toCharArray();
else if (leadingSpace)
ca4 = " NaN".toCharArray();
else ca4 = "NaN".toCharArray();
}
else {
if (!precisionSet) precision=defaultDigits;
if (precision==0) precision=1;
int ePos=-1;
if (conversionCharacter=='g') {
sx = eFormatString(x,'e').trim();
ePos=sx.indexOf('e');
}
else {
sx = eFormatString(x,'E').trim();
ePos=sx.indexOf('E');
}
i=ePos+1;
int expon=0;
if (sx.charAt(i)=='-') {
for (++i; i<sx.length(); i++)
if (sx.charAt(i)!='0') break;
if (i<sx.length())
expon=-Integer.parseInt(sx.substring(i));
}
else {
if (sx.charAt(i)=='+') ++i;
for (; i<sx.length(); i++)
if (sx.charAt(i)!='0') break;
if (i<sx.length())
expon=Integer.parseInt(sx.substring(i));
}
// Trim trailing zeros.
// If the radix character is not followed by
// a digit, trim it, too.
if (!alternateForm) {
if (expon>=-4 && expon<precision)
sy = fFormatString(x).trim();
else
sy = sx.substring(0,ePos);
i=sy.length()-1;
for (; i>=0; i--)
if (sy.charAt(i)!='0') break;
if (i>=0 && sy.charAt(i)=='.') i--;
if (i==-1) sz="0";
else if (!Character.isDigit(sy.charAt(i)))
sz=sy.substring(0,i+1)+"0";
else sz=sy.substring(0,i+1);
if (expon>=-4 && expon<precision)
ret=sz;
else
ret=sz+sx.substring(ePos);
}
else {
if (expon>=-4 && expon<precision)
ret = fFormatString(x).trim();
else
ret = sx;
}
// leading space was trimmed off during
// construction
if (leadingSpace) if (x>=0) ret = " "+ret;
ca4 = ret.toCharArray();
}
// Pad with blanks or zeros.
ca5 = applyFloatPadding(ca4,false);
precision=savePrecision;
return new String(ca5);
}
/**
* Format method for the d conversion specifer and
* short argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printDFormat(short x) {
return printDFormat(Short.toString(x));
}
/**
* Format method for the d conversion character and
* long argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printDFormat(long x) {
return printDFormat(Long.toString(x));
}
/**
* Format method for the d conversion character and
* int argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printDFormat(int x) {
return printDFormat(Integer.toString(x));
}
/**
* Utility method for formatting using the d
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printDFormat(String sx) {
int nLeadingZeros=0;
int nBlanks=0,n=0;
int i=0,jFirst=0;
boolean neg = sx.charAt(0)=='-';
if (sx.equals("0")&&precisionSet&&precision==0)
sx="";
if (!neg) {
if (precisionSet && sx.length() < precision)
nLeadingZeros = precision-sx.length();
}
else {
if (precisionSet&&(sx.length()-1)<precision)
nLeadingZeros = precision-sx.length()+1;
}
if (nLeadingZeros<0) nLeadingZeros=0;
if (fieldWidthSet) {
nBlanks = fieldWidth-nLeadingZeros-sx.length();
if (!neg&&(leadingSign||leadingSpace))
nBlanks--;
}
if (nBlanks<0) nBlanks=0;
if (leadingSign) n++;
else if (leadingSpace) n++;
n += nBlanks;
n += nLeadingZeros;
n += sx.length();
char[] ca = new char[n];
if (leftJustify) {
if (neg) ca[i++] = '-';
else if (leadingSign) ca[i++] = '+';
else if (leadingSpace) ca[i++] = ' ';
char[] csx = sx.toCharArray();
jFirst = neg?1:0;
for (int j=0; j<nLeadingZeros; i++,j++)
ca[i]='0';
for (int j=jFirst; j<csx.length; j++,i++)
ca[i] = csx[j];
for (int j=0; j<nBlanks; i++,j++)
ca[i] = ' ';
}
else {
if (!leadingZeros) {
for (i=0; i<nBlanks; i++)
ca[i] = ' ';
if (neg) ca[i++] = '-';
else if (leadingSign) ca[i++] = '+';
else if (leadingSpace) ca[i++] = ' ';
}
else {
if (neg) ca[i++] = '-';
else if (leadingSign) ca[i++] = '+';
else if (leadingSpace) ca[i++] = ' ';
for (int j=0; j<nBlanks; j++,i++)
ca[i] = '0';
}
for (int j=0; j<nLeadingZeros; j++,i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
jFirst = neg?1:0;
for (int j=jFirst; j<csx.length; j++,i++)
ca[i] = csx[j];
}
return new String(ca);
}
/**
* Format method for the x conversion character and
* short argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printXFormat(short x) {
String sx=null;
if (x == Short.MIN_VALUE)
sx = "8000";
else if (x < 0) {
String t;
if (x==Short.MIN_VALUE)
t = "0";
else {
t = Integer.toString(
(~(-x-1))^Short.MIN_VALUE,16);
if (t.charAt(0)=='F'||t.charAt(0)=='f')
t = t.substring(16,32);
}
switch (t.length()) {
case 1:
sx = "800"+t;
break;
case 2:
sx = "80"+t;
break;
case 3:
sx = "8"+t;
break;
case 4:
switch (t.charAt(0)) {
case '1':
sx = "9"+t.substring(1,4);
break;
case '2':
sx = "a"+t.substring(1,4);
break;
case '3':
sx = "b"+t.substring(1,4);
break;
case '4':
sx = "c"+t.substring(1,4);
break;
case '5':
sx = "d"+t.substring(1,4);
break;
case '6':
sx = "e"+t.substring(1,4);
break;
case '7':
sx = "f"+t.substring(1,4);
break;
}
break;
}
}
else
sx = Integer.toString((int)x,16);
return printXFormat(sx);
}
/**
* Format method for the x conversion character and
* long argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printXFormat(long x) {
String sx=null;
if (x == Long.MIN_VALUE)
sx = "8000000000000000";
else if (x < 0) {
String t = Long.toString(
(~(-x-1))^Long.MIN_VALUE,16);
switch (t.length()) {
case 1:
sx = "800000000000000"+t;
break;
case 2:
sx = "80000000000000"+t;
break;
case 3:
sx = "8000000000000"+t;
break;
case 4:
sx = "800000000000"+t;
break;
case 5:
sx = "80000000000"+t;
break;
case 6:
sx = "8000000000"+t;
break;
case 7:
sx = "800000000"+t;
break;
case 8:
sx = "80000000"+t;
break;
case 9:
sx = "8000000"+t;
break;
case 10:
sx = "800000"+t;
break;
case 11:
sx = "80000"+t;
break;
case 12:
sx = "8000"+t;
break;
case 13:
sx = "800"+t;
break;
case 14:
sx = "80"+t;
break;
case 15:
sx = "8"+t;
break;
case 16:
switch (t.charAt(0)) {
case '1':
sx = "9"+t.substring(1,16);
break;
case '2':
sx = "a"+t.substring(1,16);
break;
case '3':
sx = "b"+t.substring(1,16);
break;
case '4':
sx = "c"+t.substring(1,16);
break;
case '5':
sx = "d"+t.substring(1,16);
break;
case '6':
sx = "e"+t.substring(1,16);
break;
case '7':
sx = "f"+t.substring(1,16);
break;
}
break;
}
}
else
sx = Long.toString(x,16);
return printXFormat(sx);
}
/**
* Format method for the x conversion character and
* int argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printXFormat(int x) {
String sx=null;
if (x == Integer.MIN_VALUE)
sx = "80000000";
else if (x < 0) {
String t = Integer.toString(
(~(-x-1))^Integer.MIN_VALUE,16);
switch (t.length()) {
case 1:
sx = "8000000"+t;
break;
case 2:
sx = "800000"+t;
break;
case 3:
sx = "80000"+t;
break;
case 4:
sx = "8000"+t;
break;
case 5:
sx = "800"+t;
break;
case 6:
sx = "80"+t;
break;
case 7:
sx = "8"+t;
break;
case 8:
switch (t.charAt(0)) {
case '1':
sx = "9"+t.substring(1,8);
break;
case '2':
sx = "a"+t.substring(1,8);
break;
case '3':
sx = "b"+t.substring(1,8);
break;
case '4':
sx = "c"+t.substring(1,8);
break;
case '5':
sx = "d"+t.substring(1,8);
break;
case '6':
sx = "e"+t.substring(1,8);
break;
case '7':
sx = "f"+t.substring(1,8);
break;
}
break;
}
}
else
sx = Integer.toString(x,16);
return printXFormat(sx);
}
/**
* Utility method for formatting using the x
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printXFormat(String sx) {
int nLeadingZeros = 0;
int nBlanks = 0;
if (sx.equals("0")&&precisionSet&&precision==0)
sx="";
if (precisionSet)
nLeadingZeros = precision-sx.length();
if (nLeadingZeros<0) nLeadingZeros=0;
if (fieldWidthSet) {
nBlanks = fieldWidth-nLeadingZeros-sx.length();
if (alternateForm) nBlanks = nBlanks - 2;
}
if (nBlanks<0) nBlanks=0;
int n=0;
if (alternateForm) n+=2;
n += nLeadingZeros;
n += sx.length();
n += nBlanks;
char[] ca = new char[n];
int i=0;
if (leftJustify) {
if (alternateForm) {
ca[i++]='0'; ca[i++]='x';
}
for (int j=0; j<nLeadingZeros; j++,i++)
ca[i]='0';
char[] csx = sx.toCharArray();
for (int j=0; j<csx.length; j++,i++)
ca[i] = csx[j];
for (int j=0; j<nBlanks; j++,i++)
ca[i] = ' ';
}
else {
if (!leadingZeros)
for (int j=0; j<nBlanks; j++,i++)
ca[i] = ' ';
if (alternateForm) {
ca[i++]='0'; ca[i++]='x';
}
if (leadingZeros)
for (int j=0; j<nBlanks; j++,i++)
ca[i] = '0';
for (int j=0; j<nLeadingZeros; j++,i++)
ca[i]='0';
char[] csx = sx.toCharArray();
for (int j=0; j<csx.length; j++,i++)
ca[i] = csx[j];
}
String caReturn=new String(ca);
if (conversionCharacter=='X')
caReturn = caReturn.toUpperCase();
return caReturn;
}
/**
* Format method for the o conversion character and
* short argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printOFormat(short x) {
String sx=null;
if (x == Short.MIN_VALUE)
sx = "100000";
else if (x < 0) {
String t = Integer.toString(
(~(-x-1))^Short.MIN_VALUE,8);
switch (t.length()) {
case 1:
sx = "10000"+t;
break;
case 2:
sx = "1000"+t;
break;
case 3:
sx = "100"+t;
break;
case 4:
sx = "10"+t;
break;
case 5:
sx = "1"+t;
break;
}
}
else
sx = Integer.toString((int)x,8);
return printOFormat(sx);
}
/**
* Format method for the o conversion character and
* long argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printOFormat(long x) {
String sx=null;
if (x == Long.MIN_VALUE)
sx = "1000000000000000000000";
else if (x < 0) {
String t = Long.toString(
(~(-x-1))^Long.MIN_VALUE,8);
switch (t.length()) {
case 1:
sx = "100000000000000000000"+t;
break;
case 2:
sx = "10000000000000000000"+t;
break;
case 3:
sx = "1000000000000000000"+t;
break;
case 4:
sx = "100000000000000000"+t;
break;
case 5:
sx = "10000000000000000"+t;
break;
case 6:
sx = "1000000000000000"+t;
break;
case 7:
sx = "100000000000000"+t;
break;
case 8:
sx = "10000000000000"+t;
break;
case 9:
sx = "1000000000000"+t;
break;
case 10:
sx = "100000000000"+t;
break;
case 11:
sx = "10000000000"+t;
break;
case 12:
sx = "1000000000"+t;
break;
case 13:
sx = "100000000"+t;
break;
case 14:
sx = "10000000"+t;
break;
case 15:
sx = "1000000"+t;
break;
case 16:
sx = "100000"+t;
break;
case 17:
sx = "10000"+t;
break;
case 18:
sx = "1000"+t;
break;
case 19:
sx = "100"+t;
break;
case 20:
sx = "10"+t;
break;
case 21:
sx = "1"+t;
break;
}
}
else
sx = Long.toString(x,8);
return printOFormat(sx);
}
/**
* Format method for the o conversion character and
* int argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printOFormat(int x) {
String sx=null;
if (x == Integer.MIN_VALUE)
sx = "20000000000";
else if (x < 0) {
String t = Integer.toString(
(~(-x-1))^Integer.MIN_VALUE,8);
switch (t.length()) {
case 1:
sx = "2000000000"+t;
break;
case 2:
sx = "200000000"+t;
break;
case 3:
sx = "20000000"+t;
break;
case 4:
sx = "2000000"+t;
break;
case 5:
sx = "200000"+t;
break;
case 6:
sx = "20000"+t;
break;
case 7:
sx = "2000"+t;
break;
case 8:
sx = "200"+t;
break;
case 9:
sx = "20"+t;
break;
case 10:
sx = "2"+t;
break;
case 11:
sx = "3"+t.substring(1);
break;
}
}
else
sx = Integer.toString(x,8);
return printOFormat(sx);
}
/**
* Utility method for formatting using the o
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printOFormat(String sx) {
int nLeadingZeros = 0;
int nBlanks = 0;
if (sx.equals("0")&&precisionSet&&precision==0)
sx="";
if (precisionSet)
nLeadingZeros = precision-sx.length();
if (alternateForm) nLeadingZeros++;
if (nLeadingZeros<0) nLeadingZeros=0;
if (fieldWidthSet)
nBlanks = fieldWidth-nLeadingZeros-sx.length();
if (nBlanks<0) nBlanks=0;
int n=nLeadingZeros+sx.length()+nBlanks;
char[] ca = new char[n];
int i;
if (leftJustify) {
for (i=0; i<nLeadingZeros; i++) ca[i]='0';
char[] csx = sx.toCharArray();
for (int j=0; j<csx.length; j++,i++)
ca[i] = csx[j];
for (int j=0; j<nBlanks; j++,i++) ca[i] = ' ';
}
else {
if (leadingZeros)
for (i=0; i<nBlanks; i++) ca[i]='0';
else
for (i=0; i<nBlanks; i++) ca[i]=' ';
for (int j=0; j<nLeadingZeros; j++,i++)
ca[i]='0';
char[] csx = sx.toCharArray();
for (int j=0; j<csx.length; j++,i++)
ca[i] = csx[j];
}
return new String(ca);
}
/**
* Format method for the c conversion character and
* char argument.
*
* The only flag character that affects c format is
* the '-', meaning that the output should be left
* justified within the field. The default is to
* pad with blanks on the left.
*
* The field width is treated as the minimum number
* of characters to be printed. Padding is with
* blanks by default. The default width is 1.
*
* The precision, if set, is ignored.
* @param x the char to format.
* @return the formatted String.
*/
private String printCFormat(char x) {
int nPrint = 1;
int width = fieldWidth;
if (!fieldWidthSet) width = nPrint;
char[] ca = new char[width];
int i=0;
if (leftJustify) {
ca[0] = x;
for (i=1; i<=width-nPrint; i++) ca[i]=' ';
}
else {
for (i=0; i<width-nPrint; i++) ca[i]=' ';
ca[i] = x;
}
return new String(ca);
}
/**
* Format method for the s conversion character and
* String argument.
*
* The only flag character that affects s format is
* the '-', meaning that the output should be left
* justified within the field. The default is to
* pad with blanks on the left.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is the
* smaller of the number of characters in the the
* input and the precision. Padding is with blanks
* by default.
*
* The precision, if set, specifies the maximum
* number of characters to be printed from the
* string. A null digit string is treated
* as a 0. The default is not to set a maximum
* number of characters to be printed.
* @param x the String to format.
* @return the formatted String.
*/
private String printSFormat(String x) {
int nPrint = x.length();
int width = fieldWidth;
if (precisionSet && nPrint>precision)
nPrint=precision;
if (!fieldWidthSet) width = nPrint;
int n=0;
if (width>nPrint) n+=width-nPrint;
if (nPrint>=x.length()) n+= x.length();
else n+= nPrint;
char[] ca = new char[n];
int i=0;
if (leftJustify) {
if (nPrint>=x.length()) {
char[] csx = x.toCharArray();
for (i=0; i<x.length(); i++) ca[i]=csx[i];
}
else {
char[] csx =
x.substring(0,nPrint).toCharArray();
for (i=0; i<nPrint; i++) ca[i]=csx[i];
}
for (int j=0; j<width-nPrint; j++,i++)
ca[i]=' ';
}
else {
for (i=0; i<width-nPrint; i++) ca[i]=' ';
if (nPrint>=x.length()) {
char[] csx = x.toCharArray();
for (int j=0; j<x.length(); i++,j++)
ca[i]=csx[j];
}
else {
char[] csx =
x.substring(0,nPrint).toCharArray();
for (int j=0; j<nPrint; i++,j++)
ca[i]=csx[j];
}
}
return new String(ca);
}
/**
* Check for a conversion character. If it is
* there, store it.
* @return <code>true</code> if the conversion
* character is there, and
* <code>false</code> otherwise.
*/
private boolean setConversionCharacter() {
/* idfgGoxXeEcs */
boolean ret = false;
conversionCharacter='\0';
if (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (c=='i'||c=='d'||c=='f'||c=='g'||c=='G'
|| c=='o' || c=='x' || c=='X' || c=='e'
|| c=='E' || c=='c' || c=='s' || c=='%') {
conversionCharacter = c;
pos++;
ret = true;
}
}
return ret;
}
/**
* Check for an h, l, or L in a format. An L is
* used to control the minimum number of digits
* in an exponent when using floating point
* formats. An l or h is used to control
* conversion of the input to a long or short,
* respectively, before formatting. If any of
* these is present, store them.
*/
private void setOptionalHL() {
optionalh=false;
optionall=false;
optionalL=false;
if (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (c=='h') { optionalh=true; pos++; }
else if (c=='l') { optionall=true; pos++; }
else if (c=='L') { optionalL=true; pos++; }
}
}
/**
* Set the precision.
*/
private void setPrecision() {
int firstPos = pos;
precisionSet = false;
if (pos<fmt.length()&&fmt.charAt(pos)=='.') {
pos++;
if ((pos < fmt.length())
&& (fmt.charAt(pos)=='*')) {
pos++;
if (!setPrecisionArgPosition()) {
variablePrecision = true;
precisionSet = true;
}
return;
}
else {
while (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (Character.isDigit(c)) pos++;
else break;
}
if (pos > firstPos+1) {
String sz = fmt.substring(firstPos+1,pos);
precision = Integer.parseInt(sz);
precisionSet = true;
}
}
}
}
/**
* Set the field width.
*/
private void setFieldWidth() {
int firstPos = pos;
fieldWidth = 0;
fieldWidthSet = false;
if ((pos < fmt.length())
&& (fmt.charAt(pos)=='*')) {
pos++;
if (!setFieldWidthArgPosition()) {
variableFieldWidth = true;
fieldWidthSet = true;
}
}
else {
while (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (Character.isDigit(c)) pos++;
else break;
}
if (firstPos<pos && firstPos < fmt.length()) {
String sz = fmt.substring(firstPos,pos);
fieldWidth = Integer.parseInt(sz);
fieldWidthSet = true;
}
}
}
/**
* Store the digits <code>n</code> in %n$ forms.
*/
private void setArgPosition() {
int xPos;
for (xPos=pos; xPos<fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos>pos && xPos<fmt.length()) {
if (fmt.charAt(xPos)=='$') {
positionalSpecification = true;
argumentPosition=
Integer.parseInt(fmt.substring(pos,xPos));
pos=xPos+1;
}
}
}
/**
* Store the digits <code>n</code> in *n$ forms.
*/
private boolean setFieldWidthArgPosition() {
boolean ret=false;
int xPos;
for (xPos=pos; xPos<fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos>pos && xPos<fmt.length()) {
if (fmt.charAt(xPos)=='$') {
positionalFieldWidth = true;
argumentPositionForFieldWidth=
Integer.parseInt(fmt.substring(pos,xPos));
pos=xPos+1;
ret=true;
}
}
return ret;
}
/**
* Store the digits <code>n</code> in *n$ forms.
*/
private boolean setPrecisionArgPosition() {
boolean ret=false;
int xPos;
for (xPos=pos; xPos<fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos>pos && xPos<fmt.length()) {
if (fmt.charAt(xPos)=='$') {
positionalPrecision = true;
argumentPositionForPrecision=
Integer.parseInt(fmt.substring(pos,xPos));
pos=xPos+1;
ret=true;
}
}
return ret;
}
boolean isPositionalSpecification() {
return positionalSpecification;
}
int getArgumentPosition() { return argumentPosition; }
boolean isPositionalFieldWidth() {
return positionalFieldWidth;
}
int getArgumentPositionForFieldWidth() {
return argumentPositionForFieldWidth;
}
boolean isPositionalPrecision() {
return positionalPrecision;
}
int getArgumentPositionForPrecision() {
return argumentPositionForPrecision;
}
/**
* Set flag characters, one of '-+#0 or a space.
*/
private void setFlagCharacters() {
/* '-+ #0 */
thousands = false;
leftJustify = false;
leadingSign = false;
leadingSpace = false;
alternateForm = false;
leadingZeros = false;
for ( ; pos < fmt.length(); pos++) {
char c = fmt.charAt(pos);
if (c == '\'') thousands = true;
else if (c == '-') {
leftJustify = true;
leadingZeros = false;
}
else if (c == '+') {
leadingSign = true;
leadingSpace = false;
}
else if (c == ' ') {
if (!leadingSign) leadingSpace = true;
}
else if (c == '#') alternateForm = true;
else if (c == '0') {
if (!leftJustify) leadingZeros = true;
}
else break;
}
}
/**
* The integer portion of the result of a decimal
* conversion (i, d, u, f, g, or G) will be
* formatted with thousands' grouping characters.
* For other conversions the flag is ignored.
*/
private boolean thousands = false;
/**
* The result of the conversion will be
* left-justified within the field.
*/
private boolean leftJustify = false;
/**
* The result of a signed conversion will always
* begin with a sign (+ or -).
*/
private boolean leadingSign = false;
/**
* Flag indicating that left padding with spaces is
* specified.
*/
private boolean leadingSpace = false;
/**
* For an o conversion, increase the precision to
* force the first digit of the result to be a
* zero. For x (or X) conversions, a non-zero
* result will have 0x (or 0X) prepended to it.
* For e, E, f, g, or G conversions, the result
* will always contain a radix character, even if
* no digits follow the point. For g and G
* conversions, trailing zeros will not be removed
* from the result.
*/
private boolean alternateForm = false;
/**
* Flag indicating that left padding with zeroes is
* specified.
*/
private boolean leadingZeros = false;
/**
* Flag indicating that the field width is *.
*/
private boolean variableFieldWidth = false;
/**
* If the converted value has fewer bytes than the
* field width, it will be padded with spaces or
* zeroes.
*/
private int fieldWidth = 0;
/**
* Flag indicating whether or not the field width
* has been set.
*/
private boolean fieldWidthSet = false;
/**
* The minimum number of digits to appear for the
* d, i, o, u, x, or X conversions. The number of
* digits to appear after the radix character for
* the e, E, and f conversions. The maximum number
* of significant digits for the g and G
* conversions. The maximum number of bytes to be
* printed from a string in s and S conversions.
*/
private int precision = 0;
/** Default precision. */
private final static int defaultDigits=6;
/**
* Flag indicating that the precision is *.
*/
private boolean variablePrecision = false;
/**
* Flag indicating whether or not the precision has
* been set.
*/
private boolean precisionSet = false;
/*
*/
private boolean positionalSpecification=false;
private int argumentPosition=0;
private boolean positionalFieldWidth=false;
private int argumentPositionForFieldWidth=0;
private boolean positionalPrecision=false;
private int argumentPositionForPrecision=0;
/**
* Flag specifying that a following d, i, o, u, x,
* or X conversion character applies to a type
* short int.
*/
private boolean optionalh = false;
/**
* Flag specifying that a following d, i, o, u, x,
* or X conversion character applies to a type lont
* int argument.
*/
private boolean optionall = false;
/**
* Flag specifying that a following e, E, f, g, or
* G conversion character applies to a type double
* argument. This is a noop in Java.
*/
private boolean optionalL = false;
/** Control string type. */
private char conversionCharacter = '\0';
/**
* Position within the control string. Used by
* the constructor.
*/
private int pos = 0;
/** Literal or control format string. */
private String fmt;
}
/** Vector of control strings and format literals. */
private List<ConversionSpecification> vFmt = new ArrayList<ConversionSpecification>();
/** Character position. Used by the constructor. */
private int cPos=0;
/** Character position. Used by the constructor. */
private DecimalFormatSymbols dfs=null;
}
| gpl-3.0 |
Becksteinlab/BornProfiler | bornprofiler/plotting.py | 3870 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# BornProfiler --- A package to calculate electrostatic free energies with APBS
# Written by Kaihsu Tai, Lennard van der Feltz, and Oliver Beckstein
# Released under the GNU Public Licence, version 3
#
"""
:Author: Lennard van der Feltz
:Year: 2014
:Licence: GPL 3
:Copyright: (c) 2014 Lennard van der Feltz
"""
"""Repository for various functions used repeatedly in plotting scripts. Many functions expect a logger under the title 'logger' to be in operation."""
import bornprofiler
import sys
import traceback
import argparse
import logging
import numpy
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
from bornprofiler.config import cfg
logger = logging.getLogger("bornprofiler")
def test_seaborn():
try:
import seaborn as sns
return True
except ImportError:
logger.info("seaborn import failed. Proceeding with uglier graphs")
return False
def protein_membrane_plot(axis,cfgs):
"""function for plotting membrane and protein on subplot axis using information from the first cfg in cfgs"""
plot_bot,plot_top = axis.get_ylim()
logger.info("reading cfg")
logger.warning("Assuming membrane and protein locations identical in all cfgs")
cfg.readfp(open(cfgs[0]))
protein_bottom = float(cfg.get('plotting','protein_bottom'))
protein_top = protein_bottom + float(cfg.get('plotting','protein_length'))
membrane_bottom = float(cfg.get('membrane','zmem'))
membrane_top = membrane_bottom + float(cfg.get('membrane','lmem'))
protein_low,protein_high = [plot_bot*.6 + plot_top*.4,plot_bot*.4+plot_top*.6]
axis.fill_between([membrane_bottom,membrane_top],[plot_top,plot_top],[plot_bot,plot_bot],facecolor='yellow',alpha=0.3)
axis.fill_between([protein_bottom,protein_top],[protein_high,protein_high],[protein_low,protein_low],facecolor='red',alpha=0.3)
def plot_markups(fig,axis,title,x_label,y_label,file_title,cfgs=None,seaborn=False):
"""function for applying labels,titles,membrane boxes and saving a matplotlib figure fig with subplot axis, previously plotted"""
axis.legend(loc='best')
axis.set_title(title)
axis.set_xlabel(x_label)
axis.set_ylabel(y_label)
if cfgs==None:
pass
else:
protein_membrane_plot(axis,cfgs)
if seaborn:
import seaborn as sns
sns.despine(trim=True, fig=fig)
fig.tight_layout()
logger.info("saving figure to {file_title}.pdf and {file_title}.png".format(file_title=file_title))
fig.savefig("{file_title}.png".format(file_title=file_title),format='png')
fig.savefig("{file_title}.pdf".format(file_title=file_title),format='pdf')
def graph_mult_data(file_list,xcolumn,ycolumn,plot_labels,x_label,y_label,title,file_title,colors=None,cfgs=None,seaborn=False):
if seaborn:
seaborn = test_seaborn()
import seaborn as sns
logger.info("unpacking data")
if colors==None:
datalist = [[numpy.loadtxt(filename),label] for filename,label in zip(file_list, plot_labels)]
else:
datalist = [[numpy.loadtxt(filename),label,color] for filename,label,color in zip(file_list, plot_labels,colors)]
if seaborn:
sns.set_style("ticks", rc={'font.family': 'Helvetica'})
sns.set_context("paper")
logger.info("plotting")
fig = plt.figure()
axis = fig.add_subplot(111)
if seaborn:
sns.offset_spines(fig=fig)
if colors==None:
for data,label in datalist:
axis.plot( data[:,xcolumn],data[:,ycolumn],label=label)
else:
for data,label,color in datalist:
axis.plot( data[:,xcolumn],data[:,ycolumn],label=label,color=color)
plot_markups(fig,axis,title,x_label,y_label,file_title,cfgs=cfgs,seaborn=seaborn)
| gpl-3.0 |
michaeljoseph/capecommute-scraperwiki | tests/__init__.py | 1857 | from datetime import datetime
import json
from tablib import Dataset
from unittest2 import TestCase
from capecommute import train
class TrainTestCase(TestCase):
def test_parse_url(self):
url = '_timetables/2013_04_08/South/ST_CT_Sun_April_2013.htm'
self.assertEquals(
('South', 'ST', 'CT', 'Sun', datetime(2013, 4, 8, 0, 0)),
train.parse_url(url)
)
def test_scrape_capemetro_urls(self):
self.assertEquals(
[
('http://www.capemetrorail.co.za/'
'_timetables/2013_04_08/Central/CT_KYL_MonFri_April_2013.htm'),
('http://www.capemetrorail.co.za/'
'_timetables/2013_04_08/Central/CT_KYL_Sat_April_2013.htm'),
],
train.scrape_capemetro_urls()[:2]
)
def test_extract_station(self):
row = ['SIMON`S TOWN', '04:24', '05:24', '06:22', '07:18', '08:17',
'09:04', '09:55', '10:42', '11:53', 'SIMON`S TOWN', '13:00',
'13:41', '14:54', '16:02']
expected = list(set(row))
expected.remove('SIMON`S TOWN')
self.assertEquals(
('SIMON`S TOWN', sorted(expected)),
train.extract_station(row)
)
def test_generate_dataset(self):
station_times = {
'Muizenberg': {
'zone': 'South',
'station': 'Muizenberg',
'times': [{
'11:30': {
'train_number': '201',
'platform': '1',
}
}]
}
}
self.assertEquals(
('[{"zone": "South", "station": "Muizenberg", "time": "11:30", '
'"train_number": "201", "platform": "1"}]'),
train.generate_dataset(station_times).json
)
| gpl-3.0 |
chtaal/imgtosnd | example.py | 1335 | ## imports
import imgtosnd as i2s
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
## short-time fourier parameters
sample_rate = 16000 # sample rate in Hz
frame_size = i2s.next_pow2(sample_rate*25/1000) # frame size in samples
hop_size = int(frame_size/2) # hop size (samples)
## read image and get complex spectrogram with random phase
im = i2s.read_image_as_spec("data/me.jpg", frame_size, sample_rate, hop_size, num_seconds=20)
im **= 2
im = i2s.add_random_phase(im)
## convert image to audio via inverse short-time fft
x = i2s.st_irfft(im, frame_size, hop_size, win_sqrt=False)
## apply some normalization to the audio signal and write to disk
x /= np.max(np.abs(x))
wavfile.write('data\\me.wav', sample_rate, x)
## get back spectrogram of synthesized waveform
xf = i2s.st_rfft(x, frame_size, hop_size)
xf = np.abs(xf)
xf /= np.max(xf)
## plot stuff
ax = plt.subplot(121)
t = np.arange(np.size(x))/sample_rate
plt.plot(t, x)
plt.grid()
plt.xlabel('Time (s)')
plt.subplot(122, sharex=ax)
t = np.arange(np.shape(im)[1])/(sample_rate/hop_size)
f = np.fft.rfftfreq(frame_size)*sample_rate/1000
plt.pcolormesh(t, f, 20*np.log10(xf), cmap='plasma')
plt.colorbar(label='level(dB)')
plt.clim([-30, 0])
plt.colormaps()
plt.xlabel('Time (s)')
plt.ylabel('Frequency (kHz)')
plt.gcf().autofmt_xdate() | gpl-3.0 |
dovydasvenckus/todo-web | app/models/list.js | 159 | module.exports = Backbone.Model.extend({
url: require('config').api.url + '/api/list',
defaults: {
id: undefined,
title: ''
}
});
| gpl-3.0 |
webSPELL/webSPELL | languages/es/profile.php | 5077 | <?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'about'=>'Sobre',
'add_buddylist'=>'añadir a lista amigos',
'administrator'=>'Administrador',
'age'=>'Edad',
'are_on'=>'está ON',
'articlecomments'=>'Comentarios Artículos',
'back_buddylist'=>'volver a lista amigos',
'bbcode'=>'BBCode',
'buddylist'=>'Lista amigos',
'buddys'=>'Amigos',
'by'=>'por',
'clan'=>'Clan',
'clan_equipment'=>'Clan / Equipamiento',
'clan_history'=>'Historial clan',
'clanmember'=>'Miembro del clan',
'clanwarcomments'=>'Comentarios encuentros',
'contact'=>'Contacto',
'cpu'=>'CPU',
'date'=>'Fecha',
'delete_selected'=>'borrar seleccionado',
'democomments'=>'Comentarios demos',
'email'=>'Email',
'female'=>'hembra',
'forumposts'=>'Foro: Mensajes',
'forumtopics'=>'Foro: Temas',
'galleries'=>'Galerías',
'graphiccard'=>'T.Gráfica',
'guestbook'=>'Libro visitas',
'homepage'=>'Web',
'hp'=>'HP',
'html_off'=>'HTML está OFF',
'i_connection'=>'Conex. Internet',
'ignore_user'=>'ignorar usuario',
'incoming'=>'entrante',
'irc_channel'=>'Canal IRC',
'is_banned'=>'Este miembro está cerrado!',
'is_on'=>'está ON',
'keyboard'=>'Teclado',
'last'=>'Último(s)',
'last_login'=>'Última conexion',
'last_posts'=>'Últimos mensajes',
'last_topics'=>'Últimos temas',
'latest_visitors'=>'Últimos visitantes',
'location'=>'Localización',
'logged'=>'conectado',
'mainboard'=>'P.Base',
'male'=>'varón',
'messenger'=>'Messenger',
'moderator'=>'Moderador',
'monitor'=>'Monitor',
'mouse'=>'Ratón',
'mousepad'=>'Alfombrilla',
'n_a'=>'n/a',
'name'=>'Nombre',
'new_entry'=>'nuevo dato',
'new_guestbook_entry'=>'Nuevo libro visitas en tú perfil!',
'new_guestbook_entry_msg'=>'[b]Hay una firma en libro de visitas![/b] [URL=index.php?site=profile&action=guestbook&id=%guestbook_id%]Haz clic aquí[/URL]',
'newscomments'=>'Comentarios noticias',
'newsposts'=>'Newsposts',
'nickname'=>'Apodo',
'no_access'=>'Sin acceso!',
'no_buddys'=>'sin amigos',
'no_galleries'=>'no hay galerías',
'no_posts'=>'no hay mensajes',
'no_topics'=>'no hay temas',
'no_visits'=>'no hay visitas',
'now'=>'ahora',
'offline'=>'fuera de línea',
'online'=>'en línea',
'options'=>'Opciones',
'outgoing'=>'saliente',
'personal_info'=>'Info. Personal',
'pictures'=>'Imagenes',
'posts'=>'mensajes',
'profile'=>'Perfil',
'quote'=>'citar',
'ram'=>'RAM',
'real_name'=>'Nombre real',
'registered_since'=>'Registrado desde',
'replys'=>'replies',
'security_code'=>'Inserta código seguridad',
'select_all'=>'seleccionar todos',
'sexuality'=>'Sexo',
'smilies'=>'Emoticonos',
'sort'=>'Ordenar',
'soundcard'=>'T.Sonido',
'statistics'=>'Estadísticas',
'status'=>'Estado',
'submit'=>'enviar',
'unknown'=>'not available',
'user_doesnt_exist'=>'Este usuario no existe.',
'usergalleries_disabled'=>'Galerías de usuario desactivados.',
'userpic'=>'Imagen de usuario',
'usertitle'=>'Título de usuario',
'views'=>'vistas',
'wrote'=>'escrito',
'years'=>'años',
'yht_enter_message'=>'Debes insertar un mensaje!',
'yht_enter_name'=>'Debes insertar tu nombre!',
'your_email'=>'tu e-mail',
'your_homepage'=>'tu web',
'your_message'=>'tu mensaje',
'your_name'=>'tu nombre'
);
?> | gpl-3.0 |
am8850/azurehealthmonitor | CSWebMonitor/App_Start/IdentityConfig.cs | 1788 | using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using CSWebMonitor.Models;
namespace CSWebMonitor
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
}
| gpl-3.0 |
josejapch/proyectoIV1617 | queue/migrations/0004_delete_usuario.py | 359 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-18 14:49
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('queue', '0003_auto_20161014_1531'),
]
operations = [
migrations.DeleteModel(
name='Usuario',
),
]
| gpl-3.0 |
aleatorio12/ProVentasConnector | jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/xml/JRPrintXmlLoader.java | 14592 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.xml;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRFont;
import net.sf.jasperreports.engine.JROrigin;
import net.sf.jasperreports.engine.JRPrintElement;
import net.sf.jasperreports.engine.JRPrintHyperlinkParameter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.engine.JRStyle;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.PrintBookmark;
import net.sf.jasperreports.engine.TabStop;
import net.sf.jasperreports.engine.util.CompositeClassloader;
import org.apache.commons.digester.SetNestedPropertiesRule;
import org.apache.commons.digester.SetPropertiesRule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Utility class that helps reconverting XML documents into
* {@link net.sf.jasperreports.engine.JasperPrint} objects.
* <p>
* Generated documents can be stored in XML format if they are exported using the
* {@link net.sf.jasperreports.engine.export.JRXmlExporter}. After they're exported,
* one can parse them back into {@link net.sf.jasperreports.engine.JasperPrint} objects
* by using this class.
* </p>
* @author Teodor Danciu (teodord@users.sourceforge.net)
*/
public class JRPrintXmlLoader implements ErrorHandler
{
private static final Log log = LogFactory.getLog(JRPrintXmlLoader.class);
/**
*
*/
private final JasperReportsContext jasperReportsContext;
private JasperPrint jasperPrint;
private List<Exception> errors = new ArrayList<Exception>();
/**
* @deprecated Replaced by {@link #JRPrintXmlLoader(JasperReportsContext)}.
*/
protected JRPrintXmlLoader()
{
this(DefaultJasperReportsContext.getInstance());
}
/**
*
*/
protected JRPrintXmlLoader(JasperReportsContext jasperReportsContext)
{
this.jasperReportsContext = jasperReportsContext;
}
/**
*
*/
public JasperReportsContext getJasperReportsContext()
{
return jasperReportsContext;
}
/**
*
*/
public void setJasperPrint(JasperPrint jasperPrint)
{
this.jasperPrint = jasperPrint;
}
/**
*
*/
public static JasperPrint loadFromFile(JasperReportsContext jasperReportsContext, String sourceFileName) throws JRException
{
JasperPrint jasperPrint = null;
FileInputStream fis = null;
try
{
fis = new FileInputStream(sourceFileName);
JRPrintXmlLoader printXmlLoader = new JRPrintXmlLoader(jasperReportsContext);
jasperPrint = printXmlLoader.loadXML(fis);
}
catch(IOException e)
{
throw new JRException(e);
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch(IOException e)
{
}
}
}
return jasperPrint;
}
/**
* @see #loadFromFile(JasperReportsContext, String)
*/
public static JasperPrint loadFromFile(String sourceFileName) throws JRException
{
return loadFromFile(DefaultJasperReportsContext.getInstance(), sourceFileName);
}
/**
* @see #loadFromFile(String)
*/
public static JasperPrint load(String sourceFileName) throws JRException
{
return loadFromFile(sourceFileName);
}
/**
*
*/
public static JasperPrint load(JasperReportsContext jasperReportsContext, InputStream is) throws JRException
{
JasperPrint jasperPrint = null;
JRPrintXmlLoader printXmlLoader = new JRPrintXmlLoader(jasperReportsContext);
jasperPrint = printXmlLoader.loadXML(is);
return jasperPrint;
}
/**
* @see #load(JasperReportsContext, InputStream)
*/
public static JasperPrint load(InputStream is) throws JRException
{
return load(DefaultJasperReportsContext.getInstance(), is);
}
/**
*
*/
private JasperPrint loadXML(InputStream is) throws JRException
{
try
{
JRXmlDigester digester = prepareDigester();
/* */
digester.parse(is);
}
catch(ParserConfigurationException e)
{
throw new JRException(e);
}
catch(SAXException e)
{
throw new JRException(e);
}
catch(IOException e)
{
throw new JRException(e);
}
if (errors.size() > 0)
{
Exception e = errors.get(0);
if (e instanceof JRException)
{
throw (JRException)e;
}
throw new JRException(e);
}
return this.jasperPrint;
}
/**
*
*/
protected JRXmlDigester prepareDigester() throws ParserConfigurationException, SAXException
{
JRXmlDigester digester = new JRXmlDigester(createParser());
// use a classloader that resolves both JR classes and classes from the context classloader
CompositeClassloader digesterClassLoader = new CompositeClassloader(
JRPrintXmlLoader.class.getClassLoader(),
Thread.currentThread().getContextClassLoader());
digester.setClassLoader(digesterClassLoader);
digester.setNamespaceAware(true);
digester.setRuleNamespaceURI(JRXmlConstants.JASPERPRINT_NAMESPACE);
digester.push(this);
//digester.setDebug(3);
digester.setErrorHandler(this);
digester.setValidating(true);
/* */
digester.addFactoryCreate("jasperPrint", JasperPrintFactory.class.getName());
digester.addSetNext("jasperPrint", "setJasperPrint", JasperPrint.class.getName());
/* */
digester.addRule("*/property", new JRPropertyDigesterRule());
/* */
digester.addFactoryCreate("jasperPrint/origin", JROriginFactory.class.getName());
digester.addSetNext("jasperPrint/origin", "addOrigin", JROrigin.class.getName());
/* */
digester.addFactoryCreate("jasperPrint/reportFont", JRStyleFactory.class.getName());
digester.addSetNext("jasperPrint/reportFont", "addStyle", JRStyle.class.getName());
/* */
digester.addFactoryCreate("jasperPrint/style", JRPrintStyleFactory.class.getName());
digester.addSetNext("jasperPrint/style", "addStyle", JRStyle.class.getName());
/* */
digester.addFactoryCreate("*/style/pen", JRPenFactory.Style.class.getName());
/* */
digester.addFactoryCreate("*/bookmark", PrintBookmarkFactory.class.getName());
digester.addSetNext("*/bookmark", "addBookmark", PrintBookmark.class.getName());
/* */
digester.addFactoryCreate("jasperPrint/part", PrintPartFactory.class.getName());
/* */
digester.addFactoryCreate("jasperPrint/page", JRPrintPageFactory.class.getName());
digester.addSetNext("jasperPrint/page", "addPage", JRPrintPage.class.getName());
/* */
digester.addFactoryCreate("*/line", JRPrintLineFactory.class.getName());
digester.addSetNext("*/line", "addElement", JRPrintElement.class.getName());
/* */
digester.addFactoryCreate("*/reportElement", JRPrintElementFactory.class.getName());
/* */
digester.addFactoryCreate("*/graphicElement", JRPrintGraphicElementFactory.class.getName());
/* */
digester.addFactoryCreate("*/pen", JRPenFactory.class.getName());
/* */
digester.addFactoryCreate("*/rectangle", JRPrintRectangleFactory.class.getName());
digester.addSetNext("*/rectangle", "addElement", JRPrintElement.class.getName());
/* */
digester.addFactoryCreate("*/ellipse", JRPrintEllipseFactory.class.getName());
digester.addSetNext("*/ellipse", "addElement", JRPrintElement.class.getName());
/* */
digester.addFactoryCreate("*/image", JRPrintImageFactory.class.getName());
digester.addSetNext("*/image", "addElement", JRPrintElement.class.getName());
/* */
digester.addFactoryCreate("*/box", JRBoxFactory.class.getName());
/* */
digester.addFactoryCreate("*/box/pen", JRPenFactory.Box.class.getName());
digester.addFactoryCreate("*/box/topPen", JRPenFactory.Top.class.getName());
digester.addFactoryCreate("*/box/leftPen", JRPenFactory.Left.class.getName());
digester.addFactoryCreate("*/box/bottomPen", JRPenFactory.Bottom.class.getName());
digester.addFactoryCreate("*/box/rightPen", JRPenFactory.Right.class.getName());
/* */
digester.addFactoryCreate("*/paragraph", JRParagraphFactory.class.getName());
digester.addFactoryCreate("*/paragraph/tabStop", TabStopFactory.class.getName());
digester.addSetNext("*/paragraph/tabStop", "addTabStop", TabStop.class.getName());
/* */
digester.addFactoryCreate("*/image/imageSource", JRPrintImageSourceFactory.class.getName());
digester.addCallMethod("*/image/imageSource", "setImageSource", 0);
/* */
digester.addFactoryCreate("*/text", JRPrintTextFactory.class.getName());
digester.addSetNext("*/text", "addElement", JRPrintElement.class.getName());
SetNestedPropertiesRule textRule = new SetNestedPropertiesRule(
new String[]{"textContent", "textTruncateSuffix", "reportElement", "box", "font",
JRXmlConstants.ELEMENT_lineBreakOffsets},
new String[]{"text", "textTruncateSuffix"});
textRule.setTrimData(false);
textRule.setAllowUnknownChildElements(true);
digester.addRule("*/text", textRule);
digester.addRule("*/text/textContent",
new SetPropertiesRule(JRXmlConstants.ATTRIBUTE_truncateIndex, "textTruncateIndex"));
/* */
digester.addFactoryCreate("*/text/font", JRPrintFontFactory.class.getName());
digester.addSetNext("*/text/font", "setFont", JRFont.class.getName());
digester.addRule("*/text/" + JRXmlConstants.ELEMENT_lineBreakOffsets,
new TextLineBreakOffsetsRule());
addFrameRules(digester);
addHyperlinkParameterRules(digester);
addGenericElementRules(digester);
return digester;
}
protected SAXParser createParser()
{
String parserFactoryClass = JRPropertiesUtil.getInstance(jasperReportsContext).getProperty(
JRSaxParserFactory.PROPERTY_PRINT_PARSER_FACTORY);
if (log.isDebugEnabled())
{
log.debug("Using SAX parser factory class " + parserFactoryClass);
}
JRSaxParserFactory factory = BaseSaxParserFactory.getFactory(jasperReportsContext, parserFactoryClass);
return factory.createParser();
}
private void addFrameRules(JRXmlDigester digester)
{
digester.addFactoryCreate("*/frame", JRPrintFrameFactory.class.getName());
digester.addSetNext("*/frame", "addElement", JRPrintElement.class.getName());
}
protected void addHyperlinkParameterRules(JRXmlDigester digester)
{
String parameterPattern = "*/" + JRXmlConstants.ELEMENT_hyperlinkParameter;
digester.addFactoryCreate(parameterPattern, JRPrintHyperlinkParameterFactory.class);
digester.addSetNext(parameterPattern, "addHyperlinkParameter", JRPrintHyperlinkParameter.class.getName());
String parameterValuePattern = parameterPattern + "/" + JRXmlConstants.ELEMENT_hyperlinkParameterValue;
digester.addFactoryCreate(parameterValuePattern, JRPrintHyperlinkParameterValueFactory.class);
digester.addCallMethod(parameterValuePattern, "setData", 0);
}
protected void addGenericElementRules(JRXmlDigester digester)
{
String elementPattern = "*/" + JRXmlConstants.ELEMENT_genericElement;
digester.addFactoryCreate(elementPattern,
JRGenericPrintElementFactory.class);
digester.addSetNext(elementPattern, "addElement",
JRPrintElement.class.getName());
String elementTypePattern = elementPattern + "/"
+ JRXmlConstants.ELEMENT_genericElementType;
digester.addFactoryCreate(elementTypePattern,
JRGenericElementTypeFactory.class);
digester.addSetNext(elementTypePattern, "setGenericType");
String elementParameterPattern = elementPattern + "/"
+ JRXmlConstants.ELEMENT_genericElementParameter;
digester.addFactoryCreate(elementParameterPattern,
JRGenericPrintElementParameterFactory.class);
digester.addCallMethod(elementParameterPattern, "addParameter");
digester.addRule(elementParameterPattern, new JRGenericPrintElementParameterFactory.ArbitraryValueSetter());
String elementParameterValuePattern = elementParameterPattern + "/"
+ JRXmlConstants.ELEMENT_genericElementParameterValue;
digester.addFactoryCreate(elementParameterValuePattern,
JRGenericPrintElementParameterFactory.ParameterValueFactory.class);
digester.addCallMethod(elementParameterValuePattern, "setData", 0);
addValueHandlerRules(digester, elementParameterPattern);
}
protected void addValueHandlerRules(JRXmlDigester digester, String elementParameterPattern)
{
List<XmlValueHandler> handlers = XmlValueHandlerUtils.instance().getHandlers();
for (XmlValueHandler handler : handlers)
{
XmlHandlerNamespace namespace = handler.getNamespace();
if (namespace != null)
{
String namespaceURI = namespace.getNamespaceURI();
if (log.isDebugEnabled())
{
log.debug("Configuring the digester for handler " + handler
+ " and namespace " + namespaceURI);
}
digester.setRuleNamespaceURI(namespaceURI);
handler.configureDigester(digester);
String schemaResource = namespace.getInternalSchemaResource();
digester.addInternalEntityResource(namespace.getPublicSchemaLocation(),
schemaResource);
}
}
digester.setRuleNamespaceURI(JRXmlConstants.JASPERPRINT_NAMESPACE);
}
/**
*
*/
public void addError(Exception e)
{
this.errors.add(e);
}
/**
*
*/
public void error(SAXParseException e)
{
this.errors.add(e);
}
/**
*
*/
public void fatalError(SAXParseException e)
{
this.errors.add(e);
}
/**
*
*/
public void warning(SAXParseException e)
{
this.errors.add(e);
}
}
| gpl-3.0 |
vybeonllc/dat_framework | V1/Framework/Controls/FormView/FormViewItemType.cs | 269 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dat.V1.Framework.Controls
{
public enum FormViewItemType
{
Header,
Footer,
Item,
EmptyItem
}
}
| gpl-3.0 |
ramsey-darling1/woodpecker | index.php | 1441 | <?php
/**
* Start, Heart, and Brain of the Application
* a simple app to record hours against a project
* @rdarling
*
*/
session_start();//start the session
//include classes
include_once 'models/Accounts.php';
include_once 'models/Projects.php';
include_once 'models/Hours.php';
include_once 'models/Db.php';
$account = new Accounts();
//router
switch(@$_GET['page']){
case 'register':
$view = 'register';
break;
case 'new_project':
$view = !$account->is_logged_in() ? 'index' : 'new_project';
break;
case 'list_projects':
if($account->is_logged_in()){
$project = new Projects();
$account_id = Accounts::re_static_id();
$projects_list = $project->re_projects_list($account_id);
$view = 'list_projects';
}else{
$view = 'index';
}
break;
case 'view_project':
if($account->is_logged_in() and !empty($_GET['project'])){
$project = new Projects();
$hours = new Hours();
$project->set_id($_GET['project']);
$project->set_account_id(Accounts::re_static_id());
$project_data = $project->is_users_project() ? $project->re_project() : null;
$project_hours = $hours->re_project_hours($_GET['project']);
$view = 'view_project';
}else{
$view = 'index';
}
break;
default:
$view = !$account->is_logged_in() ? 'index' : 'main';
}
//include the view
include_once "views/{$view}.php";
| gpl-3.0 |
trevlaib/dev_bible | js/showverse.js | 706 | function validateForm()
{
var x=document.forms["confirm"]["start"].value;
var y=document.forms["confirm"]["stop"].value;
var subject=document.forms["confirm"]["subject"].value;
var chapter=document.forms["confirm"]["chapter"].value;
var verses=document.forms["confirm"]["verses"].value;
if (x > y)
{
alert("Stop time must be greater than Start time.");
return false;
}
else if (subject == null || subject == "" || chapter==null || chapter==""|| verses==null || verses=="" || x==null || x==""|| y==null || y=="")
{
alert("Missing info")
return false;
}
}
function showVerse(text)
{
var el = document.getElementById('showverse');
el.onclick = showVerse;
alert (text);
return false;
}
| gpl-3.0 |
cerndb/wls-cern-sso | WlsAttributeNameMapper/src/ch/cern/sso/weblogic/mappers/attributes/Attribute.java | 4736 | /*******************************************************************************
* Copyright (C) 2015, CERN
* This software is distributed under the terms of the GNU General Public
* License version 3 (GPL Version 3), copied verbatim in the file "LICENSE".
* In applying this license, CERN does not waive the privileges and immunities
* granted to it by virtue of its status as Intergovernmental Organization
* or submit itself to any jurisdiction.
*
*
*******************************************************************************/
package ch.cern.sso.weblogic.mappers.attributes;
import java.util.Collection;
import ch.cern.sso.weblogic.principals.CernWlsGroupPrincipal;
import ch.cern.sso.weblogic.principals.CernWlsPrincipal;
import ch.cern.sso.weblogic.principals.CernWlsUserPrincipal;
public enum Attribute {
UPN("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setUpn((String) value);
}
},
EMAIL_ADDRESS("http://schemas.xmlsoap.org/claims/EmailAddress") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setEmailAddress((String) value);
}
},
COMMON_NAME("http://schemas.xmlsoap.org/claims/CommonName") {
public void setValue(Object principal, Object value) {
((CernWlsPrincipal) principal).setCommonName((String) value);
}
},
ROLE("http://schemas.microsoft.com/ws/2008/06/identity/claims/role") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setRole((String) value);
}
},
IDENTITY_CLASS("http://schemas.xmlsoap.org/claims/IdentityClass") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setIdentityClass((String) value);
}
},
DISPLAY_NAME("http://schemas.xmlsoap.org/claims/DisplayName") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setDisplayName((String) value);
}
},
PHONE_NUMBER("http://schemas.xmlsoap.org/claims/PhoneNumber") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setPhoneNumber((String) value);
}
},
BUILDING("http://schemas.xmlsoap.org/claims/Building") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setBuilding((String) value);
}
},
FIRST_NAME("http://schemas.xmlsoap.org/claims/Firstname") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setFirstName((String) value);
}
},
LAST_NAME("http://schemas.xmlsoap.org/claims/Lastname") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setLastName((String) value);
}
},
DEPARTMENT("http://schemas.xmlsoap.org/claims/Department") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setDepartment((String) value);
}
},
HOME_INSTITUTE("http://schemas.xmlsoap.org/claims/HomeInstitute") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setHomeInstitute((String) value);
}
},
PERSON_ID("http://schemas.xmlsoap.org/claims/PersonID") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setPersonID((String) value);
}
},
UID_NUMBER("http://schemas.xmlsoap.org/claims/uidNumber") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setUidNumber((String) value);
}
},
GID_NUMBER("http://schemas.xmlsoap.org/claims/gidNumber") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setGidNumber((String) value);
}
},
PREFERRED_LANGUAGE("http://schemas.xmlsoap.org/claims/PreferredLanguage") {
public void setValue(Object principal, Object value) {
((CernWlsUserPrincipal) principal).setPreferredLanguage((String) value);
}
},
GROUP("http://schemas.xmlsoap.org/claims/Group") {
public void setValue(Object principal, Object value) {
if (principal instanceof CernWlsUserPrincipal) {
Collection<String> groups = (Collection<String>) value;
if (groups != null && groups.size() > 0) {
for (String groupName : groups) {
((CernWlsUserPrincipal) principal).addGroup(groupName);
}
}
}
if (principal instanceof CernWlsGroupPrincipal) {
((CernWlsGroupPrincipal) principal)
.setCommonName((String) value);
}
}
};
private final String name;
private Attribute(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public abstract void setValue(Object principal, Object value);
}
| gpl-3.0 |