repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
labgeo/siguanet-desktop
|
SharpMap/Web/Cache.cs
|
2504
|
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap 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 SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpMap.Web
{
/// <summary>
/// Class for storing rendered images in the httpcache
/// </summary>
public class Caching
{
/// <summary>
/// Inserts an image into the HttpCache and returns the cache identifier.
/// </summary>
/// <remarks>
/// Image can after insertion into the cache be requested by calling getmap.aspx?ID=[identifier]<br/>
/// This requires you to add the following to web.config:
/// <code escaped="true">
/// <httpHandlers>
/// <add verb="*" path="GetMap.aspx" type="SharpMap.Web.HttpHandler,SharpMap"/>
/// </httpHandlers>
/// </code>
/// <example>
/// Inserting the map into the cache and setting the ImageUrl:
/// <code>
/// string imgID = SharpMap.Web.Caching.CacheMap(5, myMap.GetMap(), Session.SessionID, Context);
/// imgMap.ImageUrl = "getmap.aspx?ID=" + HttpUtility.UrlEncode(imgID);
/// </code>
/// </example>
/// </remarks>
/// <param name="minutes">Number of minutes to cache the map</param>
/// <param name="map">Map reference</param>
/// <returns>Image identifier</returns>
public static string InsertIntoCache(int minutes, System.Drawing.Image map)
{
string guid = System.Guid.NewGuid().ToString().Replace("-","");
System.IO.MemoryStream MS = new System.IO.MemoryStream();
map.Save(MS, System.Drawing.Imaging.ImageFormat.Png);
byte[] buffer = MS.ToArray();
System.Web.HttpContext.Current.Cache.Insert(guid, buffer, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes));
map.Dispose();
return guid;
}
}
}
|
gpl-3.0
|
rubenswagner/L2J-Global
|
dist/game/data/scripts/handlers/admincommandhandlers/AdminInvul.java
|
3597
|
/*
* This file is part of the L2J Global 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 handlers.admincommandhandlers;
import java.util.logging.Logger;
import com.l2jglobal.Config;
import com.l2jglobal.gameserver.handler.IAdminCommandHandler;
import com.l2jglobal.gameserver.model.L2Object;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance;
/**
* This class handles following admin commands: - invul = turns invulnerability on/off
* @version $Revision: 1.2.4.4 $ $Date: 2007/07/31 10:06:02 $
*/
public class AdminInvul implements IAdminCommandHandler
{
private static Logger _log = Logger.getLogger(AdminInvul.class.getName());
private static final String[] ADMIN_COMMANDS =
{
"admin_invul",
"admin_setinvul",
"admin_undying",
"admin_setundying"
};
@Override
public boolean useAdminCommand(String command, L2PcInstance activeChar)
{
if (command.equals("admin_invul"))
{
handleInvul(activeChar);
AdminHtml.showAdminHtml(activeChar, "gm_menu.htm");
}
else if (command.equals("admin_undying"))
{
handleUndying(activeChar);
AdminHtml.showAdminHtml(activeChar, "gm_menu.htm");
}
else if (command.equals("admin_setinvul"))
{
final L2Object target = activeChar.getTarget();
if (target instanceof L2PcInstance)
{
handleInvul((L2PcInstance) target);
}
}
else if (command.equals("admin_setundying"))
{
final L2Object target = activeChar.getTarget();
if (target instanceof L2Character)
{
handleUndying((L2Character) target);
}
}
return true;
}
@Override
public String[] getAdminCommandList()
{
return ADMIN_COMMANDS;
}
private void handleInvul(L2PcInstance activeChar)
{
String text;
if (activeChar.isInvul())
{
activeChar.setIsInvul(false);
text = activeChar.getName() + " is now mortal";
if (Config.DEBUG)
{
_log.finer("GM: Gm removed invul mode from character " + activeChar.getName() + "(" + activeChar.getObjectId() + ")");
}
}
else
{
activeChar.setIsInvul(true);
text = activeChar.getName() + " is now invulnerable";
if (Config.DEBUG)
{
_log.finer("GM: Gm activated invul mode for character " + activeChar.getName() + "(" + activeChar.getObjectId() + ")");
}
}
activeChar.sendMessage(text);
}
private void handleUndying(L2Character activeChar)
{
String text;
if (activeChar.isUndying())
{
activeChar.setUndying(false);
text = activeChar.getName() + " is now mortal";
if (Config.DEBUG)
{
_log.finer("GM: Gm removed undying mode from character " + activeChar.getName() + "(" + activeChar.getObjectId() + ")");
}
}
else
{
activeChar.setUndying(true);
text = activeChar.getName() + " is now undying";
if (Config.DEBUG)
{
_log.finer("GM: Gm activated undying mode for character " + activeChar.getName() + "(" + activeChar.getObjectId() + ")");
}
}
activeChar.sendMessage(text);
}
}
|
gpl-3.0
|
victorjacobs/jetbird
|
jetbird/include/configuration.manipulator.class.php
|
3864
|
<?php
/* This file is part of Jetbird.
Jetbird 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.
Jetbird 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 Jetbird. If not, see <http://www.gnu.org/licenses/>.
*/
class configuration_manipulator{
private $status, $raw_data, $out_array = array(), $out_string, $out_temp;
// Declare some statics
const FILE_BASE =
"<?php
/* This file is part of Jetbird.
Jetbird 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.
Jetbird 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 Jetbird. If not, see <http://www.gnu.org/licenses/>.
*/
/* File generated by configuration_manipulator class on ///DATEPLACEHOLDER/// */
///DATAPLACEHOLDER///
?>";
public function __construct(){
// Parse $config, before we check whether this is clean install.
// We do this because the bare configuration contains some essential default settings
$this->parse_config_to_array();
}
public function add_var($path, $data){
list($parent, $child) = $this->eval_path($path);
$this->out_array[$parent][$child] = $data;
}
private function parse_config_to_array(){
global $config;
$this->out_array = array_merge($config, $this->out_array);
}
private function out_array_to_string(){
// Sort out_array, TODO: sort childs
ksort($this->out_array);
foreach($this->out_array as $parent => $var){
$this->out_temp .= "\t" . '// '. ucfirst($parent) .' settings' . "\n";
foreach($var as $child => $data){
$this->out_temp .= "\t" . '$config[\''. $parent .'\'][\''. $child .'\'] = ';
if(is_int($data)){
$this->out_temp .= $data . ";";
}elseif(is_string($data)){
$this->out_temp .= '"'. $data .'";';
}elseif(is_bool($data)){
if($data){
$this->out_temp .= 'true;';
}else{
$this->out_temp .= 'false;';
}
}
$this->out_temp .= "\n";
}
$this->out_temp .= "\n";
}
return $this->out_temp;
}
private function generate(){
$this->out_string = str_replace("///DATAPLACEHOLDER///", rtrim($this->out_array_to_string()), configuration_manipulator::FILE_BASE);
$this->out_string = str_replace("///DATEPLACEHOLDER///", date("c"), $this->out_string);
return $this->out_string;
}
private function eval_path($path){
if(empty($path)) return false;
// Clean up the path
$temp = explode("/", $path);
if(count($temp) > 4) return false;
if(empty($temp[0])) array_shift($temp);
if(empty($temp[count($temp) - 1])) array_pop($temp);
list($parent, $child) = $temp;
return array($parent, $child);
}
public function write(){
$out = find("include/") . "configuration.php";
if(!($file_handle = fopen($out, "w"))){
die("Could not lock $out for writing");
}
fwrite($file_handle, $this->generate());
fclose($file_handle);
}
}
?>
|
gpl-3.0
|
tosinoni/SECP
|
SECP-service/src/test/java/com/visucius/secp/models/ReflectTool.java
|
1036
|
package com.visucius.secp.models;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTool {
public static <T extends Annotation> T getMethodAnnotation(
Class<?> c, String methodName, Class<T> annotation) {
try {
Method m = c.getDeclaredMethod(methodName);
return (T)m.getAnnotation(annotation);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
}
public static <T extends Annotation> T getFieldAnnotation(
Class<?> c, String fieldName, Class<T> annotation) {
try {
Field f = c.getDeclaredField(fieldName);
return (T)f.getAnnotation(annotation);
} catch (NoSuchFieldException nsme) {
throw new RuntimeException(nsme);
}
}
public static <T extends Annotation> T getClassAnnotation(
Class<?> c, Class<T> annotation) {
return (T) c.getAnnotation(annotation);
}
}
|
gpl-3.0
|
depweb2/platform
|
panel_cours.php
|
7742
|
<?php
ob_start();
require("/admin/verify_login.php");
if ($IS_LOGGED_IN) {
?>
<!DOCTYPE html>
<!--
dep.web 2.0 - panneau d'administration des sites web des élèves
par andré-luc huneault
14 décembre 2015
-->
<html>
<head>
<meta charset="UTF-8">
<title>Administration</title>
<?php
require("/include/styles.php");
require("/include/scripts.php");
?>
<style>
body{
margin: 0 auto;
padding: 0;
width: 100%;
height: 100%;
position: relative;
}
.dep-settings-section{
padding: 8px;
}
td{
padding: 5px;
}
</style>
</head>
<body>
<?php
require("./include/loading.php");
require("/include/panel_sidebar.php");
?>
<div id="panel_cours" class="w3-modal fs" style='display: table !important;'>
<div class="w3-modal-dialog">
<div class="w3-modal-content">
<header class="w3-container w3-theme">
<h2>
<a class="nou menu-link" href="javascript:void(0)" onclick='w3_toggle()'>
Modules et stages
</a>
</h2>
</header>
<div class="w3-modal-main-container">
<table class='w3-bordered w3-striped w3-theme-l4'>
<tr class='w3-theme-d2 fixed-table-headers'>
<th>Nom du module</th>
<th>Nom générique</th>
<th>Type de module</th>
<th>Durée du cours</th>
<th>Enseignants</th>
<th>Plan de cours</th>
<th>Modifier</th>
</tr>
<?php
// connexion à la base de données
$odbc = odbc_connect("depweb", "user", "user");
$result1 = odbc_exec($odbc, "SELECT * FROM cours ORDER BY id_cours;");
odbc_fetch_row($result1, 0);
while (odbc_fetch_row($result1)) {
// récupère l'information pour la sortie
$idc = odbc_result($result1, "id_cours");
$nomc = utf8_encode(odbc_result($result1, "nom_cours"));
$nidc = utf8_encode(odbc_result($result1, "nid_cours"));
$typec = odbc_result($result1, "stage");
$durc = odbc_result($result1, "dur_cours");
$sdurc = odbc_result($result1, "stage_dur_semaine");
echo "<tr><td><a target='_blank' href='/cours.php?c=$nidc'>$nomc (M$idc)</a></td><td>$nidc</td>";
if ($typec) {
echo "<td>Stage</td><td>$durc jours (" . $sdurc . "h/sem.)</td>";
} else {
echo "<td>Cours</td><td>$durc heures</td>";
}
echo "<td style='width: 1%;'><a class='w3-btn w3-blue' href='javascript:void(0)' onclick='load_cours_prof($idc)'>Enseignants</a><td style='width: 1%;'><a class='upload-btn w3-btn w3-teal' style='width: 150px;' href='javascript:void(0)' onclick='load_plan_add($idc)'>Plan de cours</a></td><td style='width: 1%;'><a class='full w3-btn w3-theme' href='javascript:void(0)' onclick='load_cours_edit($idc)'>Modifier</a></td></tr>";
}
?>
</table>
</div>
</div>
</div>
</div>
<div id="cours_edit_container">
</div>
<script>
window.onload = function () {
// messages d'information
<?php
if (array_key_exists("update", $_GET)) {
echo "alert('La base de données des cours a été mise à jour avec succès.');";
}
if (array_key_exists("enserror", $_GET)) {
echo "alert(\"Erreur lors de la mise à jour de l'association des enseignants au cours.\");";
if (isset($_GET["cid"])) {
if ($_GET["cid"] != "") {
echo "load_cours_prof(" . $_GET["cid"] . ");";
}
}
}
if (array_key_exists("notpdf", $_GET)) {
echo "alert(\"Erreur lors de l'enregistrement. Le fichier spécifié n'est pas un PDF.\");";
if (isset($_GET["cid"])) {
if ($_GET["cid"] != "") {
echo "load_plan_add(" . $_GET["cid"] . ");";
}
}
}
if (array_key_exists("uploaderror", $_GET)) {
echo "alert(\"Une erreur est survenue pendant le téléversement. Veuillez réessayer.\");";
if (isset($_GET["cid"])) {
if ($_GET["cid"] != "") {
echo "load_plan_add(" . $_GET["cid"] . ");";
}
}
}
if (array_key_exists("error", $_GET)) {
echo "alert(\"Erreur lors de l'enregistrement. La valeur saisie n'est pas un nombre valide.\");";
if (isset($_GET["cid"])) {
if ($_GET["cid"] != "") {
echo "load_cours_edit(" . $_GET["cid"] . ");";
}
}
}
?>
};
function load_cours_prof(id) {
// charge par XMLHTTP le foumulaure d'édition et l'affiche
// si aucun id n'est trouvé une erreur 403 se produit (c'est voulu)
$("#cours_edit_container").load("/include/cours_prof_edit.php", {
"dic": id
}, function () {
location.hash = "#cours_edit";
});
}
function load_plan_add(id) {
// charge par XMLHTTP le foumulaure d'édition et l'affiche
// si aucun id n'est trouvé une erreur 403 se produit (c'est voulu)
$("#cours_edit_container").load("/include/cours_plan_edit.php", {
"dic": id
}, function () {
location.hash = "#cours_edit";
});
}
function load_cours_edit(id) {
// charge par XMLHTTP le foumulaure d'édition et l'affiche
// si aucun id n'est trouvé une erreur 403 se produit (c'est voulu)
$("#cours_edit_container").load("/include/cours_edit.php", {
"dic": id
}, function () {
location.hash = "#cours_edit";
});
}
</script>
<a href="javascript:void(0)" onclick="gototop()" title="Haut de la page" class="w3-animate-bottom w3-card-2 short top w3-btn-floating-large w3-theme-dark">
<img src="images/ic_expand_less_white_18dp.png" alt=""/>
</a>
</body>
</html>
<?php
}
|
gpl-3.0
|
Whitetigerswt/gtasa_crashfix
|
crashes/crashes/game_sa/CAnimBlendHierarchySA.cpp
|
593
|
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: game_sa/CAnimBlendHierarchySA.cpp
* PURPOSE: Animation blend hierarchy
* DEVELOPERS: Jax <>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
int CAnimBlendHierarchySAInterface::GetIndex ( void )
{
return ( ( ( DWORD ) this - ARRAY_CAnimManager_Animations ) / 24 );
}
|
gpl-3.0
|
sklintyg/webcert
|
web/src/main/java/se/inera/intyg/webcert/web/service/diagnos/DiagnosService.java
|
3320
|
/*
* Copyright (C) 2022 Inera AB (http://www.inera.se)
*
* This file is part of sklintyg (https://github.com/sklintyg).
*
* sklintyg 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.
*
* sklintyg 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 se.inera.intyg.webcert.web.service.diagnos;
import se.inera.intyg.common.support.common.enumerations.Diagnoskodverk;
import se.inera.intyg.webcert.web.service.diagnos.dto.DiagnosResponse;
/**
* Supplies services related to diagnosises.
*
* @author npet
*/
public interface DiagnosService {
/**
* Returns all diagnoses in the repository exactly matching the code.
*
* @param code The code to search for.
* @param codeSystem A String representing the code system to which the code belongs.
*/
DiagnosResponse getDiagnosisByCode(String code, String codeSystem);
/**
* Returns all diagnoses in the repository exactly matching the code.
*
* @param code The code to search for.
* @param codeSystem The code system to which the code belongs (i.e ICD-10-SE or KSH97P)
*/
DiagnosResponse getDiagnosisByCode(String code, Diagnoskodverk codeSystem);
/**
* Searches the repository for codes beginning with the codeFragment. Limits the number of matches returned.
*
* @param codeFragment The string to search codes by. The string must at least correspond to the pattern 'A01'.
* @param codeSystem The code system to which the code belongs (i.e ICD-10-SE or KSH97P)
* @param nbrOfResults The number of results to return, must be larger than 0.
*/
DiagnosResponse searchDiagnosisByCode(String codeFragment, String codeSystem, int nbrOfResults);
/**
* Searches the repository for descriptions matching searchString. Limits the number of matches returned.
*
* @param searchString The string to search for in descriptions.
* @param codeSystem The code system to which the code belongs (i.e ICD-10-SE or KSH97P)
* @param nbrOfResults The number of results to return, must be larger than 0.
*/
DiagnosResponse searchDiagnosisByDescription(String searchString, String codeSystem, int nbrOfResults);
/**
* Validates that the supplied code fragment is syntactically correct.
*
* @param codeFragment The code to be validated.
* @param codeSystem The code system to which the code belongs (i.e ICD-10-SE or KSH97P)
* @return true if the code fragment is syntactically correct.
*/
boolean validateDiagnosisCode(String codeFragment, String codeSystem);
/**
* Validates that the diagnosis code has a valid format.
*
* @param code The code to be validated.
* @return true if the code is valid.
*/
boolean validateDiagnosisCodeFormat(String code);
}
|
gpl-3.0
|
immartian/musicoin
|
js/src/dapps/localtx/Application/application.js
|
5359
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import BigNumber from 'bignumber.js';
import React, { Component } from 'react';
import { api } from '../parity';
import styles from './application.css';
import { Transaction, LocalTransaction } from '../Transaction';
export default class Application extends Component {
state = {
loading: true,
transactions: [],
localTransactions: {},
blockNumber: 0
}
componentDidMount () {
const poll = () => {
this._timeout = window.setTimeout(() => {
this.fetchTransactionData().then(poll).catch(poll);
}, 1000);
};
poll();
}
componentWillUnmount () {
clearTimeout(this._timeout);
}
fetchTransactionData () {
return Promise.all([
api.parity.pendingTransactions(),
api.parity.pendingTransactionsStats(),
api.parity.localTransactions(),
api.eth.blockNumber()
]).then(([pending, stats, local, blockNumber]) => {
// Combine results together
const transactions = pending.map(tx => {
return {
transaction: tx,
stats: stats[tx.hash],
isLocal: !!local[tx.hash]
};
});
// Add transaction data to locals
transactions
.filter(tx => tx.isLocal)
.map(data => {
const tx = data.transaction;
local[tx.hash].transaction = tx;
local[tx.hash].stats = data.stats;
});
// Convert local transactions to array
const localTransactions = Object.keys(local).map(hash => {
const data = local[hash];
data.txHash = hash;
return data;
});
// Sort local transactions by nonce (move future to the end)
localTransactions.sort((a, b) => {
a = a.transaction || {};
b = b.transaction || {};
if (a.from && b.from && a.from !== b.from) {
return a.from < b.from;
}
if (!a.nonce || !b.nonce) {
return !a.nonce ? 1 : -1;
}
return new BigNumber(a.nonce).comparedTo(new BigNumber(b.nonce));
});
this.setState({
loading: false,
transactions,
localTransactions,
blockNumber
});
});
}
render () {
const { loading } = this.state;
if (loading) {
return (
<div className={ styles.container }>Loading...</div>
);
}
return (
<div className={ styles.container }>
<h1>Your local transactions</h1>
{ this.renderLocals() }
<h1>Transactions in the queue</h1>
{ this.renderQueueSummary() }
{ this.renderQueue() }
</div>
);
}
renderQueueSummary () {
const { transactions } = this.state;
if (!transactions.length) {
return null;
}
const count = transactions.length;
const locals = transactions.filter(tx => tx.isLocal).length;
const fee = transactions
.map(tx => tx.transaction)
.map(tx => tx.gasPrice.mul(tx.gas))
.reduce((sum, fee) => sum.add(fee), new BigNumber(0));
return (
<h3>
Count: <strong>{ locals ? `${count} (${locals})` : count }</strong>
Total Fee: <strong>{ api.util.fromWei(fee).toFixed(3) } ETH</strong>
</h3>
);
}
renderQueue () {
const { blockNumber, transactions } = this.state;
if (!transactions.length) {
return (
<h3>The queue seems is empty.</h3>
);
}
return (
<table cellSpacing='0'>
<thead>
{ Transaction.renderHeader() }
</thead>
<tbody>
{
transactions.map((tx, idx) => (
<Transaction
key={ tx.transaction.hash }
idx={ idx + 1 }
isLocal={ tx.isLocal }
transaction={ tx.transaction }
stats={ tx.stats }
blockNumber={ blockNumber }
/>
))
}
</tbody>
</table>
);
}
renderLocals () {
const { localTransactions } = this.state;
if (!localTransactions.length) {
return (
<h3>You haven't sent any transactions yet.</h3>
);
}
return (
<table cellSpacing='0'>
<thead>
{ LocalTransaction.renderHeader() }
</thead>
<tbody>
{
localTransactions.map(tx => (
<LocalTransaction
key={ tx.txHash }
hash={ tx.txHash }
transaction={ tx.transaction }
status={ tx.status }
stats={ tx.stats }
details={ tx }
/>
))
}
</tbody>
</table>
);
}
}
|
gpl-3.0
|
Hulva/blogme
|
models/comment.js
|
721
|
var mongoose = require('mongoose');
var BaseModel = require('./base_model');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
article_id: {type: String}, // 文章id
name: {type: String}, // 发表评论的人的用户名
title: {type: String}, // 评论的博文标题
head_image_url: {type: String},// 发表评论的人的头像
commenter_url: {type: String}, // 评论人主页地址
content: {type: String}, // 评论内容
create_at: {type: Date, default: Date.now}, // 评论发表时间
update_at: {type: Date, default: Date.now}, // 评论修改时间
}, {
collection: 'comments'
});
CommentSchema.plugin(BaseModel);
mongoose.model('Comment', CommentSchema);
|
gpl-3.0
|
waverzy/little
|
routes/login.js
|
850
|
var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
router.get('/', function(req, res) {
res.render('login', { title: 'Login' });
});
router.post('/', function(req, res) {
var mobile = req.body.mobile,
password = req.body.password;
User.getByMobile(mobile, function(err, user) {
if(err) {
return res.send({'msg': err, 'code': '2001'});
}
if(user) {
if(user.password == password) {
return res.send({'msg': 'success', 'data': {'mobile': user.mobile, 'user_id': user._id.toString()}});
} else {
return res.send({'msg': '密码错误', 'code': '1002'});
}
}
return res.send({'msg': '用户不存在', 'code': '1001'});
})
});
module.exports = router;
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/admin/view/javascript/ckeditor/plugins/a11yhelp/lang/vi.js
|
50
|
OpenCart 1.5.4 = 215d06cd865b5f3dc83b5c4dab59ff8c
|
gpl-3.0
|
ankursachdeva11/buynbrag
|
skin/adminhtml/default/default/aw_blog/js/tiny_mce/themes/simple/editor_template_src.js
|
3289
|
/**
* $Id: editor_template_src.js 920 2008-09-09 14:05:33Z spocke $
*
* This file is meant to showcase how to create a simple theme. The advanced
* theme is more suitable for production use.
*
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*/
(function() {
var DOM = tinymce.DOM;
// Tell it to load theme specific language pack(s)
tinymce.ThemeManager.requireLangPack('simple');
tinymce.create('tinymce.themes.SimpleTheme', {
init : function(ed, url) {
var t = this, states = ['Bold', 'Italic', 'Underline', 'Strikethrough', 'InsertUnorderedList', 'InsertOrderedList'], s = ed.settings;
t.editor = ed;
ed.onInit.add(function() {
ed.onNodeChange.add(function(ed, cm) {
tinymce.each(states, function(c) {
cm.get(c.toLowerCase()).setActive(ed.queryCommandState(c));
});
});
ed.dom.loadCSS(url + "/skins/" + s.skin + "/content.css");
});
DOM.loadCSS((s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : '') || url + "/skins/" + s.skin + "/ui.css");
},
renderUI : function(o) {
var t = this, n = o.targetNode, ic, tb, ed = t.editor, cf = ed.controlManager, sc;
n = DOM.insertAfter(DOM.create('span', {id : ed.id + '_container', 'class' : 'mceEditor ' + ed.settings.skin + 'SimpleSkin'}), n);
n = sc = DOM.add(n, 'table', {cellPadding : 0, cellSpacing : 0, 'class' : 'mceLayout'});
n = tb = DOM.add(n, 'tbody');
// Create iframe container
n = DOM.add(tb, 'tr');
n = ic = DOM.add(DOM.add(n, 'td'), 'div', {'class' : 'mceIframeContainer'});
// Create toolbar container
n = DOM.add(DOM.add(tb, 'tr', {'class' : 'last'}), 'td', {'class' : 'mceToolbar mceLast', align : 'center'});
// Create toolbar
tb = t.toolbar = cf.createToolbar("tools1");
tb.add(cf.createButton('bold', {title : 'simple.bold_desc', cmd : 'Bold'}));
tb.add(cf.createButton('italic', {title : 'simple.italic_desc', cmd : 'Italic'}));
tb.add(cf.createButton('underline', {title : 'simple.underline_desc', cmd : 'Underline'}));
tb.add(cf.createButton('strikethrough', {title : 'simple.striketrough_desc', cmd : 'Strikethrough'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('undo', {title : 'simple.undo_desc', cmd : 'Undo'}));
tb.add(cf.createButton('redo', {title : 'simple.redo_desc', cmd : 'Redo'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('cleanup', {title : 'simple.cleanup_desc', cmd : 'mceCleanup'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('insertunorderedlist', {title : 'simple.bullist_desc', cmd : 'InsertUnorderedList'}));
tb.add(cf.createButton('insertorderedlist', {title : 'simple.numlist_desc', cmd : 'InsertOrderedList'}));
tb.renderTo(n);
return {
iframeContainer : ic,
editorContainer : ed.id + '_container',
sizeContainer : sc,
deltaHeight : -20
};
},
getInfo : function() {
return {
longname : 'Simple theme',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
version : tinymce.majorVersion + "." + tinymce.minorVersion
}
}
});
tinymce.ThemeManager.add('simple', tinymce.themes.SimpleTheme);
})();;
|
gpl-3.0
|
helsinkiAUV/auv
|
arduinoMain/motor.hpp
|
1524
|
/*
* Motor class.
* Created by Väinö Katajisto on May 27, 2017.
*
* This file is part of the University of Helsinki AUV source code.
*
* The AUV source code 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 AUV source code 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 source code. If not, see <http://www.gnu.org/licenses/>.
*
* @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
*/
#ifndef MOTOR_HPP_
#define MOTOR_HPP_
//#include "auv.h"
//#include "constants.h"
class Motor
{
private:
int digitalPort; //turning motor on-off
int analogPort; //for the motor signal
int motorSpeedValue = 0;
public:
Motor (int,int);
void stopMotor();
void setMotorSpeed(int);
void setDigitalPort(int);
void setAnalogPort(int);
void setUpArduino();
void updateMotorSpeed();
int getDigitalPort();
int getAnalogPort();
int getMotorSpeedValue();
int convertMotorSpeedValue(int); //input the 0-3, output the arduino signal value
};
#endif /* MOTOR_HPP_ */
|
gpl-3.0
|
valtoni/file-scanner
|
src/main/java/info/boaventura/filescanner/search/Grep.java
|
3213
|
package info.boaventura.filescanner.search;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Grep {
// Charset and decoder for ISO-8859-15
private Charset charset;
private CharsetDecoder decoder;
// Pattern used to parse lines
private Pattern linePattern = Pattern.compile(".*\r?\n");
// The input pattern that we're looking for
private Pattern pattern;
public Grep() {
setupCharset(Charset.defaultCharset());
}
public Grep(Charset charset) {
setupCharset(charset);
}
public Grep(Charset charset, String pattern) {
if (charset == null) {
setupCharset(Charset.defaultCharset());
}
else {
setupCharset(charset);
}
compile(pattern);
}
public Grep(String pattern) {
setupCharset(Charset.defaultCharset());
compile(pattern);
}
public void setupCharset(Charset charset) {
this.charset = charset;
decoder = this.charset.newDecoder();
}
// Compile the pattern
public void compile(String pattern) throws PatternSyntaxException {
this.pattern = Pattern.compile(pattern);
}
// Use the linePattern to break the given CharBuffer into lines, applying
// the input pattern to each line to see if we have a match
private List<MatchedTextFile> grep(File f, CharBuffer cb) {
List<MatchedTextFile> matches = new ArrayList<MatchedTextFile>();
Matcher lm = linePattern.matcher(cb); // Line matcher
Matcher pm = null; // Pattern matcher
int lines = 0;
MatchedTextFile matchedTextFile = new MatchedTextFile(f);
while (lm.find()) {
lines++;
CharSequence cs = lm.group(); // The current line
if (pm == null) {
pm = pattern.matcher(cs);
}
else {
pm.reset(cs);
}
if (pm.find()) {
matchedTextFile.addMatch(new MatchedTextFileSnippet(lines, cs.toString()));
}
if (lm.end() == cb.limit()) {
break;
}
}
if (matchedTextFile.getMatches().size() > 0) {
matches.add(matchedTextFile);
}
return matches;
}
// Search for occurrences of the input pattern in the given file
public List<MatchedTextFile> grep(File f) throws IOException {
List<MatchedTextFile> matches;
// Open the file and then get a channel from the stream
FileInputStream fis = new FileInputStream(f);
try {
FileChannel fc = fis.getChannel();
// Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
// Decode the file into a char buffer
CharBuffer cb = decoder.decode(bb);
// Perform the search
matches = grep(f, cb);
// Close the channel and the stream
fc.close();
return matches;
} finally {
fis.close();
}
}
}
|
gpl-3.0
|
YoannLaala/GorillaEngine
|
Resources/Asset/Gui/Editor/js/widgets/panels/world.js
|
3690
|
class WorldPanel extends Panel
{
constructor(layoutManager)
{
super(layoutManager, "World",
[
{
name: "Create GameObject",
onClick: function ()
{
var id = Editor.panels.world.getSelection();
Gorilla.GameObject.create(id);
}
},
{
name: "Rename",
onClick: function ()
{
var tree = self.dom.jstree(true);
var selection = tree.get_selected()[0];
tree.edit(selection, null, function(node)
{
var id = Editor.panels.world.getSelection();
Gorilla.GameObject.rename(id, node.text);
});
}
},
{
name: "Delete",
onClick: function ()
{
var tree = self.dom.jstree(true);
var selected = tree.get_selected();
if(selected.length != 0)
{
var id = Editor.panels.world.getSelection();
tree.delete_node(selected[0]);
Gorilla.GameObject.destroy(id);
}
}
}
]);
var self =this;
this.onLoaded = function()
{
// triggered when a node is selected (or deselected
self.dom.on('changed.jstree', function (e, data)
{
var selection = self.getSelection();
if(selection) Editor.panels.property.activate();
else Editor.panels.property.deactivate();
Gorilla.GameObject.select(selection);
});
// auto select when right clicking on tree item
self.dom.on('ready.jstree', function(e, data)
{
var tree = self.dom.jstree(true);
var items = self.dom.find("a.jstree-anchor");
items.contextmenu(function()
{
tree.deselect_all(true);
tree.select_node($(this).parent().attr("id"));
});
})
// deselect tree element when clicking outside
self.dom.on("click contextmenu", function(e)
{
if($(e.target).is("#gorilla_layout_world"))
{
var selection = self.getSelection();
if(selection)
{
var tree = self.dom.jstree(true);
tree.deselect_all();
}
}
})
}
this.getSelection = function()
{
var tree = self.dom.jstree(true);
var selected = tree.get_selected();
return selected.length != 0 ? parseInt(selected[0]) : 0;
}
this.onChanged = function(string)
{
var json = JSON.parse(string);
this.dom.jstree(
{
"core" :
{
"check_callback": true ,
"data": json,
"themes":
{
"icons": false
}
}
});
}
this.onGameObjectCreated = function (string)
{
var tree = this.dom.jstree(true);
var json = JSON.parse(string);
var parent = tree.get_node(json["parent"]);
tree.create_node(parent, json);
}
}
}
|
gpl-3.0
|
6f7262/go-chdl
|
main.go
|
2972
|
package main
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"github.com/6f7262/go-chdl/board"
"github.com/6f7262/pipe"
humanize "github.com/dustin/go-humanize"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
URL = kingpin.Arg("url", "Board or thread URL").Required().URL()
Limit = kingpin.Flag("limit", "Concurrent download limit").Default("10").Short('l').Int()
Output = kingpin.Flag("out", "Output directory for downloaded files").Default("chdl").Short('o').String()
ExcludeExtras = kingpin.Flag("exclude-extras", "Exclude extra files").Default("false").Short('e').Bool()
)
type Detail struct {
File board.File
Error error
Size uint64
}
func main() {
kingpin.Parse()
_, thread, err := board.Detail(*URL)
if err != nil {
panic(err)
}
b, err := board.New(*URL)
if err != nil {
panic(err)
}
var (
files []board.File
ferr error
)
if thread == "" {
fmt.Printf("Are you sure you want to download everything in /%s? y/n: ", b.Board())
var in string
fmt.Scanln(&in)
if in != "y" {
return
}
files, ferr = b.Files(*ExcludeExtras)
} else {
files, ferr = b.Thread(thread).Files(*ExcludeExtras)
}
if ferr != nil {
panic(ferr)
}
var (
p = pipe.New(*Limit)
ch = make(chan Detail)
start = time.Now()
done int
downloaded uint64
)
for _, file := range files {
go download(p, ch, file)
}
for {
if done == len(files) {
break
}
d := <-ch
done++
str := fmt.Sprintf("[%d/%d] ", done, len(files))
if d.Error != nil {
fmt.Printf("%sFailed to download %s/%s.%s\n\tReason: %s\n", str,
d.File.Board(), d.File.Name(), d.File.Extension(), d.Error.Error())
} else {
fmt.Printf("%sFinished downloading %s/%s.%s (%s)\b\n", str,
d.File.Board(), d.File.Name(), d.File.Extension(), humanize.Bytes(d.Size))
downloaded += d.Size
}
}
fmt.Printf("Downloaded %d files (%s) in %s\n", len(files), humanize.Bytes(downloaded), time.Since(start))
}
func download(p pipe.Pipe, ch chan Detail, f board.File) {
p.Increment()
go func() {
defer p.Decrement()
if err := os.MkdirAll(filepath.Join(*Output, f.Board()), os.ModePerm); err != nil {
ch <- Detail{File: f, Error: err}
return
}
if _, err := os.Stat(dir(f)); err == nil {
ch <- Detail{File: f, Error: errors.New("File already exists")}
return
}
res, err := http.Get(f.URL())
if err != nil {
ch <- Detail{File: f, Error: err}
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
ch <- Detail{File: f, Error: fmt.Errorf("unexpected status code %d", res.StatusCode)}
return
}
out, err := os.Create(dir(f))
if err != nil {
ch <- Detail{File: f, Error: err}
return
}
defer out.Close()
w, err := io.Copy(out, res.Body)
ch <- Detail{f, err, uint64(w)}
}()
}
func dir(f board.File) string {
return filepath.Join(*Output, f.Board(), fmt.Sprintf("%s.%s", f.Name(),
f.Extension()))
}
|
gpl-3.0
|
JNPA/DPAcalc
|
src/input/bin1.hpp
|
3057
|
/*
Copyright 2014 João Amaral
This file is part of DPA Calc.
DPA Calc 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.
DPA Calc 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 DPA Calc. If not, see http://www.gnu.org/licenses/.
*/
#pragma once
#include "dpacalc.h"
#include "base.hpp"
using namespace std;
namespace SamplesInput
{
#pragma pack(push)
#pragma pack(1)
struct fileheaders {
uint32_t numtraces;
uint32_t numsamples_per_trace;
char datatype;
uint8_t knowndatalength;
};
#pragma pack(pop)
struct queueelement {
unsigned long long id;
long long size;
TracesMatrix traces;
queueelement() {
id = 0;
size = -1;
}
};
class bin1 : public base
{
public:
virtual unsigned long long read ( unsigned long long* id, TracesMatrix* traces );
bin1 ( TCLAP::CmdLine* cmd, timerUtil* _profTimer ) :
base ( cmd, _profTimer ),
nameArg ( "f", "filename", "Input file name", true, "", "path" ),
mlockArg ( "m", "mlock", "mlock entire input file in ram? Use only if you know what you're doing.", false ),
queuemutex(), readytraces() {
cmd->add ( nameArg );
cmd->add ( mlockArg );
};
virtual void init();
~bin1();
DataMatrix readData();
protected:
TCLAP::ValueArg<std::string> nameArg;
TCLAP::SwitchArg mlockArg;
std::mutex input_mutex;
int inputfd;
template <class T> void readSamples ( TracesMatrix traces, unsigned long curtrace, unsigned long startingsample, unsigned long numsamples );
char sampletype;
int samplesize;
void* fileoffset;
DataMatrix data;
void populateQueue();
mutex queuemutex;
long long RealFileSize;
queue<queueelement> readytraces;
unsigned long long getSampleOffset ( unsigned long long trace, unsigned long long samplenum ) {
//trace and samplenum are zero-based
return sizeof ( struct fileheaders ) + trace * ( samplesize * SamplesPerTrace + DATA_SIZE_BYTE ) + samplesize * samplenum;
}
unsigned long long getDataOffset ( unsigned long long trace ) {
//trace and samplenum are zero-based
return sizeof ( struct fileheaders ) + trace * ( samplesize * SamplesPerTrace + DATA_SIZE_BYTE ) + samplesize * SamplesPerTrace;
}
};
}
|
gpl-3.0
|
PascalSteger/NNfunclass
|
doc/src/FFitNN.java
|
10267
|
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Vector;
/**
* FFitNN: feeds network with input/target pairs, invokes training, applies on
* Input, returns most important function with scaling/transformation
*
* @author psteger
* @date Jun 5, 2010
*/
public class FFitNN extends Fitter {
private Network n_;
private int sam_; // # of sampling points of [0,1]
private int ntype_;
private int ndeg_;
/**
* default constructor
*/
public FFitNN() {
sam_ = 20;
// TODO: n_ = new Network( 23, 50, 50, 6 );
n_ = new Network( 10, 20, 20, 2 );
ntype_ = 6;
ndeg_ = 4;
}
/**
* constructor with given input
*
* @param in
*/
public FFitNN(Input in) {
super(
in ); // sets in_ in Fitter
sam_ = in_.getN();
n_ = new Network( sam_,
// 2 * (2 * sam_ + 1) + 1,
(2 * sam_),
(2 * sam_),
// TODO: 6 );
2 );
n_.setInput( in_ );
System.out.println( in_ );
ntype_ = 6;
ndeg_ = 4;
}
public FFitNN(int nn) {
sam_ = 10;
n_ = new Network( 10, nn, nn, 2 );
ntype_ = 6;
ndeg_ = 4;
}
/**
* generate training data
*/
public void generateTraining() {
// sampling with sam_+1 points
// step through all function templates
for ( int i = 1; i <= ntype_; ++i ) {
for ( int j = 1; j <= ndeg_; ++j ) {
final FForm f = new FForm( i, 1.0 * j );
final Vector<Vec> v = new Vector<Vec>();
// calculate y values, normalization later on
// with ymin,
// ymax
double ymin = 1.0e99;
double ymax = -1.0e99;
for ( int k = 0; k < sam_; ++k ) {
// with random Delta x double x = (k +
// 0.5 + 0.1 * Math.random()) * 1.0 /
// sam_;
double x = (k + 0.5) / sam_;
double y = f.eval( x );
if ( y < ymin ) {
ymin = y;
} else if ( y > ymax ) {
ymax = y;
}
v.add( new Vec( x, y ) );
}
// normalize in y direction to [0,1]
double sy = 1.0;
if ( Math.abs( ymax - ymin ) > 1e-10 ) {
sy = 1.0 / (ymax - ymin);
}
double ty = ymin;
for ( int k = 0; k < sam_; ++k ) {
final double y = v.elementAt( k ).getY();
v.elementAt( k ).setY( (y - ty) * sy );
}
// cast to Matrix for Network input
Matrix tt_in = new Matrix( sam_, 1 );
for ( int k = 0; k < sam_; ++k ) {
// for x- and y- input tt_in.set( 2 * k,
// 0, v.elementAt( k ).getX() );
// tt_in.set( 2 * k + 1, 0, v.elementAt(
// k ).getY() );
tt_in.set( k, 0, v.elementAt( k ).getY() );
}
// generate wished network output:
// holds fform type, deg, ( scale, translation )
// TODO:Matrix tt_out = new Matrix( 6, 1 );
Matrix tt_out = new Matrix( 2, 1 );
tt_out.set( 0, 0, i / 6.0 ); // for range [0..1]
tt_out.set( 1, 0, j / 4.0 );
// scale
// TODO:tt_out.set( 2, 0, 1.0 );
// TODO:tt_out.set( 3, 0, 1.0 );
// translation, scaled by t_
// TODO:tt_out.set( 4, 0, 0.0 );
// TODO:tt_out.set( 5, 0, 0.0 );
// store input/output pair in network
n_.setTT( tt_in, tt_out );
// System.out.println( tt_in );
}
}
}
public void setInput( Input in ) {
n_.setInput( in );
}
public void showApplication( double a ) {
final DecimalFormat thdf = new DecimalFormat( "#0.000" );
// apply on input
for ( int i = 1; i <= ntype_; ++i ) {
for ( int j = 1; j <= ndeg_; ++j ) {
n_.setInput( n_.tt_in_.elementAt( (i - 1) * 4 + j - 1 ) );
// System.out.println( n_.fireCascade( a ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
System.out.println( i + " & " + j + " & " + thdf.format( type ) + " & " + thdf.format( deg ) + " \\\\" );
}
}
}
/**
* show error as function of nit
*
* @param nnit
* @param nitmax
* @param a
* @param eta
*/
public void errorEvolution( int nnit, int nitmax, double a, double eta ) {
Matrix E1 = new Matrix( nnit, 24 );
Matrix E2 = new Matrix( nnit, 24 );
for ( int k = 0; k < nnit; ++k ) {
System.out.println( "training the " + k + "th time..." );
// train network for the next nitmax steps
n_.train( nitmax, a, eta );
// determine errors e1, e2 for all functions
for ( int i = 0; i < 6; ++i ) {
for ( int j = 0; j < 4; ++j ) {
n_.setInput( n_.tt_in_.elementAt( i * 4 + j ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
double e1 = Math.pow( type - (i + 1), 2 ) + Math.pow( deg - (j + 1), 2 );
double e2 = Math.pow( Math.round( type ) - (i + 1), 2 ) + Math.pow( Math.round( deg ) - (j + 1), 2 );
E1.set( k, i * 4 + j, e1 );
E2.set( k, i * 4 + j, e2 );
}
}
}
System.out.println( E1 );
System.out.println( " " );
System.out.println( E2 );
}
public void errorNoise( int nnit, int nitmax, double a, double eta ) {
Matrix E1 = new Matrix( 10, 24 );
Matrix E2 = new Matrix( 10, 24 );
for ( int i = 0; i < nnit; ++i ) {
System.out.println( "learn step " + i + "/9" );
n_.train( nnit * nitmax, a, eta );
}
for ( int k = 0; k < 10; ++k ) {
// determine errors e1, e2 for all functions
for ( int i = 0; i < 6; ++i ) {
for ( int j = 0; j < 4; ++j ) {
Matrix noise = new Matrix( 10, 1 );
// errors from 10% to 1%
noise.randomize().mul( 0.1 / (k + 1.0) );
n_.setInput( noise.add( n_.tt_in_.elementAt( i * 4 + j ) ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
double e1 = Math.pow( type - (i + 1), 2 ) + Math.pow( deg - (j + 1), 2 );
double e2 = Math.pow( Math.round( type ) - (i + 1), 2 ) + Math.pow( Math.round( deg ) - (j + 1), 2 );
E1.set( k, i * 4 + j, e1 );
E2.set( k, i * 4 + j, e2 );
}
}
}
System.out.println( E1 );
System.out.println( " " );
System.out.println( E2 );
}
/**
* show error as function of learning rate
*/
public void errorLearningRate() {
double a = 0.1;
int nitmax = 10000;
Matrix E = new Matrix( 10, 10 );
for ( int ta = 0; ta < 10; ++ta ) {
double eta = 0.1 * ta + 0.1;
System.out.println( "learning with eta = " + eta );
n_.reset();
for ( int nnit = 0; nnit < 10; ++nnit ) {
System.out.println( " training step " + nnit + "/9" );
n_.train( nitmax, a, eta );
double e = 0.0;
for ( int i = 0; i < 6; ++i ) {
for ( int j = 0; j < 4; ++j ) {
n_.setInput( n_.tt_in_.elementAt( i * 4 + j ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
double e1 = Math.pow( type - (i + 1), 2 ) + Math.pow( deg - (j + 1), 2 );
e += e1;
}
}
E.set( ta, nnit, e );
}
}
System.out.println( E );
}
/**
* show error as function of sigmoid function
*/
public void errorA() {
double eta = 0.9;
int nitmax = 100000;
Matrix E = new Matrix( 20, 1 );
for ( int k = 0; k < 20; ++k ) {
double a = 0.05 * k + 0.05;
System.out.println( "learning with a = " + a );
n_.reset();
n_.train( nitmax, a, eta );
double e = 0.0;
for ( int i = 0; i < 6; ++i ) {
for ( int j = 0; j < 4; ++j ) {
n_.setInput( n_.tt_in_.elementAt( i * 4 + j ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
double e1 = Math.pow( type - (i + 1), 2 ) + Math.pow( deg - (j + 1), 2 );
e += e1;
}
}
E.set( k, 0, e );
}
System.out.println( E );
}
/*
* (non-Javadoc)
*
* @see Fitter#learnFunction()
*/
@Override
public SFunction findFunction() {
double a = 0.2;
double eta = 0.9;
int nitmax = 1000;
int nnit = 10;
generateTraining();
// errorEvolution( nnit, nitmax, a, eta );
// errorLearningRate();
// errorA();
errorNoise( nnit, nitmax, a, eta );
showApplication( a );
// old,only for finding function with Classificator :
// n_.setInput( in_ );
// test on known pattern type 4, deg 2
// n_.setInput( n_.tt_in_.elementAt( 4 * (4 - 1) + 2 - 1 ) );
// System.out.println( n_.fireCascade( a ) );
// Matrix fin = new Matrix( n_.fireCascade( a ) );
// double type = fin.get( 0, 0 ) * 6.0;
// double deg = fin.get( 1, 0 ) * 4.0;
// System.out.println( "type: " + type + " (" + 4 + "), deg: " +
// deg + " (" + 2 + ")" );
final SFunction f = new SFunction();
// f.setFForm( new FForm( (int) Math.round( type ), (int)
// Math.round( deg ) ) );
// old, not learned: Vec s = new Vec( fin.get( 2, 0 ), fin.get(
// 3, 0 ) );
// Vec s = new Vec( 1.0, 1.0 );
// f.setScale( s );
// old, not learned: Vec t = new Vec( fin.get( 4, 0 ), fin.get(
// 5, 0 ) );
// Vec t = new Vec( 0.0, 0.0 );
// f.setTranslation( t );
return f;
}
public double findError() {
double a = 0.2;
double eta = 0.9;
int nitmax = 100000;
double e = 0.0;
generateTraining();
n_.train( nitmax, a, eta );
for ( int i = 0; i < 6; ++i ) {
for ( int j = 0; j < 4; ++j ) {
n_.setInput( n_.tt_in_.elementAt( i * 4 + j ) );
Matrix fin = new Matrix( n_.fireCascade( a ) );
double type = fin.get( 0, 0 ) * 6.0;
double deg = fin.get( 1, 0 ) * 4.0;
double e1 = Math.pow( type - (i + 1), 2 ) + Math.pow( deg - (j + 1), 2 );
e += e1;
}
}
return e;
}
/*
* (non-Javadoc)
*
* @see Fitter#toString()
*/
@Override
public String toString() {
String s = new String( "" );
s += n_.toString();
return s;
}
/**
* test routine
*
* @param args
*/
public static void main( final String[] args ) {
// test fitting of curve
Input in = new Input( 10, 4, 2 );
Matrix E = new Matrix( 20, 2 );
for ( int k = 0; k < 20; ++k ) {
double e = 0.0;
double tstart = 0.0;
Date dstart = new Date();
tstart = 1.0 * dstart.getTime();
System.out.println( "trying network with " + (k + 1) + " hidden neurons, starting @ " + tstart );
FFitNN f = new FFitNN( k + 1 );
e = f.findError();
E.set( k, 0, e );
Date dend = new Date();
double tend = 1.0 * dend.getTime();
E.set( k, 1, tend - tstart );
}
System.out.println( E );
// SFunction s = new SFunction( f.findFunction() );
// System.out.println( s.toString() );
}
}
|
gpl-3.0
|
Ferk/Dungeontest
|
mods/dungeon_artefacts/mechanisms/helpers/punchselect.lua
|
3260
|
mechanisms.registered_punchstates = {}
mechanisms.punchstates = {}
function mechanisms.register_punchstate(name, def)
mechanisms.registered_punchstates[name] = def
end
function mechanisms.end_player_punchstate(player_name, punchstate_name)
local state = mechanisms.punchstates[player_name]
if punchstate_name and state and punchstate_name ~= state.name then
return nil
elseif state and state.name then
mechanisms.end_marking(state.name .. "_" .. player_name)
end
mechanisms.punchstates[player_name] = nil
return state
end
function mechanisms.begin_player_punchstate(player_name, state)
local def = mechanisms.registered_punchstates[state.name]
if not def then
return error("Unregistered punchstate: " .. state.name)
end
mechanisms.punchstates[player_name] = state
mechanisms.start_marking(state.name .. "_" .. player_name, state.nodes or {}, def.get_mark_texture)
end
-- helper function
function mechanisms.absolute_to_relative(node, node_pos, pos)
local dir = minetest.facedir_to_dir(node.param2)
local p = {
x = pos.x - node_pos.x,
z = pos.z - node_pos.z,
y = pos.y - node_pos.y,
}
if dir.x > 0 and dir.z == 0 then
elseif dir.x < 0 and dir.z == 0 then
p.x, p.z = -p.x, -p.z
elseif dir.z > 0 and dir.x == 0 then
p.x, p.z = p.z, -p.x
elseif dir.z < 0 and dir.x == 0 then
p.x, p.z = -p.z, p.x
end
return p
end
function mechanisms.relative_to_absolute(node, node_pos, pos)
local dir = minetest.facedir_to_dir(node.param2)
local p = {
x = node_pos.x,
z = node_pos.z,
y = pos.y + node_pos.y,
}
if dir.x > 0 and dir.z == 0 then
p.x = p.x + pos.x
p.z = p.z + pos.z
elseif dir.x < 0 and dir.z == 0 then
p.x = p.x - pos.x
p.z = p.z - pos.z
elseif dir.z > 0 and dir.x == 0 then
p.x = p.x - pos.z
p.z = p.z + pos.x
elseif dir.z < 0 and dir.x == 0 then
p.x = p.x + pos.z
p.z = p.z - pos.x
end
return p
end
-- handles set up punches
minetest.register_on_punchnode(function(pos, node, puncher, pointed_thing)
local name = puncher:get_player_name(); if name==nil then return end
local state = mechanisms.punchstates[name]
if not state then
return
elseif state.name then
local selection = state.nodes or {}
local def = mechanisms.registered_punchstates[state.name] or {}
if def.on_punchnode_select then
pos = def.on_punchnode_select(pos, node, puncher, pointed_thing)
end
local already_selected = false
for k,p in pairs(selection) do
if p.x==pos.x and p.y==pos.y and p.z==pos.z then
already_selected = k
break
end
end
if already_selected then
local can_unmark, texture = true, nil
if def.on_unmark_node then
can_unmark, texture = def.on_unmark_node(selection[already_selected], node)
end
if can_unmark then
selection[already_selected] = nil
mechanisms.unmark_pos(state.name .. "_" .. name, pos)
elseif texture then -- if instead the texture changed, apply it
mechanisms.mark_pos(state.name .. "_" .. name, pos, texture)
end
else
local can_mark, texture = true, nil
if def.on_mark_node then
can_mark, texture = def.on_mark_node(pos, node)
end
if can_mark then
table.insert(selection, pos)
mechanisms.mark_pos(state.name .. "_" .. name, pos, texture)
end
end
end
end)
|
gpl-3.0
|
davidpodhola/piranhacmsoak-examples
|
MvcApplication6/Properties/AssemblyInfo.cs
|
1366
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MvcApplication6")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MvcApplication6")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ce9f9e83-6d9b-4e29-b49f-079d3de62d0d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-3.0
|
JacobMisirian/JacoChat
|
src/JacoChatClient/Properties/AssemblyInfo.cs
|
1404
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JacoChatClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JacoChatClient")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5c853ad7-f7db-40d1-9578-2ff9965a4f80")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-3.0
|
rocky/python2-trepan
|
trepan/processor/command/jump.py
|
2922
|
# -*- coding: utf-8 -*-
# Copyright (C) 2009, 2013, 2015 Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import inspect, os, sys
# Our local modules
from trepan.processor.command import base_cmd as Mbase_cmd
from trepan.processor import cmdproc as Mcmdproc
class JumpCommand(Mbase_cmd.DebuggerCommand):
"""**jump** *lineno*
Set the next line that will be executed. The line must be within the
stopped or bottom-most execution frame."""
aliases = ('j',)
category = 'running'
execution_set = ['Running']
min_args = 1
max_args = 1
name = os.path.basename(__file__).split('.')[0]
need_stack = False
short_help = 'Set the next line to be executed'
def run(self, args):
if not self.core.is_running(): return False
if self.proc.curindex + 1 != len(self.proc.stack):
self.errmsg("You can only jump within the bottom frame")
return False
if self.proc.curframe.f_trace is None:
self.errmsg("Sigh - operation can't be done here.")
return False
lineno = self.proc.get_an_int(args[1],
("jump: a line number is required, " +
"got %s.") % args[1])
if lineno is None: return False
try:
# Set to change position, update our copy of the stack,
# and display the new position
print(self.proc.curframe.f_trace)
self.proc.curframe.f_lineno = lineno
self.proc.stack[self.proc.curindex] = \
self.proc.stack[self.proc.curindex][0], lineno
Mcmdproc.print_location(self.proc)
except ValueError:
_, e, _ = sys.exc_info()
self.errmsg('jump failed: %s' % e)
return False
pass
if __name__ == '__main__':
from trepan.processor.command import mock
d, cp = mock.dbg_setup()
command = JumpCommand(cp)
print('jump when not running: ', command.run(['jump', '1']))
command.core.execution_status = 'Running'
cp.curframe = inspect.currentframe()
cp.curindex = 0
cp.stack = Mcmdproc.get_stack(cp.curframe, None, None)
command.run(['jump', '1'])
cp.curindex = len(cp.stack)-1
command.run(['jump', '1'])
pass
|
gpl-3.0
|
anttisalonen/brigades2
|
src/brigades/WeaponQuery.cpp
|
1693
|
#include <stdexcept>
#include "WeaponQuery.h"
#define weapon_query_check() do { if(!queryIsValid()) {assert(0); throw std::runtime_error("invalid weapon query"); } } while(0)
namespace Brigades {
WeaponQuery::WeaponQuery(const WeaponPtr s)
: mWeapon(s)
{
}
bool WeaponQuery::queryIsValid() const
{
// TODO
return true;
}
WeaponType WeaponQuery::getWeaponType() const
{
weapon_query_check();
return *mWeapon->getWeaponType();
}
bool WeaponQuery::canShoot() const
{
weapon_query_check();
return mWeapon->canShoot();
}
float WeaponQuery::getRange() const
{
weapon_query_check();
return mWeapon->getRange();
}
float WeaponQuery::getVelocity() const
{
weapon_query_check();
return mWeapon->getVelocity();
}
float WeaponQuery::getLoadTime() const
{
weapon_query_check();
return mWeapon->getLoadTime();
}
float WeaponQuery::getVariation() const
{
weapon_query_check();
return mWeapon->getVariation();
}
float WeaponQuery::getDamageAgainstSoftTargets() const
{
weapon_query_check();
return mWeapon->getDamageAgainstSoftTargets();
}
float WeaponQuery::getDamageAgainstLightArmor() const
{
weapon_query_check();
return mWeapon->getDamageAgainstLightArmor();
}
float WeaponQuery::getDamageAgainstHeavyArmor() const
{
weapon_query_check();
return mWeapon->getDamageAgainstHeavyArmor();
}
const char* WeaponQuery::getName() const
{
weapon_query_check();
return mWeapon->getName();
}
bool WeaponQuery::speedVariates() const
{
weapon_query_check();
return mWeapon->speedVariates();
}
bool WeaponQuery::operator==(const WeaponQuery& f) const
{
return mWeapon == f.mWeapon;
}
bool WeaponQuery::operator!=(const WeaponQuery& f) const
{
return !(*this == f);
}
}
|
gpl-3.0
|
bcharron/spcplayer
|
attack-sample-rate.py
|
289
|
#!/usr/bin/python
SAMPLES_PER_SECOND = 32000
attack_rates = [
4.1,
2.6,
1.5,
1.0,
0.640,
0.380,
0.260,
0.160,
0.096,
0.064,
0.040,
0.024,
0.016,
0.010,
0.006,
0.000
]
for rate in attack_rates:
print "%d, // %0.3f" % ((rate * SAMPLES_PER_SECOND) / (0x800 / 32), rate)
|
gpl-3.0
|
volkukan92/formulator-mathml
|
src/hmath/hmathast/src/data/group/mmd_group.cpp
|
38539
|
/****************************************************************************
**
** Copyright (C) 2010 Andriy Kovalchuk, Vyacheslav Levytskyy,
** Igor Samolyuk, Valentyn Yanchuk (aka "Hermitech Laboratory")
**
** All rights reserved.
** Contact: Hermitech Laboratory (info@mmlsoft.com)
**
** This file is a part of the Formulator MathML Editor project
** (http://www.mmlsoft.com).
**
** Commercial Usage
** Licensees holding valid Formulator Commercial licenses may use this
** file in accordance with the Formulator Commercial License Agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and
** Hermitech Laboratory.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Hermitech Laboratory at info@mmlsoft.com.
**
****************************************************************************/
#include "../uniword/uniword_op.h"
#include "mmd_group.h"
///////////////////////////////////////////////////////////////////////////////
MMD_GroupString::MMD_GroupString( void ) :
MArray<long>( 64, 0, 64 )
{}
MMD_GroupString::MMD_GroupString( const MMD_GroupString& ms ) :
MArray<long>( 64, 0, 64 )
{
copy( &ms );
}
MMD_GroupString* MMD_GroupString::copy( const MMD_GroupString *src )
{
MArray<long>::Copy( *src );
return this;
}
MMD_GroupString::~MMD_GroupString( void )
{
}
///////////////////////////////////////////////////////////////////////////////
MMD_GroupStringArray::MMD_GroupStringArray( void ) :
MArray<MMD_GroupString>( 64, 0, 64 )
{}
MMD_GroupStringArray::MMD_GroupStringArray( const MMD_GroupStringArray& ms ) :
MArray<MMD_GroupString>( 64, 0, 64 )
{
copy( &ms );
}
MMD_GroupStringArray* MMD_GroupStringArray::copy( const MMD_GroupStringArray *src )
{
MArray<MMD_GroupString>::Copy( *src );
return this;
}
MMD_GroupStringArray::~MMD_GroupStringArray( void )
{
}
///////////////////////////////////////////////////////////////////////////////
MMD_Group::MMD_Group( CParseDsrSymbolTable& _smbtable, long power, QString* names, long **arg_table ) :
MMD_Object( _smbtable, DSRDATA_TYPE_ABS_GROUP ),
str_id( power ), table( arg_table, power, power ), subgr_int(8, 0, 8)
{
for( long i = 0; i < power; i++ )
{
if( !names[ i ].length() )
throw "Internal error while group constructing";
str_id.Add( new QString( names[ i ] ) );
}
grp_power = power;
ready = GRT_Ready;
ConstructGetReady();
}
MMD_Group::MMD_Group( CParseDsrSymbolTable& _smbtable, long power, QString* names, MMD_GroupMulTable& arg_table ) :
MMD_Object( _smbtable, DSRDATA_TYPE_ABS_GROUP ),
str_id( power ), table( arg_table ), subgr_int(8, 0, 8)
{
for( long i = 0; i < power; i++ )
{
if( !names[ i ].length() )
throw "Internal error while group constructing";
str_id.Add( new QString( names[ i ] ) );
}
grp_power = power;
ready = GRT_Ready;
ConstructGetReady();
}
long MMD_Group::StartSubGroupList( void )
{
subgrp_det = (BN_TYPE)3;
subgr_int.Flush();
return 0;
}
long MMD_Group::StepSubGroupList( void )
{
MMD_Group* mg;
CDSRBits max_sub_det = ((CBigNumber(1) << GetPower()) - 1);
if( subgrp_det >= max_sub_det )
return -1;
long i, j, k, cb;
CDSRBitsStorage p_sub_det = &subgrp_det;
if( (mg = GetSubGroup( p_sub_det )) == 0 )
{
subgrp_det +=2;
return 0;
}
k = subgr_int.Add( new long[ GetPower() * GetPower() + 1 ] );
(subgr_int[ k ])[ 0 ] = mg->GetPower();
cb = 1;
for( i = 0; i < GetPower(); i++ )
for( j = 0; j < GetPower(); j++ )
{
if( bit( &subgrp_det, i ) && bit( &subgrp_det, j ) )
subgr_int[ k ][ cb++ ] = 1;
else
subgr_int[ k ][ cb++ ] = 0;
}
subgrp_det +=2;
return 1;
}
MIArray<long>& MMD_Group::GetSubGroupList( void )
{
return subgr_int;
}
MIArray<long>& MMD_Group::FillSubGroupList( void )
{
subgr_int.Flush();
MMD_Group* mg;
CDSRBits sub_det, max_sub_det = ((CBigNumber(1) << GetPower()) - 1);
long i, j, k, cb;
for( sub_det = (BN_TYPE)3; sub_det < max_sub_det; sub_det +=2 )
{
CDSRBitsStorage p_sub_det = &sub_det;
if( (mg = GetSubGroup( p_sub_det )) == 0 ) continue;
k = subgr_int.Add( new long[ GetPower() * GetPower() + 1 ] );
(subgr_int[ k ])[ 0 ] = mg->GetPower();
cb = 1;
for( i = 0; i < GetPower(); i++ )
for( j = 0; j < GetPower(); j++ )
{
if( bit( &subgrp_det, i ) && bit( &subgrp_det, j ) )
subgr_int[ k ][ cb++ ] = 1;
else
subgr_int[ k ][ cb++ ] = 0;
}
}
return subgr_int;
}
long MMD_Group::EvalString2Index( const QString& names )
{ // evaluate QString of format "aa * bb * cc ..." or "aa + bb + cc ..."
QStringList res = names.split( QString(" * "), QString::SkipEmptyParts );
res += names.split( QString(" + "), QString::SkipEmptyParts );
return EvalString2Index( res );
}
long MMD_Group::EvalString2Index( const QStringList& names )
{
if(GetReady() != GRT_Ready || names.size() < 2)
return INT_MAX;
long a, b;
a = GetIndex( names.at(0) );
b = GetIndex( names.at(1) );
if( (a == INT_MAX) || (b == INT_MAX) )
return INT_MAX;
int i = 2;
do
{
a = table( a, b );
if( i >= names.size() ) return a;
b = GetIndex( names.at( i++ ) );
}
while( i < names.size() );
return INT_MAX;
}
int MMD_Group::IsNotValid( MMD_GroupMulTable& _table, long _grp_power )
{
long i, j, item;
long **prow = new long*[ _grp_power ];
long **pcolumn = new long*[ _grp_power ];
for( i = 0; i < _grp_power; i++ )
{
prow[ i ] = new long[ _grp_power ];
for( j = 0; j < _grp_power; j++ )
prow[ i ][ j ] = 0;
pcolumn[ i ] = new long[ _grp_power ];
for( j = 0; j < _grp_power; j++ )
pcolumn[ i ][ j ] = 0;
}
for( i = 0; i < _grp_power; i++ )
{
for( j = 0; j < _grp_power; j++ )
{
if( (item = _table( i, j )) >= _grp_power )
return (int)MMD_Group::Range;
if( prow[ i ][ item ] || pcolumn[ j ][ item ] )
return (int)MMD_Group::NotUnique;
prow[ i ][ item ] = 1;
pcolumn[ j ][ item ] = 1;
}
}
for( i = 0; i < _grp_power; i++ )
{
delete[] prow[ i ];
delete[] pcolumn[ i ];
}
delete[] prow;
delete[] pcolumn;
for( i = 0; i < _grp_power; i++ )
{
if( (_table( 0, i ) != i) || (_table( i, 0 ) != i) )
return (int)MMD_Group::NotNeutral;
}
return (int)MMD_Group::ValidGroup;
}
MMD_Group* MMD_Group::GetSubGroup( CDSRBitsStorage& det )
{
if( !bit( det, 0 ) )
return 0;
long *items = new long[ GetPower() ];
long *weights = new long[ GetPower() ];
long i, j, de, weight = 0;
for( i = 0; i < GetPower(); i++ )
{
if( bit( det, i ) )
{
weights[ weight ] = i;
items[ i ] = weight++;
}
else
items[ i ] = -1;
}
long **new_table = new long*[ weight ];
for( i = 0; i < weight; i++ )
new_table[ i ] = new long[ weight ];
for( i = 0; i < weight; i++ )
for( j = 0; j < weight; j++ )
{
de = table( weights[ i ], weights[ j ] );
if( items[ de ] == -1 )
{
for( i = 0; i < weight; i++ )
delete[] new_table[ i ];
delete[] new_table;
delete[] items;
delete[] weights;
return 0;
}
else
new_table[ i ][ j ] = items[ de ];
}
MMD_GroupMulTable tblV( new_table, weight, weight );
if( IsNotValid( tblV, weight ) )
{
for( i = 0; i < weight; i++ )
delete[] new_table[ i ];
delete[] new_table;
delete[] items;
delete[] weights;
return 0;
}
QString *names = new QString[ weight ];
for( i = 0; i < weight; i++ )
names[ i ] = *(str_id[ weights[ i ] ]);
delete[] items;
delete[] weights;
MMD_Group *ret = new MMD_Group( getSmbTable(), weight, names, new_table );
for( i = 0; i < weight; i++ )
delete[] new_table[ i ];
delete[] new_table;
delete[] names;
return ret;
}
//==========================================================================
// Params:
// det - subgroup bits,
// chosen - result gi*H bits,
// left - is left mul
// Returns:
// term's quantity (0 on error)
//==========================================================================
long MMD_Group::Factorization( CDSRBitsStorage& det, long *chosen, bool left )
// ~~~~~~~~~~~~~
{
if( !bit( det, 0 ) )
return 0;
long i, j, index, weight = 0;
long *items = new long[ GetPower() ];
long *weights = new long[ GetPower() ];
for( i = 0; i < GetPower(); i++ )
chosen[ i ] = 0;
for( i = 0; i < GetPower(); i++ )
{
if( bit( det, i ) )
{
items[ i ] = 1;
weights[ weight ] = i;
weight++;
}
else
items[ i ] = 0;
}
/*
if( weight < 2 )
{
delete[] items;
delete[] weights;
return 0;
}
*/
long cb = 0;
for( i = 1; i < GetPower(); i++ )
{
if( !items[ i ] )
{
cb++;
items[ i ] = chosen[ i ] = cb/*1*/; // chosen <-> gi*H
for( j = 0; j < weight; j++ )
{
index = (left ? GetIndex2Index( i, weights[ j ] ) :
GetIndex2Index( weights[ j ], i ));
items[ index ] = chosen[ index ] = cb/*1*/;
}
}
}
delete[] items;
delete[] weights;
return cb + 1;
}
long MMD_Group::GetInv( long index )
{
if( index == 0 )
return index;
for( long i = 1; i < GetPower(); i++ )
if( GetTable( index, i ) == 0 )
return i;
return INT_MAX; // internal error: no inv. item
}
int MMD_Group::IsNormalSubGroup( CDSRBitsStorage& det )
{
if( !bit( det, 0 ) )
return 0;
long i, j, weight = 0;
long *items = new long[ GetPower() ];
long *weights = new long[ GetPower() ];
for( i = 0; i < GetPower(); i++ )
{
if( bit( det, i ) )
{
items[ i ] = 1;
weights[ weight ] = i;
weight++;
}
else
items[ i ] = 0;
}
if( weight < 2 )
{
delete[] items;
delete[] weights;
return 0;
}
long cb, index;
long *tst = new long[ GetPower() ];
long *tst_1 = new long[ GetPower() ];
for( i = 1; i < GetPower(); i++ )
{
if( !items[ i ] )
{
cb = 0;
for( j = 0; j < weight; j++ )
tst[ j ] = tst_1[ j ] = 0;
for( j = 0; j < weight; j++ ) // left mul.
{
index = GetIndex2Index( i, weights[ j ] );
if( !tst[ index ] )
{
tst[ index ] = 1;
cb++;
}
}
for( j = 0; j < weight; j++ ) // right mul. and check
{
index = GetIndex2Index( weights[ j ], i );
if( !tst[ index ] )
{
delete[] items;
delete[] weights;
delete[] tst;
delete[] tst_1;
return 0;
}
else
{
if( !tst_1[ index ] )
{
tst_1[ index ] = 1;
cb--;
}
}
}
if( cb )
{
delete items;
delete weights;
delete tst;
delete tst_1;
return 0;
}
}
}
delete items;
delete weights;
delete tst;
delete tst_1;
return 1;
}
MMD_Group* MMD_Group::GetFactorGroup( CDSRBitsStorage& det, bool check_normal )
// ~~~~~~~~~~~~~~
{
if( check_normal )
if( !IsNormalSubGroup( det ) ) return NULL;
if( !bit( det, 0 ) )
return 0;
long i, j, index, weight = 0;
long *items = new long[ GetPower() ];
long *weights = new long[ GetPower() ];
for( i = 0; i < GetPower(); i++ )
{
if( bit( det, i ) )
{
items[ i ] = 1;
weights[ weight ] = i;
weight++;
}
else
items[ i ] = 0;
}
if( weight < 2 )
{
delete[] items;
delete[] weights;
return 0;
}
long factor_grp_power = GetPower() / weight;
long *deleg = new long[ factor_grp_power ];
deleg[ 0 ] = 0;
long *chosen = new long[ GetPower() ];
for( i = 0; i < GetPower(); i++ )
chosen[ i ] = 0;
long cb = 1;
for( i = 1; i < GetPower(); i++ )
{
if( !items[ i ] )
{
deleg[ cb ] = i;
items[ i ] = chosen[ i ] = cb; // chosen <-> gi*H
for( j = 0; j < weight; j++ )
{
index = GetIndex2Index( i, weights[ j ] );
items[ index ] = chosen[ index ] = cb;
}
cb++;
}
}
// must be (cb == factor_grp_power)
MMD_GroupMulTable *factor_grp_table = new MMD_GroupMulTable( factor_grp_power, factor_grp_power );
for( i = 0; i < factor_grp_power; i++ )
for( j = 0; j < factor_grp_power; j++ )
(*factor_grp_table)( i, j ) = chosen[ GetTable( deleg[ i ], deleg[ j ] ) ];
QString *factor_grp_names = new QString[ factor_grp_power ];
for( i = 0; i < factor_grp_power; i++ )
{
factor_grp_names[ i ] = _T("{ ");
for( j = 0; j < GetPower(); j++ )
{
if( chosen[ j ] == i )
{
factor_grp_names[ i ] += *( str_id[ j ] ) + _T(", ");
}
}
size_t k = factor_grp_names[ i ].length();
factor_grp_names[ i ].replace( k - 2, 1, ' ');
factor_grp_names[ i ].replace( k - 1, 1, '}');
}
MMD_Group *ret = new MMD_Group( getSmbTable(), factor_grp_power, factor_grp_names, *factor_grp_table );
delete[] items;
delete[] weights;
delete[] chosen;
delete[] deleg;
delete factor_grp_table;
delete[] factor_grp_names;
return ret;
}
//==========================================================================
//==========================================================================
bool MMD_Group::CheckPod( long /*pod_count*/, long pod_power, long i, long j, MArray<long>& pod )
{
long _j;
for( _j = 0; _j < pod_power; _j++ )
if( pod[ i * pod_power + _j ] != pod[ j * pod_power + _j ] )
break;
return ( _j == pod_power ) ? false : true;
}
//==========================================================================
//==========================================================================
long MMD_Group::FindPod( long pod_count, long pod_power, MArray<long>& pod, long *new_pod )
{
long i, j, index;
index = INT_MAX;
for( i = 0; i < pod_count; i++ )
{
for( j = 0; j < pod_power; j++ )
{
if( pod[ i * pod_power + j ] != new_pod[ j ] )
break;
}
if( j == pod_power )
{
index = i;
break;
}
}
return index;
}
void MMD_Group::GetReady2GenerateGroup( long items_c, QString* items, long rules_c, QString* left, QString* right )
{
inf_genes.items_c = items_c;
inf_genes.rules_c = rules_c;
long i;
inf_genes.items = new QString[ items_c ];
inf_genes.left = new QString[ rules_c ];
inf_genes.right = new QString[ rules_c ];
for( i = 0; i < items_c; i++ )
inf_genes.items[ i ] = items[ i ];
for( i = 0; i < rules_c; i++ )
{
inf_genes.left[ i ] = left[ i ];
inf_genes.right[ i ] = right[ i ];
}
ready = GRT_Ready2Genes;
}
bool MMD_Group::StartGroupGeneration( void )
{
bool res = false;
if(GetReady() == GRT_Ready2Genes)
res = GenerateGroup( inf_genes.items_c, inf_genes.items, inf_genes.rules_c, inf_genes.left, inf_genes.right );
else if(GetReady() == GRT_Ready2Pods)
{
MArray<long> _pod( inf_pods.pod_count * inf_pods.pod_power, 0, 4 * inf_pods.pod_power );
_pod.resize(inf_pods.pod.end() - inf_pods.pod.begin());
std::copy(inf_pods.pod.begin(), inf_pods.pod.end(), _pod.begin());
res = GenerateGroup( inf_pods.pod_count, inf_pods.pod_power, _pod );
}
if( res )
ready = GRT_Ready;
return res;
}
void MMD_Group::GetReady2GenerateGroup( long pod_count, long pod_power, MArray<long>& pod )
{
inf_pods.pod_count = pod_count;
inf_pods.pod_power = pod_power;
inf_pods.pod.resize(pod.ArrayDim());
std::copy(pod.begin(), pod.end(), inf_pods.pod.begin());
ready = GRT_Ready2Pods;
}
//==========================================================================
// Params:
// items_c - genes quantity,
// pod - pods.
// Returns:
// true - ok, otherwise - false
//==========================================================================
bool MMD_Group::GenerateGroup( long pod_count, long pod_power, MArray<long>& pod )
{
long i, j, index;
str_id.Flush();
if( table.n_row() || table.n_column() )
table.erase_all_column();
index = INT_MAX;
for( i = 0; i < pod_count; i++ )
{
for( j = 0; j < pod_power; j++ )
{
if( pod[ i * pod_power + j ] != j + 1 )
break;
}
if( j == pod_power )
{
index = i;
break;
}
}
if( index == INT_MAX )
{
str_id.Flush();
table.erase_all_column();
return false;
}
else
{
if( index )
for( i = 0; i < pod_power; i++ )
{
j = pod[ i ];
pod[ i ] = i + 1;
pod[ index * pod_power + i ] = j;
}
}
grp_power = pod_count;
long items_c = pod_count;
//QString temp_str( commonGetNeutralElementName() );
QString temp_str( QString( commonGetGroupPodPrefix() ) + _T("1") );
table.add_row();
table.add_column();
str_id.Add( new QString( temp_str ) );
temp_str = commonGetGroupPodPrefix();
for( i = 1; i < pod_count; i++ )
{
table.add_row();
table.add_column();
str_id.Add( new QString( temp_str + QString("%1").arg(i + 1) ) );
}
unsigned long steps = 0, gpow = 1;
long new_1st = 0, new_items_c;
long *new_pod = new long[ pod_power ];
while( !StopGenerating( steps, gpow ) )
{
new_items_c = 0;
for( i = 0; i < items_c + new_1st; i++ )
{
for( j = 0; j < items_c + new_1st; j++ )
{
if( (i < new_1st) && (j < new_1st) )
continue;
if( (i > j) && !CheckPod( pod_count, pod_power, i, j, pod ) )
{
str_id.Flush();
table.erase_all_column();
delete[] new_pod;
return false;
}
long k;
for( k = 0; k < pod_power; k++ )
new_pod[ k ] = pod[ j * pod_power + (pod[ i * pod_power + k ] - 1) ];
if( (index = FindPod( pod_count, pod_power, pod, new_pod )) != INT_MAX )
table( i, j ) = index;
else
{
QString *str = new QString();
*str = QString( temp_str + "%1" ).arg( grp_power + 1 );
str_id.Add( str );
table.add_row();
table.add_column();
table( i, j ) = grp_power++;
new_items_c++;
for( k = 0; k < pod_power; k++ )
pod[ (grp_power - 1) * pod_power + k ] = new_pod[ k ];
pod_count++;
}
}
}
if( new_items_c )
{
steps += items_c;
gpow++;
new_1st += items_c;
items_c = new_items_c;
continue;
}
delete[] new_pod;
// Group ok!
for( i = 0; i < grp_power; i++ )
table( i, 0 ) = table( 0, i ) = i;
if( IsNotValid( GetTable(), GetPower() ) )
{
str_id.Flush();
table.erase_all_column();
return false;
}
return true;
}
str_id.Flush();
table.erase_all_column();
return false;
}
//==========================================================================
// Params:
// items_c - genes quantity,
// items - genes' names,
// rules_c - rules quantity,
// left & right - QString pairs like "a * a * a" & "E"
// Returns:
// true - ok, otherwise - false
//==========================================================================
bool MMD_Group::GenerateGroup( long items_c, QString* items, long rules_c,
QString* left, QString* right )
{
MMD_GroupStringArray* ptr2_tmp_left_idx = new MMD_GroupStringArray();
MMD_GroupStringArray* ptr2_tmp_right_idx = new MMD_GroupStringArray();
MMD_GroupStringArray& tmp_left_idx = *ptr2_tmp_left_idx;
MMD_GroupStringArray& tmp_right_idx = *ptr2_tmp_right_idx;
if( !IsValidGenes( items_c, rules_c, left, right, items, tmp_left_idx, tmp_right_idx ) )
return false;
DeduceNewGenes( tmp_left_idx, tmp_right_idx );
rules_c = (long) tmp_left_idx.ArrayDim();
long i, j;
str_id.Flush();
if( table.n_row() || table.n_column() )
table.erase_all_column();
MArray<long> mem_left( 256, 0, 64 );
MArray<long> mem_right( 256, 0, 64 );
str_id_int_vector str_id_int/*( 256, 0, 64 )*/;
long int_max = INT_MAX;
QString temp_str( commonGetNeutralElementName() );
table.add_row();
table.add_column();
str_id.Add( new QString( temp_str ) );
str_id_int.push_back( std::list<long>(1, long(0)) );
mem_left.Add( int_max );
mem_right.Add( int_max );
for( i = 0; i < items_c; i++ )
{
table.add_row();
table.add_column();
str_id.Add( new QString( items[ i ] ) );
str_id_int.push_back( std::list<long>(1, long(i + 1)) );
mem_left.Add( int_max );
mem_right.Add( int_max );
}
long basic_grp_power = grp_power = items_c + 1;
#if 0
// debug
QString str = _T("");
for( long h = 0; h < rules_c; h++ )
{
long r;
for( r = 0; r < tmp_left_idx[ h ].ArrayDim(); r++ )
str += *(str_id[ tmp_left_idx[ h ][ r ] ]) + " ");
str += _T("=");
for( r = 0; r < tmp_right_idx[ h ].ArrayDim(); r++ )
str += _T(" " + *(str_id[ tmp_right_idx[ h ][ r ] ]);
str += _T("\n");
}
// end debug
#endif
unsigned long steps = 0, gpow = 1;
long new_1st = 1, index, new_items_c;
std::list<long> to_treat;
while( !StopGenerating( steps, gpow ) )
{
new_items_c = 0;
for( i = 1/*new_1st*/; i < items_c + new_1st; i++ )
{
for( j = 1/*new_1st*/; j < items_c + new_1st; j++ )
{
if( (i < new_1st) && (j < new_1st) )
continue;
temp_str = *(str_id[ i ]) + QString( _T(" ") ) + QString(commonGetGroupMultiplicationSign()) + QString( _T(" ") ) + *(str_id[ j ]);
if( (index = str_id.Find( &temp_str )) != INT_MAX )
table( i, j ) = index;
else
{
to_treat.erase( to_treat.begin(), to_treat.end() );
if( i < basic_grp_power )
to_treat.insert(to_treat.end(), i);
else
Unroll( i, to_treat.end(), to_treat, mem_left, mem_right );
if( j < basic_grp_power )
to_treat.insert(to_treat.end(), j);
else
Unroll( j, to_treat.end(), to_treat, mem_left, mem_right );
if( (index = IdentifyFactor( to_treat, rules_c, tmp_left_idx, tmp_right_idx, str_id_int )) == INT_MAX )
{
table.add_row();
table.add_column();
str_id.Add( new QString( temp_str ) );
str_id_int.push_back( to_treat );
mem_left.Add( i );
mem_right.Add( j );
table( i, j ) = grp_power++;
new_items_c++;
}
else
table( i, j ) = index;
}
}
}
if( new_items_c )
{
steps += items_c;
gpow++;
new_1st += items_c;
items_c = new_items_c;
continue;
}
// Group ok!
for( i = 0; i < grp_power; i++ )
table( i, 0 ) = table( 0, i ) = i;
if( IsNotValid( GetTable(), GetPower() ) )
return false;
delete ptr2_tmp_left_idx;
delete ptr2_tmp_right_idx;
return true;
}
delete ptr2_tmp_left_idx;
delete ptr2_tmp_right_idx;
return false;
}
//========================================================================================
struct GRPHystoryList
{
long rule; // number of rule
bool direction; // if true - left (:=, normal) <- right, left -> right
std::vector<long>* lock; // 0 - raw object, 1 - direct rule, 2 - reverse rule
std::list<long>* to_treat; // QString to treat
long del_1st; // first item to be delete
GRPHystoryList( void )
{
to_treat = 0;
lock = 0;
}
GRPHystoryList( const GRPHystoryList& h )
{
rule = h.rule;
direction = h.direction;
del_1st = h.del_1st;
to_treat = new std::list<long>(*(h.to_treat));
lock = new std::vector<long>(*(h.lock));
}
~GRPHystoryList()
{
if( to_treat )
{
delete to_treat;
to_treat = 0;
}
if( lock )
{
delete lock;
lock = 0;
}
}
};
long MMD_Group::IdentifyFactor( std::list<long>& in_to_treat, long rules_c, MMD_GroupStringArray& left, MMD_GroupStringArray& right, str_id_int_vector& str_id_int )
{
long i, k, i2;
bool ok/*, start = true*/;
GRPHystoryList fact;
std::list<long>::iterator location;
std::list<GRPHystoryList>::iterator hystory_location;
unsigned long j2 = 0;
std::list<long> in_to_treat_copy( in_to_treat );
std::list<long>* to_treat = &(in_to_treat_copy);
std::vector<long> to_lock_ref( rules_c, long(0) );
std::vector<long>* to_lock = &(to_lock_ref);
std::list<GRPHystoryList>* hystory = new std::list<GRPHystoryList>;
long hystory_count = 0, hystory_index = 0, hystory_local_count = 0;
std::list<GRPHystoryList>::iterator in_fact = hystory->begin();
std::list<GRPHystoryList>::iterator after_in_fact = hystory->end();
for(;;)
{
hystory_local_count = 0;
for( i = 0; i < rules_c; i++ )
{
bool direction = false;
i2 = 0;
while( i2 < 1/*2*/ )
{
i2++;
direction = !direction;
if( (direction && ((*to_lock)[ i ] == 2)) ||
(!direction && ((*to_lock)[ i ] == 1)) )
break;
MArray<long>& from_part = direction ? left[ i ] : right[ i ];
ok = false;
// for( j = 0; j < from_part.ArrayDim(); j++ )
// {
long lev = 0;
std::list<long>::iterator it = to_treat->begin();
while((it != to_treat->end()) && (lev < (long) to_treat->size()))
{
if( *it == from_part[ 0 ] )
{
std::list<long>::iterator tmp_it = it;
long lleevv = lev;
tmp_it++;
lleevv++;
ok = true;
for( long tmp_j = 1; tmp_j < (long) from_part.ArrayDim(); tmp_j++ )
{
if( /*(tmp_it == to_treat->end())*/!(lleevv < (long) to_treat->size()) || (*tmp_it != from_part[ tmp_j ]) )
{
ok = false;
break;
}
else
{
tmp_it++;
lleevv++;
}
}
if( ok )
break;
else
{
it++;
lev++;
}
}
else
{
it++;
lev++;
}
}
if( ok )
{
fact.rule = i;
fact.del_1st = lev;
fact.direction = direction;
fact.to_treat = new std::list<long>( *to_treat );
fact.lock = new std::vector<long>( *to_lock );
if(!(*to_lock)[ i ])
(*(fact.lock))[ i ] = direction ? 1 : 2;
hystory_location = hystory->begin();
for( j2 = 0; j2 < (unsigned long) (hystory_index + hystory_local_count); j2++ )
hystory_location++;
hystory->insert( hystory_location, fact );
hystory_count++;
hystory_local_count++;
in_fact = hystory->begin();
fact.to_treat = 0;
fact.lock = 0;
}
//}
} // while
}
// <end>
// get current control structure
//if( in_fact == hystory->end() )
if( hystory_index >= hystory_count )
{
delete hystory;
return INT_MAX;
}
in_fact = hystory->begin();
for( j2 = 0; j2 < (unsigned long) hystory_index; j2++ )
in_fact++;
hystory_index++;
/* if( start )
{
in_fact = hystory->begin();
start = false;
}
else
in_fact++;
*/
/*
if( hystory_count >= hystory_location )
{
delete hystory;
return INT_MAX;
}
*/
after_in_fact = in_fact;
after_in_fact++;
// <end>
// constructing QString reduced
MArray<long>& to = (in_fact->direction) ? left[ in_fact->rule ] : right[ in_fact->rule ];
MArray<long>& fro = (in_fact->direction) ? right[ in_fact->rule ] : left[ in_fact->rule ];
location = in_fact->to_treat->begin();
for( j2 = 0; j2 < (unsigned long) in_fact->del_1st; j2++ )
location++;
for( k = 0; k < (long) to.ArrayDim(); k++ )
{
if( location != in_fact->to_treat->end() )
in_fact->to_treat->erase( location++ );
}
if( (fro.ArrayDim() != 1) || (fro[ 0 ] != 0) || !(in_fact->to_treat->size()) ) // not E
{
location = in_fact->to_treat->begin();
for( j2 = 0; j2 < (unsigned long) in_fact->del_1st; j2++ )
location++;
in_fact->to_treat->insert( location, fro.begin(), fro.end() );
}
to_treat = in_fact->to_treat;
to_lock = in_fact->lock;
// <end>
// substring search
// if( in_fact->to_treat->size() == 1 )
// {
for( k = 0; k < (long) str_id_int.size(); k++ )
{
if(to_treat->size() == str_id_int[ k ].size())
{
long lev = 0;
std::list<long>::iterator it_1 = in_fact->to_treat->begin();
std::list<long>::iterator it_2 = str_id_int[ k ].begin();
while(lev < (long) in_fact->to_treat->size())
{
if( *it_1 != *it_2 )
break;
it_1++;
it_2++;
lev++;
}
if( lev == (long) in_fact->to_treat->size() )
{
//long ret = *(in_fact->to_treat->begin());
delete hystory;
return k;
}
}
}
// }
// <end>
}
delete hystory;
return INT_MAX;
}
void MMD_Group::FillInNewGene( long len,
MMD_GroupString& ab_x__left, MMD_GroupString& ab_x__right,
MMD_GroupString& bc_y__left, MMD_GroupString& bc_y__right,
MMD_GroupString& ay_xc__left, MMD_GroupString& ay_xc__right )
{
long i;
for( i = 0; i < (long) ab_x__left.ArrayDim() - len; i++ )
ay_xc__left.Add( ab_x__left[ i ] );
if( bc_y__right[ 0 ] || ( (long) bc_y__right.ArrayDim() != 1 ) )
for( i = 0; i < (long) bc_y__right.ArrayDim(); i++ )
ay_xc__left.Add( bc_y__right[ i ] );
if( ab_x__right[ 0 ] || ( (long) ab_x__right.ArrayDim() != 1 ) )
for( i = 0; i < (long) ab_x__right.ArrayDim(); i++ )
ay_xc__right.Add( ab_x__right[ i ] );
for( i = len; i < (long) bc_y__left.ArrayDim(); i++ )
ay_xc__right.Add( bc_y__left[ i ] );
}
void MMD_Group::SimplifyNewGenes( MMD_GroupString& a, MMD_GroupStringArray& tmp_left_idx, MMD_GroupStringArray& tmp_right_idx )
{
long i, j, j2, k, start_j = 0;
bool ok, change;
do
{
change = false;
for( i = 0; i < (long) tmp_left_idx.ArrayDim(); i++ )
{
ok = false;
for( j = 0; j < (long) a.ArrayDim(); j++ )
{
if( a[ j ] == tmp_left_idx[ i ][ 0 ] )
{
start_j = j;
j2 = j + 1;
ok = true;
for( k = 1; k < (long) tmp_left_idx[ i ].ArrayDim(); k++, j2++ )
{
if( (j2 == a.ArrayDim()) || (a[ j2 ] != tmp_left_idx[ i ][ k ]) )
{
ok = false;
break;
}
}
if( ok ) break;
}
}
if( ok )
{
if( (tmp_right_idx[ i ].ArrayDim() == 1) && (tmp_right_idx[ i ][ 0 ] == 0) )
{
// if(tmp_left_idx[ i ].ArrayDim() == 1)
// a.erase( a.begin() + start_j );
// else
a.erase( a.begin() + start_j, a.begin() + start_j + tmp_left_idx[ i ].ArrayDim()/* - 1 */);
}
else
{
for( j = 0; j < (long) tmp_right_idx[ i ].ArrayDim(); j++ )
a[ start_j + j ] = tmp_right_idx[ i ][ j ];
if( (k = (long) tmp_left_idx[ i ].ArrayDim() - (long) tmp_right_idx[ i ].ArrayDim()) > 0 )
{
// if(k == 1)
// a.erase( a.begin() + start_j + j );
// else
a.erase( a.begin() + start_j + j, a.begin() + start_j + j + k/* - 1*/ );
}
}
change = true;
}
}
}
while( change );
}
long MMD_Group::AddNewGene( long ii, long jj,
MMD_GroupStringArray& tmp_left_idx, MMD_GroupStringArray& tmp_right_idx )
{
MMD_GroupString a, b;
long len, ret, i, index_a, index_b, change_1 = 0, null = 0;
for( len = 1; (len <= (long) tmp_left_idx[ ii ].ArrayDim() - 1) && (len <= (long) tmp_left_idx[ jj ].ArrayDim()); len++ )
{
for( i = 0; i < len; i++ )
{
if( tmp_left_idx[ ii ][ i ] != (long) tmp_left_idx[ jj ][ tmp_left_idx[ jj ].ArrayDim() - len + i ] )
break;
}
if( i == len )
{
a.Flush();
b.Flush();
FillInNewGene( len, tmp_left_idx[ jj ], tmp_right_idx[ jj ], tmp_left_idx[ ii ], tmp_right_idx[ ii ], a, b );
SimplifyNewGenes( a, tmp_left_idx, tmp_right_idx );
SimplifyNewGenes( b, tmp_left_idx, tmp_right_idx );
if( a.ArrayDim() == 0 ) a.Add( null );
if( b.ArrayDim() == 0 ) b.Add( null );
ret = compare(a, b);
if( ret )
{
if( ret == 1 )
{
if( ((index_a = tmp_left_idx.Find( a )) == INT_MAX) ||
((index_b = tmp_right_idx.Find( b )) == INT_MAX) ||
(index_a != index_b) )
{
tmp_left_idx.Add( a );
tmp_right_idx.Add( b );
change_1++;
}
}
else
{
if( ((index_b = tmp_left_idx.Find( b )) == INT_MAX) ||
((index_a = tmp_right_idx.Find( a )) == INT_MAX) ||
(index_b != index_a) )
{
tmp_left_idx.Add( b );
tmp_right_idx.Add( a );
change_1++;
}
}
}
}
}
return change_1;
}
void MMD_Group::DeduceNewGenes( MMD_GroupStringArray& tmp_left_idx, MMD_GroupStringArray& tmp_right_idx )
{
//const double growing_koef = 10; // rules quantity can't be increased more than in 10 time
const long deepest_change_step = 10;
long i, j, cb, new_c;
long start_c, rules_c;
start_c = 0;
rules_c = (long) tmp_left_idx.ArrayDim();
cb = 0;
do
{
new_c = 0;
if( start_c )
{
for( i = 0; i < start_c; i++ )
for( j = start_c; j < rules_c; j++ )
new_c += AddNewGene( i, j, tmp_left_idx, tmp_right_idx );
for( i = start_c; i < rules_c; i++ )
for( j = 0; j < start_c; j++ )
new_c += AddNewGene( i, j, tmp_left_idx, tmp_right_idx );
}
for( i = start_c; i < rules_c; i++ )
for( j = start_c; j < rules_c; j++ )
new_c += AddNewGene( i, j, tmp_left_idx, tmp_right_idx );
start_c = rules_c;
rules_c += new_c;
cb++;
}
while( new_c && (cb < deepest_change_step) );
}
bool MMD_Group::StopGenerating( unsigned long steps, unsigned long gpow )
{
return (( steps > 256 ) || ( gpow > 8 ));
}
bool MMD_Group::IsValidGenes( long item_c, long argc, QString* left, QString *right, QString *items, MMD_GroupStringArray& tmp_left_idx, MMD_GroupStringArray& tmp_right_idx )
{
long i, j, k;
QString str;
MArray<QString> tmp_left( 256, 0, 64 ), tmp_right( 256, 0, 64 );
for( i = 0; i < argc; i++ )
{
tmp_left.Flush();
tmp_left_idx[ i ].Flush();
j = 0;
for(;;)
{
str = _T("");
for( ; (j < (long) left[ i ].length()) && (left[ i ].at(j) != _T(' ')); j++ )
{
str += left[ i ].at(j);
}
if( str == commonGetNeutralElementName() )
k = 0;
else
{
for( k = 1; k < item_c + 1; k++ )
{
if( items[ k - 1 ] == str )
break;
}
if( k == item_c + 1 )
return false;
}
tmp_left_idx[ i ].Add( k );
tmp_left.Add( str );
if( j == left[ i ].length() )
break;
else
j += 3;
}
tmp_right.Flush();
tmp_right_idx[ i ].Flush();
j = 0;
for(;;)
{
str = _T("");
for( ; (j < (long) right[ i ].length()) && (right[ i ].at(j) != _T(' ')); j++ )
{
str += right[ i ].at(j);
}
if( str == commonGetNeutralElementName() )
k = 0;
else
{
for( k = 1; k < item_c + 1; k++ )
{
if( items[ k - 1 ] == str )
break;
}
if( k == item_c + 1 )
return false;
}
tmp_right_idx[ i ].Add( k );
tmp_right.Add( str );
if( j == right[ i ].length() )
break;
else
j += 3;
}
if( !Equilibrium( tmp_left_idx[ i ], tmp_right_idx[ i ] ) )
return false;
}
// lets's sort
return true;
}
bool MMD_Group::Equilibrium( MMD_GroupString& left_idx, MMD_GroupString& right_idx )
{
MMD_GroupString tmp;
if( left_idx.ArrayDim() < right_idx.ArrayDim() )
{
tmp = left_idx;
left_idx = right_idx;
right_idx = tmp;
}
else if( left_idx.ArrayDim() == right_idx.ArrayDim() )
{
long k;
for( k = 0; k < (long) left_idx.ArrayDim(); k++ )
{
if( left_idx[ k ] > right_idx[ k ] )
break;
if( left_idx[ k ] < right_idx[ k ] )
{
tmp = left_idx;
left_idx = right_idx;
right_idx = tmp;
break;
}
}
if( k == left_idx.ArrayDim() )
return false;
}
return true;
}
int compare( const MMD_GroupString& left_idx, const MMD_GroupString& right_idx )
{
long ret = -1;
if( left_idx.ArrayDim() < right_idx.ArrayDim() )
{
ret = -1;
}
else
{
if( left_idx.ArrayDim() == right_idx.ArrayDim() )
{
long k;
for( k = 0; k < (long) left_idx.ArrayDim(); k++ )
{
if( left_idx[ k ] > right_idx[ k ] )
{
ret = 1;
break;
}
if( left_idx[ k ] < right_idx[ k ] )
{
ret = -1;
break;
}
}
if( k == left_idx.ArrayDim() )
ret = 0;
}
else
ret = 1;
}
return ret;
}
void MMD_Group::Unroll( long i, std::list<long>::iterator it, std::list<long>& to_treat, MArray<long>& mem_left, MArray<long>& mem_right )
{
if( (mem_left[ i ] == INT_MAX) && (mem_right[ i ] == INT_MAX) )
to_treat.insert( it, i );
else
{
Unroll( mem_left[ i ], it, to_treat, mem_left, mem_right );
Unroll( mem_right[ i ], it, to_treat, mem_left, mem_right );
}
}
///////////////////////////////////////////////////////////////////////////////
MMD_Object* MMD_Group::copy( const MMD_Group* ms )
{
MMD_Object::copy( ms );
ready = ms->ready;
grp_power = ms->grp_power;
long i;
str_id.Flush();
for( i = 0; i < (long) ms->str_id.ArrayDim(); i++ )
str_id.Add( new QString( *(ms->str_id[ i ]) ) );
table = ms->table;
subgr_int.Flush();
for( i = 0; i < (long) ms->subgr_int.ArrayDim(); i++ )
subgr_int.Add( new long( *(ms->subgr_int[ i ]) ) );
subgrp_det = ms->subgrp_det;
return this;
}
MMD_Group::MMD_Group( CParseDsrSymbolTable& _smbtable ) :
MMD_Object( _smbtable, DSRDATA_TYPE_ABS_GROUP ),
str_id( 256, 0, 64 ), subgr_int( 8, 0, 8 )
{
grp_power = -1;
ready = GRT_Raw;
ConstructGetReady();
}
MMD_Group::MMD_Group( const MMD_Group& ms ) :
MMD_Object( ms ),
str_id( 256, 0, 64 ), subgr_int( 8, 0, 8 )
{
//copy( &ms );
ready = ms.ready;
grp_power = ms.grp_power;
long i;
str_id.Flush();
for( i = 0; i < (long) ms.str_id.ArrayDim(); i++ )
str_id.Add( new QString( *(ms.str_id[ i ]) ) );
table = ms.table;
subgr_int.Flush();
for( i = 0; i < (long) ms.subgr_int.ArrayDim(); i++ )
subgr_int.Add( new long( *(ms.subgr_int[ i ]) ) );
subgrp_det = ms.subgrp_det;
}
MMD_Group::~MMD_Group( void )
{
ReleaseGetReady();
}
enum GroupReadyTo MMD_Group::GetReady( void )
{
return ready;
}
long& MMD_Group::GetTable( long a, long b ) // a - row, b - column
{
return table( a, b );
}
MMD_GroupMulTable& MMD_Group::GetTable( void ) // a - row, b - column
{
return table;
}
QString MMD_Group::GetGroupNeutralElementName( void )
{
return str_id[ 0 ] ? *(str_id[ 0 ]) : _T("");
}
long MMD_Group::GetPower( void )
{
return grp_power;
}
QString MMD_Group::GetInv( const QString& a )
{
return GetString( GetInv( GetIndex( a ) ) );
}
long MMD_Group::GetIndex( const QString& name )
{
QString str( name );
return str_id.Find( &str );
}
QString MMD_Group::GetString( long index )
{
if( index >= grp_power )
return QString("");
return str_id[ index ] ? *(str_id[ index ]) : _T("");
}
long MMD_Group::GetIndex2Index( long a, long b )
{
return table( a, b );
}
QString MMD_Group::GetString2String( const QString& a, const QString& b )
{
long x = GetIndex( a );
long y = GetIndex( b );
if( (x == INT_MAX) || (y == INT_MAX) )
return QString("");
else
return GetString( GetIndex2Index( x, y ) );
}
QString MMD_Group::EvalString2String( const QStringList& names )
{
long index = EvalString2Index( names );
return (index == INT_MAX) ? QString("") : GetString( index );
}
QString MMD_Group::EvalString2String( const QString& names )
{
long index = EvalString2Index( names );
return (index == INT_MAX) ? QString("") : GetString( index );
}
void MMD_Group::ConstructGetReady( void )
{
inf_genes.items = inf_genes.left = inf_genes.right = 0;
}
void MMD_Group::ReleaseGetReady( void )
{
if( GetReady() == GRT_Ready2Genes )
{
if( inf_genes.items ) delete inf_genes.items;
if( inf_genes.left ) delete inf_genes.left;
if( inf_genes.right ) delete inf_genes.right;
}
}
///////////////////////////////////////////////////////////////////////////////
|
gpl-3.0
|
brettc/bricolage
|
bricolage/dot_layout.py
|
11723
|
import pathlib
from pygraphviz import AGraph
from pyx_drawing import Diagram
from bricolage.graph_maker import (
NodeType,
BaseGraph,
GraphType,
decode_module_id,
get_graph_by_type,
node_logic_differs,
)
from analysis import NetworkAnalysis
_dot_default_args = '-Nfontname="Helvetica-8"'
class DotMaker(object):
"""Convert an NXGraph into an AGraph."""
def __init__(self, graph, simple=False):
"""Used to make dot files from network using Graphviz
"""
assert isinstance(graph, BaseGraph)
self.graph = graph
self.labeller = None
self.simple = simple
# def get_label(self, graph, node_type, ident):
# if self.labeller is not None:
# return self.labeller.get_label(node_type, ident)
#
# return graph.get_label((node_type, ident))
def get_node_attributes(self, node, use_graph=None):
if use_graph is None:
use_graph = self.graph
name = use_graph.node_to_name(node)
ntype, ident = node
if ntype == NodeType.GENE:
shape = "hexagon" if use_graph.is_structural(node) else "box"
attrs = {
"shape": shape,
"label": use_graph.get_label((ntype, ident), self.simple),
}
elif ntype == NodeType.MODULE:
attrs = {
"shape": "oval",
"label": use_graph.get_label((ntype, ident), self.simple),
}
elif ntype == NodeType.CHANNEL:
if use_graph.is_input(node):
shape = "oval"
# shape = 'invtriangle'
elif use_graph.is_output(node):
shape = "triangle"
else:
shape = "diamond"
attrs = {
"shape": shape,
"label": use_graph.get_label((ntype, ident), self.simple),
}
else:
attrs = {}
return name, attrs
def categorize_node(self, node, name, input_nodes, structural_nodes, output_nodes):
if self.graph.is_input(node):
input_nodes.append(name)
elif self.graph.is_structural(node):
structural_nodes.append(name)
elif self.graph.is_output(node):
output_nodes.append(name)
def get_dot(self, labeller=None):
self.labeller = labeller
a_graph = AGraph(directed=True)
nx_graph = self.graph.nx_graph
structural_nodes = []
output_nodes = []
input_nodes = []
# First, add nodes
for node in nx_graph.nodes():
name, attrs = self.get_node_attributes(node)
self.categorize_node(
node, name, input_nodes, structural_nodes, output_nodes
)
# Keep a reference to the original node
a_graph.add_node(name, **attrs)
# We need to add subgraphs to cluster stuff on rank
sub = a_graph.add_subgraph(input_nodes, name="input")
sub.graph_attr["rank"] = "source"
sub = a_graph.add_subgraph(structural_nodes, name="structural")
sub.graph_attr["rank"] = "same"
sub = a_graph.add_subgraph(output_nodes, name="output")
sub.graph_attr["rank"] = "sink"
# Now add edges
for u, v, edgedata in nx_graph.edges(data=True):
attrs = {}
a_graph.add_edge(
self.graph.node_to_name(u), self.graph.node_to_name(v), **attrs
)
return a_graph
def get_dot_diff(self, other):
a_graph = AGraph(directed=True)
nx_to_graph = self.graph.nx_graph
nx_from_graph = other.nx_graph
structural_nodes = []
output_nodes = []
input_nodes = []
# First, Add the nodes from the "to" Graph, marking those that are
# changed and new.
for node in nx_to_graph.nodes():
name, attrs = self.get_node_attributes(node)
if node in nx_from_graph.nodes():
if node_logic_differs(self.graph, other, node):
attrs["color"] = "blue"
else:
attrs["color"] = "green"
self.categorize_node(
node, name, input_nodes, structural_nodes, output_nodes
)
# Keep a reference to the original node
a_graph.add_node(name, **attrs)
for node in nx_from_graph.nodes():
name, attrs = self.get_node_attributes(node, use_graph=other)
if node not in nx_to_graph.nodes():
attrs["color"] = "red"
self.categorize_node(
node, name, input_nodes, structural_nodes, output_nodes
)
a_graph.add_node(name, **attrs)
# We need to add subgraphs to cluster stuff on rank
sub = a_graph.add_subgraph(input_nodes, name="input")
sub.graph_attr["rank"] = "source"
sub = a_graph.add_subgraph(structural_nodes, name="structural")
sub.graph_attr["rank"] = "same"
sub = a_graph.add_subgraph(output_nodes, name="output")
sub.graph_attr["rank"] = "sink"
# Now add edges
for u, v, edgedata in nx_to_graph.edges(data=True):
attrs = {}
if (u, v) not in nx_from_graph.edges():
attrs["color"] = "green"
a_graph.add_edge(
self.graph.node_to_name(u), self.graph.node_to_name(v), **attrs
)
for edge in nx_from_graph.edges():
if edge not in nx_to_graph.edges():
attrs = {"color": "red"}
a_graph.add_edge(
self.graph.node_to_name(edge[0]),
self.graph.node_to_name(edge[1]),
**attrs
)
return a_graph
def save_picture(self, f):
a = self.get_dot()
a.draw(f, prog="dot", args=_dot_default_args)
def save_dot(self, f):
a = self.get_dot()
a.write(f)
def save_diff_picture(self, f, other):
a = self.get_dot_diff(other)
a.draw(f, prog="dot", args=_dot_default_args)
def save_diff_dot(self, f, other):
a = self.get_dot_diff(other)
a.write(f)
class DotDiagram(Diagram):
# Map the binding types to arrows
def __init__(self, graph, height=8.0, width=5.0):
super(DotDiagram, self).__init__()
assert isinstance(graph, BaseGraph)
self.graph = graph
if hasattr(graph.analysis, "annotations"):
self.annotations = graph.analysis.annotations
else:
self.annotations = None
self.world = graph.analysis.world
self.width = width
self.height = height
# Set these below
self.xscaling = 1.0
self.yscaling = 1.0
self.connections = []
self.shapes_by_name = {}
self._generate()
def _generate(self):
"""Use dot program to initialise the diagram
"""
if hasattr(self, "get_label"):
labeller = self
else:
labeller = None
dot = DotMaker(self.graph).get_dot(labeller)
# Lay it out
dot.layout(prog="dot", args=_dot_default_args)
sx, sy = self._calc_size(dot)
self.yscaling = self.height / sy
if self.width is not None:
self.xscaling = float(self.width) / sx
else:
self.xscaling = self.yscaling
for anode in dot.nodes():
self.add_shape(anode)
for e in dot.edges():
self.add_connection(e)
def _calc_size(self, dot):
"""Calculate the size from the layout of the nodes
"""
minx = miny = maxx = maxy = None
def _update(mn, mx, cur):
if mn is None or cur < mn:
mn = cur
if mx is None or cur > mx:
mx = cur
return mn, mx
for anode in dot.nodes():
px, py = self.get_pt(anode.attr["pos"])
minx, maxx = _update(minx, maxx, px)
miny, maxy = _update(miny, maxy, py)
return maxx - minx, maxy - miny
def add_shape(self, anode):
node_id = self.graph.name_to_node(anode)
ntype, ident = node_id
px, py = self.make_pt(anode.attr["pos"])
if ntype == NodeType.GENE:
gene = self.graph.network.genes[ident]
shape = self.get_gene_shape(px, py, gene)
self.add_object(shape, zorder=1)
elif ntype == NodeType.CHANNEL:
channel_type = self.graph.get_channel_type(node_id)
shape = self.get_signal_shape(px, py, ident, channel_type)
self.add_object(shape, zorder=2)
elif ntype == NodeType.MODULE:
gi, mi = decode_module_id(ident)
mod = self.graph.network.genes[gi].modules[mi]
shape = self.get_module_shape(px, py, mod)
self.add_object(shape, zorder=2)
else:
raise RuntimeError("Node type not found")
self.shapes_by_name[anode] = shape
def add_connection(self, edge):
"""Decipher the information loaded into the edge by the dot program"""
n1, n2 = edge
# Drop the 'e,' from the description, and read in all of the
# points into an array
point_string = edge.attr["pos"][2:]
all_points = [self.make_pt(p) for p in point_string.split()]
# We begin at point 1, and then skip each 3. Basically we're just
# looking for the points describing the arc, not the control
# points, as we reconstruct these.
current_index = 1
len_points = len(all_points)
points = []
while current_index < len_points:
points.append(all_points[current_index])
current_index += 3
# We now have enough to make a nice curvy path
shape1 = self.shapes_by_name[n1]
shape2 = self.shapes_by_name[n2]
connector = self.get_connector(shape1, shape2, points)
self.add_object(connector, zorder=3)
def get_pt(self, strpair):
x, y = strpair.split(",")
return float(x), float(y)
def make_pt(self, strpair):
x, y = self.get_pt(strpair)
x *= self.xscaling
y *= self.yscaling
return x, y
def get_gene_shape(self, px, py, gene):
raise NotImplementedError
def get_signal_shape(self, px, py, channel, channel_type):
raise NotImplementedError
def get_module_shape(self, px, py, mod):
raise NotImplementedError
def get_connector(self, shape1, shape2, points):
raise NotImplementedError
def save_graph(
net,
path=".",
name=None,
simplify=True,
graph_type=GraphType.GENE_SIGNAL,
target=None,
with_dot=False,
diff=None,
simple_labels=False,
):
"""Put it all together into a simple call
"""
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
ana = NetworkAnalysis(net)
ana.annotate(target)
g = get_graph_by_type(graph_type, ana, knockouts=simplify)
d = DotMaker(g, simple=simple_labels)
if name is None:
name = str(net.identifier)
path = path / name
if diff is None:
d.save_picture(str(path.with_suffix(".png")))
if with_dot:
d.save_dot(str(path.with_suffix(".dot")))
else:
other_ana = NetworkAnalysis(diff)
other_ana.annotate(target)
gdiff = get_graph_by_type(graph_type, other_ana, knockouts=simplify)
d.save_diff_picture(str(path.with_suffix(".png")), other=gdiff)
if with_dot:
d.save_diff_dot(str(path.with_suffix(".dot")), other=gdiff)
return path
|
gpl-3.0
|
m3rlin87/darkstar
|
scripts/globals/mobskills/osmosis.lua
|
890
|
---------------------------------------------
-- Osmosis
--
-- Description: Steals an enemy's HP and one beneficial status dsp.effect. Ineffective against undead.
-- Type: Magical
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local effect = mob:stealStatusEffect(target)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,dsp.magic.ele.DARK,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS)
skill:setMsg(MobPhysicalDrainMove(mob, target, skill, MOBDRAIN_HP, dmg))
return dmg
end
|
gpl-3.0
|
shitongtong/libraryManage
|
novel-reader-last/src/main/java/org/yidu/novel/action/admin/BlockListAction.java
|
2511
|
package org.yidu.novel.action.admin;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.yidu.novel.action.base.AbstractAdminListBaseAction;
import org.yidu.novel.bean.SystemBlockSearchBean;
import org.yidu.novel.entity.TSystemBlock;
import org.yidu.novel.utils.LoginManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>
* 区块列表Action
* </p>
* Copyright(c) 2013 YiDu-Novel. All rights reserved.
*
* @version 1.1.9
* @author shinpa.you
*/
@Action(value = "blockList")
public class BlockListAction extends AbstractAdminListBaseAction {
/**
* 串行化版本统一标识符
*/
private static final long serialVersionUID = -4110412379794700028L;
/**
* 功能名称。
*/
public static final String NAME = "blockList";
/**
* URL。
*/
public static final String URL = NAMESPACE + "/" + NAME;
private int blockno;
List<TSystemBlock> blockList = new ArrayList<TSystemBlock>();
public int getBlockno() {
return this.blockno;
}
public void setBlockno(int blockno) {
this.blockno = blockno;
}
public List<TSystemBlock> getBlockList() {
return blockList;
}
@Override
protected void loadData() {
logger.debug("loadData start.");
// 初始化类型选项
initCollections(new String[] { "collectionProperties.block.type" });
SystemBlockSearchBean searchBean = new SystemBlockSearchBean();
if (StringUtils.isEmpty(pagination.getSortColumn())) {
pagination.setSortColumn("blockno");
}
searchBean.setPagination(pagination);
// 总件数设置
pagination.setPreperties(systemBlockService.getCount(searchBean));
blockList = systemBlockService.find(searchBean);
// Setting number of records in the particular page
pagination.setPageRecords(blockList.size());
logger.debug("loadData normally end.");
}
public String delete() throws Exception {
logger.debug("del start.");
TSystemBlock systemBlock = systemBlockService.getByNo(blockno);
systemBlock.setDeleteflag(true);
systemBlock.setModifyuserno(LoginManager.getLoginUser().getUserno());
systemBlock.setModifytime(new Date());
systemBlockService.save(systemBlock);
loadData();
logger.debug("del normally end.");
return SUCCESS;
}
}
|
gpl-3.0
|
AlexAegis/elte-progtech-1
|
submission2/src/main/java/com/github/alexaegis/elements/PlayButton.java
|
1436
|
package com.github.alexaegis.elements;
import com.github.alexaegis.logic.FieldSizeOptions;
import com.github.alexaegis.logic.GameModes;
import com.github.alexaegis.panels.GamePanel;
import javax.swing.*;
import java.awt.*;
import static com.github.alexaegis.Main.*;
import static com.github.alexaegis.Main.WINDOW_HEIGHT;
import static com.github.alexaegis.Main.WINDOW_WIDTH;
public class PlayButton extends GameButton {
public PlayButton() {
name = "Play";
setName(name);
setText(name);
addActionListener(actionEvent -> {
JPanel gp = (JPanel) getParent().getParent();
JComboBox comboBox = (JComboBox) getParent().getComponent(2);
FieldSizeOptions fieldSizeOption = (FieldSizeOptions) comboBox.getSelectedItem();
/*NumberSelector n1 = (NumberSelector) getParent().getComponent(4);
NumberSelector n2 = (NumberSelector) getParent().getComponent(6);
fieldSizeOption.setCustomSize(Math.max(n1.getValue(), n2.getValue()), Math.max(n1.getValue(), n2.getValue()));*/
TILE_SIZE = GRID_SIZE_DEFAULT / Math.max(fieldSizeOption.getWidth(), fieldSizeOption.getHeight());
gp.removeAll();
gp.add(new GamePanel(fieldSizeOption, ((GameModes) ((GameModeSelector) getParent().getComponent(1)).getSelectedItem()).getGameLogic()));
gp.revalidate();
gp.repaint();
});
}
}
|
gpl-3.0
|
carlgreen/Lexicon-MPX-G2-Editor
|
mpxg2-model/src/main/java/info/carlwithak/mpxg2/model/PostMix.java
|
1978
|
/*
* Copyright (C) 2012 Carl Green
*
* 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 info.carlwithak.mpxg2.model;
import info.carlwithak.mpxg2.model.parameters.GenericValue;
import info.carlwithak.mpxg2.model.parameters.Parameter;
/**
*
* @author Carl Green
*/
public class PostMix implements DataObject {
private final GenericValue<Integer> postMix = new GenericValue<>("Mix", "%", 0, 100);
private final GenericValue<Integer> postLevel = new GenericValue<>("Level", "dB", -90, 6);
private final GenericValue<Integer> postBypassLevel = new GenericValue<>("Bypass Level", "dB", -90, 6);
@Override
public Parameter getParameter(final int parameterIndex) {
Parameter parameter;
switch (parameterIndex) {
case 0:
parameter = postMix;
break;
case 1:
parameter = postLevel;
break;
case 2:
parameter = postBypassLevel;
break;
default:
parameter = null;
}
return parameter;
}
public GenericValue<Integer> getPostMix() {
return postMix;
}
public GenericValue<Integer> getPostLevel() {
return postLevel;
}
public GenericValue<Integer> getPostBypassLevel() {
return postBypassLevel;
}
}
|
gpl-3.0
|
bipulr/moodle
|
lib/classes/event/role_deleted.php
|
2392
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core\event;
defined('MOODLE_INTERNAL') || die();
/**
* Role assigned event.
*
* @property-read array $other {
* Extra information about event.
*
* @type string shortname shortname of role.
* @type string description role description.
* @type string archetype role type.
* }
*
* @package core
* @since Moodle 2.6
* @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class role_deleted extends base {
/**
* Initialise event parameters.
*/
protected function init() {
$this->data['objecttable'] = 'role';
$this->data['crud'] = 'd';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Returns localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('eventroledeleted', 'role');
}
/**
* Returns non-localised event description with id's for admin use only.
*
* @return string
*/
public function get_description() {
return 'Role ' . $this->objectid . ' is deleted by user ' . $this->userid;
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/admin/roles/manage.php');
}
/**
* Returns array of parameters to be passed to legacy add_to_log() function.
*
* @return array
*/
protected function get_legacy_logdata() {
return array(SITEID, 'role', 'delete', 'admin/roles/manage.php?action=delete&roleid=' . $this->objectid,
$this->other['shortname'], '');
}
}
|
gpl-3.0
|
xtwxy/dcim
|
modbus/src/main/java/com/wincom/protocol/modbus/AbstractModbusRequest.java
|
770
|
package com.wincom.protocol.modbus;
import com.wincom.dcim.agentd.HandlerContext;
import com.wincom.dcim.agentd.messages.AbstractWireable;
import com.wincom.dcim.agentd.messages.Handler;
/**
*
* @author master
*/
public abstract class AbstractModbusRequest extends AbstractWireable {
AbstractModbusRequest(HandlerContext sender) {
super(sender);
}
@Override
public void apply(HandlerContext ctx, Handler handler) {
if(handler instanceof ModbusPayloadOutboundHandler) {
applyModbusRequest(ctx, (ModbusPayloadOutboundHandler) handler);
} else {
handler.handle(ctx, this);
}
}
abstract protected void applyModbusRequest(HandlerContext ctx, ModbusPayloadOutboundHandler handler);
}
|
gpl-3.0
|
NobleKiss/ContainerSystem
|
ContainerSystem/ContainerWeb/App_Start/BundleConfig.cs
|
1821
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Optimization;
namespace ContainerWeb
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-{version}.js",
"~/Scripts/knockout.validation.js"));
bundles.Add(new ScriptBundle("~/bundles/app").Include(
"~/Scripts/sammy-{version}.js",
"~/Scripts/app/common.js",
"~/Scripts/app/app.datamodel.js",
"~/Scripts/app/app.viewmodel.js",
"~/Scripts/app/home.viewmodel.js",
"~/Scripts/app/_run.js"));
// 使用要用于开发和学习的 Modernizr 的开发版本。然后,当你做好
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
}
}
|
gpl-3.0
|
glamprou/bookings
|
lib/Database/DatabaseFactory.php
|
1212
|
<?php
require_once(ROOT_DIR . 'lib/Config/namespace.php');
class DatabaseFactory
{
private static $_instance = null;
public static function GetDatabase()
{
if (is_null(self::$_instance))
{
$databaseType = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_TYPE);
$dbUser = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_USER);
$dbPassword = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_PASSWORD);
$hostSpec = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_HOSTSPEC);
$dbName = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_NAME);
if (strtolower($databaseType) == 'mysql')
{
require_once(ROOT_DIR . 'lib/Database/MySQL/namespace.php');
self::$_instance = new Database(new MySqlConnection($dbUser, $dbPassword, $hostSpec, $dbName));
}
else
{
require_once(ROOT_DIR . 'lib/Database/MDB2/namespace.php');
self::$_instance = new Database(new Mdb2Connection($databaseType, $dbUser, $dbPassword, $hostSpec, $dbName));
}
}
return self::$_instance;
}
}
?>
|
gpl-3.0
|
MendelMonteiro/TailBlazer
|
Source/TailBlazer/App.xaml.cs
|
326
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace TailBlazer
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
|
gpl-3.0
|
SPACEDAC7/TrabajoFinalGrado
|
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/google/android/exoplayer/upstream/DataSource.java
|
473
|
/*
* Decompiled with CFR 0_115.
*
* Could not load the following classes:
* com.google.android.exoplayer.upstream.DataSpec
*/
package com.google.android.exoplayer.upstream;
import com.google.android.exoplayer.upstream.DataSpec;
import java.io.IOException;
public interface DataSource {
public void close() throws IOException;
public long open(DataSpec var1) throws IOException;
public int read(byte[] var1, int var2, int var3) throws IOException;
}
|
gpl-3.0
|
Construo/construo
|
src/root_graphic_context.hpp
|
1746
|
// Construo - A wire-frame construction game
// Copyright (C) 2002 Ingo Ruhnke <grumbel@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef HEADER_ROOT_GRAPHIC_CONTEXT_HPP
#define HEADER_ROOT_GRAPHIC_CONTEXT_HPP
#include <stack>
#include "graphic_context.hpp"
#include "cursor_type.hpp"
/** RootGraphicContext represetens the window in which Construo runs,
* it provides ways to set the title the cursor, etc. in addition to
* the stuff that a normal GraphicContext provides.
*/
class RootGraphicContext : public GraphicContext
{
private:
std::stack<CursorType> cursor_stack;
CursorType current_cursor;
public:
RootGraphicContext() {}
virtual ~RootGraphicContext() {}
void set_cursor(CursorType);
void push_cursor();
void pop_cursor();
protected:
virtual void set_cursor_real(CursorType) =0;
public:
/** Enter fullscreen mode */
virtual void enter_fullscreen() =0;
/** Leave fullscreen and return to windowed mode */
virtual void leave_fullscreen() =0;
private:
RootGraphicContext (const RootGraphicContext&);
RootGraphicContext& operator= (const RootGraphicContext&);
};
#endif
/* EOF */
|
gpl-3.0
|
PanzerKunst/hoffice
|
website/wp-content/themes/hoffice/js/hoffice/services/browser.js
|
2290
|
CBR.Services.Browser = {
ScrollbarWidth: (function () {
var _scrollbarWidth = null;
function _getScrollarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
return {
get: function () {
if (_scrollbarWidth === null) {
_scrollbarWidth = _getScrollarWidth();
}
return _scrollbarWidth;
}
}
})(),
OS: (function () {
return {
isIOS: function () {
return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
}
}
})(),
Breakpoints: (function () {
return {
isMediumScreen: function() {
var content = window.getComputedStyle(
document.querySelector("html"), ":after"
).getPropertyValue("content");
// In some browsers like Firefox, "content" is wrapped by double-quotes, that's why doing "return content === "GLOBAL_MEDIUM_SCREEN_BREAKPOINT" would be false.
return _.contains(content, "GLOBAL_MEDIUM_SCREEN_BREAKPOINT");
},
isLargeScreen: function() {
var content = window.getComputedStyle(
document.querySelector("html"), ":after"
).getPropertyValue("content");
return _.contains(content, "GLOBAL_LARGE_SCREEN_BREAKPOINT");
},
isSmallScreen: function () {
return !this.isMediumScreen() && !this.isLargeScreen();
}
}
})()
};
|
gpl-3.0
|
dymkowsk/mantid
|
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py
|
8168
|
#pylint: disable=no-init,invalid-name
from __future__ import (absolute_import, division, print_function)
from mantid.api import *
from mantid.kernel import *
from mantid.simpleapi import *
import os
import math
import sys
#pylint: disable=too-few-public-methods
class REFLOptions(object):
def __init__(self):
from reduction_gui.reduction.reflectometer.refl_data_script import DataSets as REFLDataSets
from reduction_gui.reduction.reflectometer.refl_data_series import DataSeries
self._state = DataSeries(data_class=REFLDataSets)
def get_state(self):
return self._state
class REFLReprocess(PythonAlgorithm):
"""
Normalise detector counts by accelerator current and beam spectrum.
"""
def category(self):
return "Workflow\\REFL"
def name(self):
return "REFLReprocess"
def summary(self):
return "Re-reduce REFL data for an entire experiment using saved parameters"
def PyInit(self):
self.declareProperty("IPTS", '0', "IPTS number to process")
self.declareProperty(FileProperty(name="OutputDirectory",defaultValue="",action=FileAction.OptionalDirectory))
self.declareProperty("LoadProcessed", False, "If True, data will be loaded instead of being processed")
self.declareProperty("Filter", "ts.txt", "String that the reduced data file name must contain")
def PyExec(self):
from reduction_gui.reduction.reflectometer.refl_reduction import REFLReductionScripter
ipts = self.getProperty("IPTS").value
try:
ipts_number = int(ipts)
ipts = "IPTS-%s" % ipts_number
except:
pass
Logger("REFLReprocess").notice("Processing %s" % ipts)
# Locate the IPTS directory
ipts_dir = "/SNS/REF_L/%s/shared" % ipts
if not os.path.isdir(ipts_dir):
ipts_dir = ipts
# Determine the output directory
output_dir = self.getProperty("OutputDirectory").value
if len(output_dir)==0:
output_dir = ipts_dir
load_only = self.getProperty("LoadProcessed").value
if load_only:
return self.load_processed(output_dir)
# Reprocess the data
if os.path.isdir(ipts_dir):
for item in os.listdir(ipts_dir):
if item.endswith('.xml'):
try:
Logger("REFLReprocess").notice("Processing %s" % os.path.join(ipts_dir, item))
refl = REFLReductionScripter()
options = REFLOptions()
refl.attach(options)
refl.from_xml(os.path.join(ipts_dir, item))
code = refl.to_script()
exec(code, globals(), locals())
self.stitch_data(os.path.join(ipts_dir, item), output_dir,
q_min=options.get_state().data_sets[0].q_min,
q_step=options.get_state().data_sets[0].q_step)
except:
Logger("REFLReprocess").error(str(sys.exc_info()[1]))
else:
Logger("REFLReprocess").error("%s not a valid directory" % ipts_dir)
def load_processed(self, output_dir):
filter_string = self.getProperty("Filter").value
if not os.path.isdir(output_dir):
Logger("REFLReprocess").error("%s not a valid directory" % output_dir)
return
for item in os.listdir(output_dir):
if item.endswith('.txt') and \
(len(filter_string)==0 or item.find(filter_string)>=0):
basename, _ = os.path.splitext(item)
Load(Filename=os.path.join(output_dir, item), OutputWorkspace=basename)
(_name,_ts) = basename.split('_#')
CloneWorkspace(InputWorkspace=basename, OutputWorkspace=_name)
def stitch_data(self, input_file, output_dir, q_min, q_step):
from LargeScaleStructures.data_stitching import DataSet, Stitcher#, RangeSelector
# Identify the data sets to stitch and order them
workspace_list = []
_list_name = []
_list_ts = []
ws_list = AnalysisDataService.getObjectNames()
for item in ws_list:
if item.endswith('ts'):
(_name,_ts) = item.split('_#')
_list_name.append(item)
_list_ts.append(_ts)
_name_ts = sorted(zip(_list_ts, _list_name))
_ts_sorted, workspace_list = list(zip(*_name_ts))
# Stitch the data
s = Stitcher()
q_max = 0
for item in workspace_list:
data = DataSet(item)
data.load(True, True)
dummy_x_min, x_max = data.get_range()
if x_max > q_max:
q_max = x_max
s.append(data)
s.set_reference(0)
s.compute()
# Apply the scaling factors
for data in s._data_sets:
Scale(InputWorkspace=str(data), OutputWorkspace=data._ws_scaled,
Operation="Multiply", Factor=data.get_scale())
SaveAscii(InputWorkspace=str(data), Filename=os.path.join(output_dir, '%s.txt' % str(data)))
output_file = input_file.replace('.xml', '_reprocessed.txt')
Logger("REFLReprocess").notice("Saving to %s" % output_file)
output_ws = _average_y_of_same_x_(q_min, q_step, q_max)
SaveAscii(InputWorkspace=output_ws, Filename=output_file)
def weightedMean(data_array, error_array):
"""
Code taken out as-is from base_ref_reduction.py
"""
sz = len(data_array)
# calculate the numerator of mean
dataNum = 0
for i in range(sz):
if not data_array[i] == 0:
tmpFactor = float(data_array[i]) / float((pow(error_array[i],2)))
dataNum += tmpFactor
# calculate denominator
dataDen = 0
for i in range(sz):
if not error_array[i] == 0:
tmpFactor = 1./float((pow(error_array[i],2)))
dataDen += tmpFactor
if dataDen == 0:
mean = 0
mean_error = 0
else:
mean = float(dataNum) / float(dataDen)
mean_error = math.sqrt(1/dataDen)
return [mean, mean_error]
def _average_y_of_same_x_(q_min, q_step, q_max=2):
"""
Code taken out as-is from base_ref_reduction.py
2 y values sharing the same x-axis will be average using
the weighted mean
"""
ws_list = AnalysisDataService.getObjectNames()
scaled_ws_list = []
# Get the list of scaled histos
for ws in ws_list:
if ws.endswith("_scaled"):
scaled_ws_list.append(ws)
# get binning parameters
#_from_q = str(state.data_sets[0].q_min)
#_bin_size = str(state.data_sets[0].q_step)
#_bin_max = str(2)
#binning_parameters = _from_q + ',-' + _bin_size + ',' + _bin_max
binning_parameters = "%s,-%s,%s" % (q_min, q_step, q_max)
# Convert each histo to histograms and rebin to final binning
for ws in scaled_ws_list:
new_name = "%s_histo" % ws
ConvertToHistogram(InputWorkspace=ws, OutputWorkspace=new_name)
Rebin(InputWorkspace=new_name, Params=binning_parameters,
OutputWorkspace=new_name)
# Take the first rebinned histo as our output
data_y = mtd[scaled_ws_list[0]+'_histo'].dataY(0)
data_e = mtd[scaled_ws_list[0]+'_histo'].dataE(0)
# Add in the other histos, averaging the overlaps
for i in range(1, len(scaled_ws_list)):
data_y_i = mtd[scaled_ws_list[i]+'_histo'].dataY(0)
data_e_i = mtd[scaled_ws_list[i]+'_histo'].dataE(0)
for j in range(len(data_y_i)):
if data_y[j]>0 and data_y_i[j]>0:
[data_y[j], data_e[j]] = weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]])
elif (data_y[j] == 0) and (data_y_i[j]>0):
data_y[j] = data_y_i[j]
data_e[j] = data_e_i[j]
return scaled_ws_list[0]+'_histo'
#############################################################################################
AlgorithmFactory.subscribe(REFLReprocess)
|
gpl-3.0
|
PHPBoost/PHPBoost
|
kernel/framework/builder/form/field/FormFieldRichTextEditor.class.php
|
5215
|
<?php
/**
* This class represents a rich text editor.
* @package Builder
* @subpackage Form\field
* @copyright © 2005-2022 PHPBoost
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL-3.0
* @author Benoit SAUTEL <ben.popeye@phpboost.com>
* @version PHPBoost 6.0 - last update: 2021 11 27
* @since PHPBoost 3.0 - 2010 01 09
* @contributor Arnaud GENET <elenwii@phpboost.com>
* @contributor mipel <mipel@phpboost.com>
* @contributor Sebastien LARTIGUE <babsolune@phpboost.com>
*/
class FormFieldRichTextEditor extends FormFieldMultiLineTextEditor
{
/**
* @var ContentFormattingFactory
*/
private $formatter = null;
private $reset_value = null;
/**
* Constructs a rich text edit field.
* In addition to the parameters of the FormMultiLineEdit ones, there is the formatter which
* is an instance of the ContentFormattingFactory which ensures the formatting. The default value
* corresponds to the user's default configuration and will be the one to use 99% of the time.
* @param string $id Field id
* @param string $label Field label
* @param string $value Default value
* @param string[] $field_options options
* @param FormFieldConstraint[] $constraints The constraints
*/
public function __construct($id, $label, $value, array $field_options = array(), array $constraints = array())
{
$this->formatter = AppContext::get_content_formatting_service()->get_default_factory();
parent::__construct($id, $label, '', $field_options, $constraints);
$this->set_value($value);
}
/**
* @return string The html code for the textarea.
*/
public function display()
{
$template = parent::display();
$this->assign_editor($template);
return $template;
}
private function assign_editor(Template $template)
{
$editor = $this->formatter->get_editor();
$editor->set_identifier($this->get_html_id());
$template->put_all(array(
'C_EDITOR_ENABLED' => true,
'C_RESET_BUTTON_ENABLED' => $this->reset_value !== null,
'EDITOR' => $editor->display(),
'EDITOR_NAME' => TextHelper::strtolower($this->formatter->get_name()),
'VALUE' => $this->get_raw_value(),
'PREVIEW_BUTTON' => $this->get_preview_button_code(),
'RESET_BUTTON' => $this->get_reset_button_code()
));
}
private function get_preview_button_code()
{
$template = new FileTemplate('framework/builder/form/button/FormButtonPreview.tpl');
$template->put('HTML_ID', $this->get_html_id());
return $template->render();
}
private function get_reset_button_code()
{
$template = new FileTemplate('framework/builder/form/button/FormButtonReset.tpl');
$template->put_all(array(
'C_ONCLICK_FUNCTION' => true,
'HTML_ID' => $this->get_html_id(),
'CLASS' => 'small',
'L_RESET' => LangLoader::get_message('form.reset', 'form-lang'),
'ONCLICK_ACTIONS' => (AppContext::get_current_user()->get_editor() == 'TinyMCE' ? 'setTinyMceContent(' . TextHelper::to_js_string($this->unparse_value($this->reset_value)) . ');' :
'HTMLForms.getField("' . $this->get_id() . '").setValue(' . TextHelper::to_js_string($this->unparse_value($this->reset_value)) . ');')
));
return $template->render();
}
/**
* {@inheritdoc}
*/
public function get_value()
{
return $this->parse_value($this->get_raw_value());
}
private function parse_value($value)
{
$parser = $this->formatter->get_parser();
$parser->set_content($value);
$parser->parse();
return $parser->get_content();
}
private function get_raw_value()
{
return parent::get_value();
}
/**
* {@inheritdoc}
*/
public function set_value($value)
{
$this->set_raw_value($this->unparse_value($value));
}
private function set_raw_value($value)
{
parent::set_value($value);
}
private function unparse_value($value)
{
$unparser = $this->formatter->get_unparser();
$unparser->set_content($value);
$unparser->parse();
return $unparser->get_content();
}
public function get_onblur_validations()
{
return parent::get_onblur_validations();
}
/**
* {@inheritdoc}
*/
public function retrieve_value()
{
$request = AppContext::get_request();
if ($request->has_parameter($this->get_html_id()))
{
$this->set_raw_value($request->get_string($this->get_html_id()));
}
}
protected function compute_options(array &$field_options)
{
foreach($field_options as $attribute => $value)
{
$attribute = TextHelper::strtolower($attribute);
switch ($attribute)
{
case 'formatter':
if ($value instanceof ContentFormattingExtensionPoint)
{
$this->formatter = $value;
unset($field_options['formatter']);
}
else
{
throw new FormBuilderException('The value associated to the formatter attribute must be an instance of the ContentFormattingFactory class');
}
break;
case 'reset_value':
$this->reset_value = $value;
unset($field_options['reset_value']);
break;
}
}
parent::compute_options($field_options);
}
}
?>
|
gpl-3.0
|
FlightControl-Master/MOOSE_MISSIONS
|
AID - AI Dispatching/AID-A2A - AI A2A Dispatching/AID-A2A-050 - Resources/AID-A2A-050 - Resources.lua
|
2607
|
---
-- Name: AID-A2A-050 - Resources
-- Author: FlightControl
-- Date Created: 21 Sep 2017
-- Define a SET_GROUP object that builds a collection of groups that define the EWR network.
-- Here we build the network with all the groups that have a name starting with DF CCCP AWACS and DF CCCP EWR.
DetectionSetGroup = SET_GROUP:New()
DetectionSetGroup:FilterPrefixes( { "DF CCCP AWACS", "DF CCCP EWR" } )
DetectionSetGroup:FilterStart()
Detection = DETECTION_AREAS:New( DetectionSetGroup, 30000 )
-- Setup the A2A dispatcher, and initialize it.
A2ADispatcher = AI_A2A_DISPATCHER:New( Detection )
-- Enable the tactical display panel.
A2ADispatcher:SetTacticalDisplay( true )
-- Initialize the dispatcher, setting up a border zone. This is a polygon,
-- which takes the waypoints of a late activated group with the name CCCP Border as the boundaries of the border area.
-- Any enemy crossing this border will be engaged.
CCCPBorderZone = ZONE_POLYGON:New( "CCCP Border", GROUP:FindByName( "CCCP Border" ) )
A2ADispatcher:SetBorderZone( CCCPBorderZone )
-- Initialize the dispatcher, setting up a radius of 100km where any airborne friendly
-- without an assignment within 100km radius from a detected target, will engage that target.
A2ADispatcher:SetEngageRadius( 250000 )
-- Setup the squadrons.
A2ADispatcher:SetSquadron( "Mineralnye", AIRBASE.Caucasus.Mineralnye_Vody, { "SQ CCCP SU-27" }, 6 )
-- Setup the overhead
A2ADispatcher:SetSquadronOverhead( "Mineralnye", 1.2 )
-- Setup the Grouping
A2ADispatcher:SetSquadronGrouping( "Mineralnye", 1 )
-- Setup the Takeoff methods
A2ADispatcher:SetSquadronTakeoff( "Mineralnye", AI_A2A_DISPATCHER.Takeoff.Hot )
-- Setup the Landing methods
A2ADispatcher:SetSquadronLandingAtEngineShutdown( "Mineralnye" )
-- Setup the visibility before start.
A2ADispatcher:SetSquadronVisible( "Mineralnye" )
-- CAP Squadron execution.
CAPZoneEast = ZONE_POLYGON:New( "CAP Zone East", GROUP:FindByName( "CAP Zone East" ) )
A2ADispatcher:SetSquadronCap( "Mineralnye", CAPZoneEast, 4000, 10000, 500, 600, 800, 900 )
A2ADispatcher:SetSquadronCapInterval( "Mineralnye", 1, 30, 60, 1 )
A2ADispatcher:SetSquadronFuelThreshold( "Mineralnye", 0.20 )
-- GCI Squadron execution.
--A2ADispatcher:SetSquadronGci( "Mineralnye", 900, 1200 )
-- Blue attack simulation
local Frequency = 60
--BlueSpawn1 = SPAWN
-- :New( "RT NATO 1" )
-- :InitLimit( 2, 10 )
-- :InitRandomizeTemplate( { "SQ NATO A-10C", "SQ NATO F-15C", "SQ NATO F-16A", "SQ NATO F/A-18", "SQ NATO F-16C" } )
-- :InitRandomizeRoute( 0, 0, 30000 )
-- --:InitDelayOn()
-- :SpawnScheduled( Frequency, 0.4 )
|
gpl-3.0
|
mcisse3007/moodle_esco_master
|
mod/nln/version.php
|
1282
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* NLN module version information
*
* @package mod
* @subpackage nln
* @copyright 2009 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2014061201; // The current module version (Date: YYYYMMDDXX)
$plugin->requires = 2014051200; // Requires this Moodle version
$plugin->component = 'mod_nln'; // Full name of the plugin (used for diagnostics)
$plugin->cron = 0;
$plugin->release = '2.7.0';
$plugin->maturity = MATURITY_STABLE;
|
gpl-3.0
|
DidiMilikina/SoftUni
|
Programming Basics - C#/Exams/Programming Basics Exam - 19 March 2017 - Morning/Problem 02 - Cups/Properties/AssemblyInfo.cs
|
1410
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem 02 - Cups")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem 02 - Cups")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5eef4999-72f2-4e33-9d45-ea4f62468787")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-3.0
|
asolitarywolf/LetsMod
|
src/main/java/com/modernbushcraft/letsmod/proxy/ClientProxy.java
|
98
|
package com.modernbushcraft.letsmod.proxy;
public class ClientProxy extends CommonProxy
{
}
|
gpl-3.0
|
payeboland/python-telegram-bot-openshift
|
maker.py
|
2905
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import arabic_reshaper
from random import randint
from bidi.algorithm import get_display
def maker1_f(name,phone,desc,email,website):
img = Image.open("f1.png")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("titr.ttf", 16, encoding='unic')
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text_alignment = 'right';
draw.text_antialias = True
draw.text_encoding = 'utf-8'
font = ImageFont.truetype("titr.ttf", 60, encoding='unic')
#phone = phone.decode('utf-8')
disp=arabic_reshaper.reshape(phone)
disp = get_display(disp)
draw.text((img.width / 3 -15*len(desc) +20 , img.height/2 + 400),disp,(255,255,255),font=font)
font = ImageFont.truetype("Georgia.ttf", 46, encoding='unic')
draw.text((img.width / 3 -10*len(email) + 700 , img.height/2 + 420),email,(255,255,255),font=font)
font = ImageFont.truetype("titr.ttf", 110, encoding='unic')
name=' '+name
#name = name.decode('utf-8')
namedisp=arabic_reshaper.reshape(name)
namedisp = get_display(namedisp)
w, h = draw.textsize(namedisp,font)
draw.text(( (img.width -w)/2 , img.height/2 - 66 ),namedisp,(255,255,255),font=font)
font = ImageFont.truetype("Yekan.ttf", 73 , encoding='unic')
desc=' '+desc
#desc = desc.decode('utf-8')
descdisp=arabic_reshaper.reshape(desc)
descdisp = get_display(descdisp)
w, h = draw.textsize(descdisp,font)
draw.text(( (img.width -w)/2 , img.height/2 +200),descdisp,(255,255,255),font=font)
photoadd=str(randint(111,9876543210))+".png"
img.save(photoadd)
return photoadd
def maker1_b(back,backsub):
img = Image.open("b1.png")
draw = ImageDraw.Draw(img)
W,H = img.size
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("titr.ttf", 16, encoding='unic')
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text_alignment = 'right';
draw.text_antialias = True
draw.text_encoding = 'utf-8'
font = ImageFont.truetype("Georgia.ttf", 205, encoding='unic')
back=' '+back
#back = back.decode('utf-8')
#namedisp=arabic_reshaper.reshape(back)
#namedisp = get_display(namedisp)
w, h = draw.textsize(back,font)
draw.text( ( (W-w)/2,(H-h)/2 - 250 ) ,back,(255,255,255),font=font)
font = ImageFont.truetype("Georgia.ttf", 88, encoding='unic')
backsub=' '+backsub
#backsub = backsub.decode('utf-8')
#descdisp=arabic_reshaper.reshape(backsub)
#descdisp = get_display(descdisp)
w, h = draw.textsize(backsub,font)
draw.text(( (W-w)/2 , img.height/2),backsub,(255,255,255),font=font)
photoadd=str(randint(111,9876543210))+".png"
img.save(photoadd)
return photoadd
|
gpl-3.0
|
cyberchimps/responsive
|
tests/tests/_support/Helper/Customizer.php
|
185
|
<?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Customizer extends \Codeception\Module
{
}
|
gpl-3.0
|
241180/Oryx
|
oryx-crypt/src/com/oryx/interfaces/VerifyingStream.java
|
1818
|
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.oryx.interfaces;
import com.oryx.exceptions.KeyczarException;
import java.nio.ByteBuffer;
/**
* Verifying Streams are able to verify data that has been signed by
* {@link SigningStream} objects.
*
* @author steveweis@gmail.com (Steve Weis)
*/
public interface VerifyingStream extends Stream {
/**
* @return The size of digests that this stream will verify.
*/
int digestSize();
/**
* Initialize this stream for verification. This must be called before
* updateVerify().
*
* @throws KeyczarException If a Java JCE error occurs.
*/
void initVerify() throws KeyczarException;
/**
* Update the data which has been signed.
*
* @param input Data which has been signed.
* @throws KeyczarException If a Java JCE error occurs.
*/
void updateVerify(ByteBuffer input) throws KeyczarException;
/**
* Verify that the given signautre is a valid signautre on the updated data.
*
* @param signature The signature to verify
* @return Whether the given signature is valid.
* @throws KeyczarException If a Java JCE error occurs.
*/
boolean verify(ByteBuffer signature) throws KeyczarException;
}
|
gpl-3.0
|
mguetlein/CheS-Map
|
src/alg/align3d/MaxFragAligner.java
|
2832
|
package alg.align3d;
import java.util.List;
import main.Settings;
import main.TaskProvider;
import data.ClusterDataImpl;
import data.DatasetFile;
import data.fragments.MatchEngine;
import dataInterface.ClusterData;
import dataInterface.CompoundData;
import dataInterface.CompoundProperty;
import dataInterface.FragmentProperty;
import dataInterface.NominalProperty;
import dataInterface.SmartsUtil;
import dataInterface.SubstructureSmartsType;
public class MaxFragAligner extends Abstract3DAligner
{
public static final MaxFragAligner INSTANCE = new MaxFragAligner();
private MaxFragAligner()
{
}
@Override
public String getName()
{
return getNameStatic();
}
public static String getNameStatic()
{
return Settings.text("align.max-frag");
}
@Override
public String getDescription()
{
return Settings.text("align.max-frag.desc", Settings.OPENBABEL_STRING, Settings.CDK_STRING);
}
@Override
public void algin(DatasetFile dataset, List<ClusterData> clusters, List<CompoundProperty> features)
{
for (ClusterData clusterData : clusters)
{
FragmentProperty maxFrag = null;
int maxFragLength = -1;
MatchEngine maxMatchEngine = null;
for (CompoundProperty feat : features)
{
if (!(feat instanceof FragmentProperty))
continue;
boolean matchesAll = true;
for (CompoundData c : clusterData.getCompounds())
if (c.getStringValue((NominalProperty) feat).equals("0"))
{
matchesAll = false;
break;
}
if (!matchesAll)
continue;
int featLength = SmartsUtil.getLength(((FragmentProperty) feat).getSmarts());
if (featLength >= MIN_NUM_ATOMS && (maxFrag == null || maxFragLength < featLength))
{
maxFrag = (FragmentProperty) feat;
maxFragLength = featLength;
maxMatchEngine = maxFrag.getSmartsMatchEngine();
}
}
if (maxFrag != null)
{
((ClusterDataImpl) clusterData).setSubstructureSmarts(SubstructureSmartsType.MAX_FRAG,
maxFrag.getSmarts());
((ClusterDataImpl) clusterData).setSubstructureSmartsMatchEngine(SubstructureSmartsType.MAX_FRAG,
maxMatchEngine);
}
}
alignToSmarts(dataset, clusters);
}
@Override
public SubstructureSmartsType getSubstructureSmartsType()
{
return SubstructureSmartsType.MAX_FRAG;
}
@Override
public boolean requiresStructuralFragments()
{
return true;
}
@Override
public void giveNoSmartsWarning(int clusterIndex)
{
TaskProvider.warning("Could not align cluster " + (clusterIndex + 1) + ", no common fragment found.", getName()
+ " could not align the cluster, as there is no structural fragment (of size >=" + MIN_NUM_ATOMS
+ ") that matches all compounds of the cluster. "
+ "The reason maybe that the cluster is too structurally diverse. "
+ "You could try to increase the number of structural fragments.");
}
}
|
gpl-3.0
|
ramsodev/DitaManagement
|
dita/dita.reference/src/net/ramso/dita/reference/Coderef.java
|
1794
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.02 at 08:10:17 PM CEST
//
package net.ramso.dita.reference;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{}coderef.class">
* <attribute ref="{}class default="+ topic/xref pr-d/coderef ""/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "coderef")
public class Coderef
extends CoderefClass
{
@XmlAttribute(name = "class")
protected String clazz;
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
if (clazz == null) {
return "+ topic/xref pr-d/coderef ";
} else {
return clazz;
}
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
}
|
gpl-3.0
|
chenglongcl/blog
|
Application/Common/Conf/webconfig.php
|
854
|
<?php
return array(
//'配置项'=>'配置值'
/*
* 网站设置
*/
'UPLOADIMG_PATH' => './Uploads/img/',//默认图片上传目录
'IMAGE_TITLE_ALT_WORD' => 'MYBLOG',
//邮箱设置
'EMAIL_SMTP' => 'smtp.163.com', // SMTP服务器
'EMAIL_USERNAME' => 'qinsmoon910106@163.com', // 邮箱用户名
'EMAIL_PASSWORD' => 'cheng83661031', // 邮箱密码
'EMAIL_FROM_NAME' => 'MYBLOG', // 发件名
//评论管理
'COMMENT_REVIEW' => '1', // 是否开启评论1:开启 0:关闭
'COMMENT_SEND_EMAIL' => '0', // 被评论后送邮件1:开启 0:关闭
'EMAIL_RECEIVE' => '298115800@qq.com', // 接收评论通知邮箱
'ADMINISTRATOR' =>array('41'),
);
|
gpl-3.0
|
takisd123/executequery
|
src/org/executequery/gui/erd/ErdLineStyleDialog.java
|
14871
|
/*
* ErdLineStyleDialog.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.erd;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import org.executequery.GUIUtilities;
import org.executequery.components.ColourChooserButton;
import org.executequery.gui.DefaultPanelButton;
import org.executequery.gui.WidgetFactory;
import org.executequery.localization.Bundles;
import org.underworldlabs.swing.AbstractBaseDialog;
import org.underworldlabs.swing.plaf.UIUtils;
/**
*
* @author Takis Diakoumis
*/
public class ErdLineStyleDialog extends AbstractBaseDialog {
/** The line weight combo box */
private JComboBox weightCombo;
/** The line style combo box */
private JComboBox styleCombo;
/** The arrow style combo box */
private JComboBox arrowCombo;
/** The colour selection button */
private ColourChooserButton colourButton;
/** The dependency panel where changes will occur */
private ErdDependanciesPanel dependsPanel;
/** <p>Creates a new instance with the specified values
* pre-selected within respective combo boxes.
*
* @param the <code>ErdDependanciesPanel</code> where
* changes will occur
* @param the line weight
* @param the line style index to be selected:<br>
* 0 - solid line
* 1 - dotted line
* 2 - dashed line
* @param the arrow index to be selected:<br>
* 0 - filled arrow
* 1 - outline arrow
* @param the line colour
*/
public ErdLineStyleDialog(ErdDependanciesPanel dependsPanel) {
super(GUIUtilities.getParentFrame(), "Line Style", true);
this.dependsPanel = dependsPanel;
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
determineWeightComboSelection(dependsPanel);
styleCombo.setSelectedIndex(dependsPanel.getLineStyleIndex());
arrowCombo.setSelectedIndex(dependsPanel.getArrowStyleIndex());
pack();
this.setLocation(GUIUtilities.getLocationForDialog(this.getSize()));
setVisible(true);
}
private void determineWeightComboSelection(ErdDependanciesPanel dependsPanel) {
float lineWeight = dependsPanel.getLineWeight();
if (isFloatEqual(lineWeight, 0.5f)) {
weightCombo.setSelectedIndex(0);
} else if (isFloatEqual(lineWeight, 1.0f)) {
weightCombo.setSelectedIndex(1);
} else if (isFloatEqual(lineWeight, 1.5f)) {
weightCombo.setSelectedIndex(2);
} else if (isFloatEqual(lineWeight, 2.0f)) {
weightCombo.setSelectedIndex(3);
}
}
private void jbInit() throws Exception {
LineStyleRenderer renderer = new LineStyleRenderer();
LineWeightIcon[] weightIcons = {new LineWeightIcon(0),
new LineWeightIcon(1),
new LineWeightIcon(2),
new LineWeightIcon(3)};
weightCombo = WidgetFactory.createComboBox(weightIcons);
weightCombo.setRenderer(renderer);
LineStyleIcon[] styleIcons = {new LineStyleIcon(0),
new LineStyleIcon(1),
new LineStyleIcon(2)};
styleCombo = WidgetFactory.createComboBox(styleIcons);
styleCombo.setRenderer(renderer);
ArrowStyleIcon[] arrowIcons = {new ArrowStyleIcon(0),
new ArrowStyleIcon(1)};
arrowCombo = WidgetFactory.createComboBox(arrowIcons);
arrowCombo.setRenderer(renderer);
JButton cancelButton = new DefaultPanelButton(Bundles.get("common.cancel.button"));
JButton okButton = new DefaultPanelButton(Bundles.get("common.ok.button"));
ActionListener btnListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttons_actionPerformed(e); }
};
cancelButton.addActionListener(btnListener);
okButton.addActionListener(btnListener);
colourButton = new ColourChooserButton(dependsPanel.getLineColour());
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(14,10,5,10);
gbc.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JLabel("Line Style:"), gbc);
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets.top = 10;
gbc.weightx = 1.0;
panel.add(styleCombo, gbc);
gbc.insets.top = 0;
gbc.gridy = 1;
panel.add(weightCombo, gbc);
gbc.gridwidth = 1;
gbc.insets.top = 5;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.gridx = 0;
panel.add(new JLabel("Line Weight:"), gbc);
gbc.gridy = 2;
panel.add(new JLabel("Arrow Style:"), gbc);
gbc.gridwidth = 2;
gbc.insets.top = 0;
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
panel.add(arrowCombo, gbc);
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
panel.add(colourButton, gbc);
gbc.insets.left = 10;
gbc.insets.top = 5;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.gridx = 0;
gbc.gridwidth = 1;
panel.add(new JLabel("Line Colour:"), gbc);
gbc.gridx = 1;
gbc.insets.right = 5;
gbc.ipadx = 25;
gbc.insets.left = 143;
gbc.insets.top = 5;
gbc.insets.bottom = 10;
gbc.weighty = 1.0;
gbc.weightx = 1.0;
gbc.gridy = 4;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
panel.add(okButton, gbc);
gbc.ipadx = 0;
gbc.insets.right = 10;
gbc.insets.left = 0;
gbc.gridx = 2;
gbc.weightx = 0;
panel.add(cancelButton, gbc);
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(450, 200));
Container c = this.getContentPane();
c.setLayout(new GridBagLayout());
c.add(panel, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.SOUTHEAST, GridBagConstraints.BOTH,
new Insets(7, 7, 7, 7), 0, 0));
setResizable(false);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
/** <p>Performs the respective action upon selection
* of a button within this dialog.
*
* @param the <code>ActionEvent</code>
*/
private void buttons_actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Cancel"))
dispose();
else if (command.equals("OK")) {
int index = weightCombo.getSelectedIndex();
float lineWeight = 0f;
switch (index) {
case 0:
lineWeight = 0.5f;
break;
case 1:
lineWeight = 1.0f;
break;
case 2:
lineWeight = 1.5f;
break;
case 3:
lineWeight = 2.0f;
break;
}
dependsPanel.setLineWeight(lineWeight);
dependsPanel.setArrowStyle(arrowCombo.getSelectedIndex() == 0 ? true : false);
dependsPanel.setLineColour(colourButton.getColour());
dependsPanel.setLineStyle(styleCombo.getSelectedIndex());
dependsPanel.repaint();
dispose();
}
}
private boolean isFloatEqual(float value1, float value2) {
return (Math.abs(value1 - value2) < .0000001);
}
} // class
/** <p>Draws the available arrow styles as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class ArrowStyleIcon extends ImageIcon {
private int type;
public ArrowStyleIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
// fill the background
g.setColor(UIUtils.getColour("executequery.Erd.background", Color.WHITE));
g.fillRect(0, 0, 290, 20);
// draw the line
g.setColor(Color.BLACK);
g.drawLine(5, 10, 250, 10);
int[] polyXs = {240, 250, 240};
int[] polyYs = {16, 10, 4};
switch (type) {
case 0:
g.fillPolygon(polyXs, polyYs, 3);
break;
case 1:
g.drawPolyline(polyXs, polyYs, 3);
break;
}
}
} // ArrowStyleIcon
class LineStyleRenderer extends JLabel
implements ListCellRenderer {
private static final Color focusColour =
UIManager.getColor("ComboBox.selectionBackground");
public LineStyleRenderer() {
super();
}
public Component getListCellRendererComponent(JList list, Object obj, int row,
boolean sel, boolean hasFocus) {
if (obj instanceof ImageIcon) {
setIcon((ImageIcon)obj);
if (sel)
setBorder(BorderFactory.createLineBorder(focusColour, 2));
else
setBorder(null);
} else
setText("ERROR");
return this;
}
} // LineStyleRenderer
/** <p>Draws the available line weights as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class LineWeightIcon extends ImageIcon {
private static final BasicStroke solidStroke_1 = new BasicStroke(0.5f);
private static final BasicStroke solidStroke_2 = new BasicStroke(1.0f);
private static final BasicStroke solidStroke_3 = new BasicStroke(1.5f);
private static final BasicStroke solidStroke_4 = new BasicStroke(2.0f);
private static final String HALF = "0.5";
private static final String ONE = "1.0";
private static final String ONE_FIVE = "1.5";
private static final String TWO = "2.0";
private int type;
public LineWeightIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D)g;
String text = null;
switch (type) {
case 0:
g2d.setStroke(solidStroke_1);
text = HALF;
break;
case 1:
g2d.setStroke(solidStroke_2);
text = ONE;
break;
case 2:
g2d.setStroke(solidStroke_3);
text = ONE_FIVE;
break;
case 3:
g2d.setStroke(solidStroke_4);
text = TWO;
break;
}
// fill the background
g2d.setColor(UIUtils.getColour("executequery.Erd.background", Color.WHITE));
g2d.fillRect(0, 0, 290, 20);
FontMetrics fm = g2d.getFontMetrics();
// draw the line style
g2d.setColor(Color.BLACK);
g2d.drawString(text, 5, fm.getHeight());
g2d.drawLine(30, 10, 250, 10);
}
} // LineWeightIcon
/** <p>Draws the available line styles as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class LineStyleIcon extends ImageIcon {
private static final BasicStroke solidStroke = new BasicStroke(1.0f);
private static final float dash1[] = {2.0f};
private static final BasicStroke dashedStroke_1 =
new BasicStroke(1.0f, 0, 0, 10f, dash1, 0.0f);
private static final float dash2[] = {5f, 2.0f};
private static final BasicStroke dashedStroke_2 =
new BasicStroke(1.0f, 0, 0, 10f, dash2, 0.0f);
private int type;
public LineStyleIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D)g;
switch (type) {
case 0:
g2d.setStroke(solidStroke);
break;
case 1:
g2d.setStroke(dashedStroke_1);
break;
case 2:
g2d.setStroke(dashedStroke_2);
break;
}
// fill the background
g2d.setColor(UIUtils.getColour("executequery.Erd.background", Color.WHITE));
g2d.fillRect(0, 0, 290, 20);
// draw the line style
g2d.setColor(Color.BLACK);
g2d.drawLine(5, 10, 250, 10);
}
} // LineStyleIcon
|
gpl-3.0
|
offbye/Tower
|
Android/src/com/o3dr/services/android/lib/drone/companion/solo/tlv/mpcc/SoloSplineAttach.java
|
2952
|
package com.o3dr.services.android.lib.drone.companion.solo.tlv.mpcc;
import android.os.Parcel;
import android.os.Parcelable;
import com.o3dr.services.android.lib.drone.companion.solo.tlv.TLVMessageTypes;
import com.o3dr.services.android.lib.drone.companion.solo.tlv.TLVPacket;
import java.nio.ByteBuffer;
/**
*
* Bidirectional.
*
* When Shotmanager enters playback mode, the vehicle may or may not be positioned on the path --
* from the app’s point of view, the actual position and velocity of the vehicle with respect to
* the Path are unknown.
*
* This message directs Shotmanager to fly to a Keypoint on the Path.
* After the vehicle reaches this point, Shotmanager responds with a SOLO_SPLINE_ATTACH to
* indicate that it has reached the Path and is prepared to receive SOLO_SPLINE_SEEK messages.
*
*
* This message is only valid once after a Path is loaded. There is no corresponding “detach”
* message -- the vehicle stays attached until playback mode is exited.
*
* @since 2.8.0
*/
public class SoloSplineAttach extends TLVPacket {
public static final int MESSAGE_LENGTH = 4;
/**
* The index of the Keypoint on the currently defined Path to which Shotmanager will attach
* (or did attach, for Shotmanager to App packets).
*/
private final int keypointIndex;
public SoloSplineAttach(int keypointIndex) {
super(TLVMessageTypes.TYPE_SOLO_SPLINE_ATTACH, MESSAGE_LENGTH);
this.keypointIndex = keypointIndex;
}
protected SoloSplineAttach(Parcel in) {
super(in);
this.keypointIndex = in.readInt();
}
public SoloSplineAttach(ByteBuffer buffer){
this(buffer.getInt());
}
@Override
protected void getMessageValue(ByteBuffer valueCarrier) {
valueCarrier.putInt(keypointIndex);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SoloSplineAttach)) return false;
if (!super.equals(o)) return false;
SoloSplineAttach that = (SoloSplineAttach) o;
return that.keypointIndex == keypointIndex;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (keypointIndex != +0.0f ? Float.floatToIntBits(keypointIndex) : 0);
return result;
}
public int getKeypointIndex() {
return keypointIndex;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(this.keypointIndex);
}
public static final Creator<SoloSplineAttach> CREATOR = new Creator<SoloSplineAttach>() {
@Override
public SoloSplineAttach createFromParcel(Parcel source) {
return new SoloSplineAttach(source);
}
@Override
public SoloSplineAttach[] newArray(int size) {
return new SoloSplineAttach[size];
}
};
}
|
gpl-3.0
|
pantelis60/L2Scripts_Underground
|
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ExPledgeWaitingUser.java
|
377
|
package l2s.gameserver.network.l2.s2c;
/**
* @author GodWorld
* @reworked by Bonux
**/
public class ExPledgeWaitingUser extends L2GameServerPacket
{
private final int _charId;
private final String _desc;
public ExPledgeWaitingUser(int charId, String desc)
{
_charId = charId;
_desc = desc;
}
protected void writeImpl()
{
writeD(_charId);
writeS(_desc);
}
}
|
gpl-3.0
|
xoddark/ArxLibertatis
|
tools/profiler/ProfilerMain.cpp
|
1232
|
/*
* Copyright 2014 Arx Libertatis Team (see the AUTHORS file)
*
* This file is part of Arx Libertatis.
*
* Arx Libertatis 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.
*
* Arx Libertatis 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 Arx Libertatis. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include "profiler/ui/ArxProfiler.h"
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
INT WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR, INT) {
QApplication app(__argc, __argv);
#else
int main(int argc, char **argv) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QApplication app(argc, argv);
#endif
ArxProfiler w;
w.show();
return app.exec();
}
|
gpl-3.0
|
SpoutDev/BukkitBridge
|
src/main/java/org/spout/bridge/bukkit/entity/BridgeComplexPart.java
|
1358
|
/*
* This file is part of BukkitBridge.
*
* Copyright (c) 2012 Spout LLC <http://www.spout.org/>
* BukkitBridge is licensed under the GNU General Public License.
*
* BukkitBridge 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.
*
* BukkitBridge 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.spout.bridge.bukkit.entity;
import org.bukkit.entity.ComplexEntityPart;
import org.bukkit.entity.ComplexLivingEntity;
import org.bukkit.entity.EntityType;
import org.spout.api.entity.Entity;
public class BridgeComplexPart extends BridgeEntity implements ComplexEntityPart {
protected BridgeComplexPart(Entity handle) {
super(handle);
}
@Override
public ComplexLivingEntity getParent() {
throw new UnsupportedOperationException();
}
@Override
public EntityType getType() {
return EntityType.COMPLEX_PART;
}
}
|
gpl-3.0
|
bildzeitung/hind
|
lua/libraries/loveframes/objects/internal/columnlist/columnlist-row.lua
|
4806
|
--[[------------------------------------------------
-- LÖVE Frames --
-- By Nikolai Resokav --
--]]------------------------------------------------
-- columnlistrow object
columnlistrow = class("columnlistrow", base)
columnlistrow:include(loveframes.templates.default)
--[[---------------------------------------------------------
- func: initialize()
- desc: intializes the element
--]]---------------------------------------------------------
function columnlistrow:initialize(parent, data)
self.type = "columnlistrow"
self.parent = parent
self.colorindex = self.parent.rowcolorindex
self.font = love.graphics.newFont(10)
self.textcolor = {0, 0, 0, 255}
self.width = 80
self.height = 25
self.textx = 5
self.texty = 5
self.internal = true
self.columndata = data
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function columnlistrow:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if visible == false then
if alwaysupdate == false then
return
end
end
self:CheckHover()
-- move to parent if there is a parent
if self.parent ~= loveframes.base then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
if self.Update then
self.Update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function columnlistrow:draw()
local visible = self.visible
if visible == false then
return
end
loveframes.drawcount = loveframes.drawcount + 1
self.draworder = loveframes.drawcount
-- skin variables
local index = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = loveframes.skins.available[selfskin] or loveframes.skins.available[index] or loveframes.skins.available[defaultskin]
if self.Draw ~= nil then
self.Draw(self)
else
skin.DrawColumnListRow(self)
end
local cwidth, cheight = self:GetParent():GetParent():GetColumnSize()
local x = self.textx
local textcolor = self.textcolor
for k, v in ipairs(self.columndata) do
love.graphics.setFont(self.font)
love.graphics.setColor(unpack(textcolor))
love.graphics.print(v, self.x + x, self.y + self.texty)
x = x + cwidth
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function columnlistrow:mousepressed(x, y, button)
if self.visible == false then
return
end
if self.hover == true and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function columnlistrow:mousereleased(x, y, button)
if self.visible == false then
return
end
if self.hover == true and button == "l" then
local parent1 = self:GetParent()
local parent2 = parent1:GetParent()
if parent2.OnRowClicked then
parent2.OnRowClicked(parent2, self, self.columndata)
end
end
end
--[[---------------------------------------------------------
- func: SetTextPos(x, y)
- desc: sets the positions of the object's text
--]]---------------------------------------------------------
function columnlistrow:SetTextPos(x, y)
self.textx = x
self.texty = y
end
--[[---------------------------------------------------------
- func: SetFont(font)
- desc: sets the object's font
--]]---------------------------------------------------------
function columnlistrow:SetFont(font)
self.font = font
end
--[[---------------------------------------------------------
- func: GetFont()
- desc: gets the object's font
--]]---------------------------------------------------------
function columnlistrow:GetFont()
return self.font
end
--[[---------------------------------------------------------
- func: GetColorIndex()
- desc: gets the object's color index
--]]---------------------------------------------------------
function columnlistrow:GetColorIndex()
return self.colorindex
end
--[[---------------------------------------------------------
- func: SetTextColor(color)
- desc: sets the object's text color
--]]---------------------------------------------------------
function columnlistrow:SetTextColor(color)
self.textcolor = color
end
|
gpl-3.0
|
lgulyas/MEME
|
Plugins/intellisweepPlugin/ai/aitia/meme/paramsweep/intellisweepPlugin/utils/ga/DefaultMutation.java
|
4375
|
/*******************************************************************************
* Copyright (C) 2006-2013 AITIA International, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ai.aitia.meme.paramsweep.intellisweepPlugin.utils.ga;
import java.io.Serializable;
import java.util.List;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import ai.aitia.meme.utils.FormsUtils;
import cern.jet.random.Uniform;
import cern.jet.random.engine.MersenneTwister;
public class DefaultMutation implements IGAOperator, Serializable {
//=========================================================================
//members
private static final long serialVersionUID = 7385576920337495076L;
protected static Random genSelection = new Random( 1 );
protected static Uniform genValue;
protected double geneMutProb = 0.01;
//settings panel
protected transient JPanel settingsPanel = null;
protected transient JTextField geneMutProbField = new JTextField();
static{
MersenneTwister gEngine = new MersenneTwister( 1 );
genValue = new Uniform( gEngine );
}
//=========================================================================
//public static functions
/**
* Sets the random seed for the pseudo-random generator, that is used to
* select genes randomly for mutation.
*/
public static void initSelectionGenerator( int seed ){
genSelection = new Random( seed );
}
/**
* Sets the random seed for the pseudo-random generator, that is used to
* generate new random values for the genes.
*/
public static void initValueGenerator( int seed ){
MersenneTwister gEngine = new MersenneTwister( seed );
genValue = new Uniform( gEngine );
}
/**
* Mutates the solutions: each gene is mutated at equal probability.
*
* @param <T> is the type of the gene
* @param solution is the list of a solution's genes.
* @param mutationProb is the probability of the mutation of each gene
* (an element of the [0,1] interval).
*/
/*public static void mutate( List<IMutableGene> solution, double mutationProb ){
for( int j = 0; j < solution.size(); ++j ){
double nextRnd = genSelection.nextDouble();
if( nextRnd < mutationProb ){
solution.get( j ).mutate();
}
}
}*/
//=========================================================================
//implemented interfaces
public void operate(List<Chromosome> population,
List<Chromosome> nextPopulation, boolean maximizeFitness) {
for( int i = 0; i < nextPopulation.size(); ++i ){
Chromosome ch = nextPopulation.get( i );
for( int j = 0; j < ch.getSize(); ++j ){
double nextRnd = genSelection.nextDouble();
if( nextRnd < geneMutProb ){
ch.geneAt( j ).setValue( ch.geneAt( j ).getUniformRandomValue( genValue ) );
}
}
}
}
public String getDescription() {
return "Default mutation";
}
public String getName() {
return "Default mutation";
}
public JPanel getSettingspanel() {
// TODO Auto-generated method stub
if( settingsPanel == null ){
geneMutProbField.setColumns( 15 );
geneMutProbField.setText( String.valueOf( geneMutProb ) );
settingsPanel = FormsUtils.build( "p p",
"01 p",
new JLabel( "Gene mutation probability: " ),
geneMutProbField ).getPanel();
}
return settingsPanel;
}
public String saveSettings() {
try{
geneMutProb = Integer.valueOf( geneMutProbField.getText() );
}catch( NumberFormatException e ){
return "'" + geneMutProbField.getText() + "' is not a valid value!";
}
return null;
}
public String getPackageName() {
return null;
}
}
|
gpl-3.0
|
LouisStrous/LUX
|
src/idl.cc
|
12149
|
/* This is file idl.cc.
Copyright 2013-2014 Louis Strous
This file is part of LUX.
LUX 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.
LUX 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 LUX. If not, see <http://www.gnu.org/licenses/>.
*/
/* LUX routines for reading IDL Save files
Louis Strous 19sep98 */
#include <stdio.h>
#include "action.hh"
int32_t lux_idlrestore(int32_t narg, int32_t ps[])
/* IDLRESTORE,<filename> restores all variables from the IDL Save file
with name <filename>. Supports scalars, strings, and numerical arrays
LS 18sep98 */
{
uint8_t bytes[8];
char *p;
int32_t ints[3], dims[MAX_DIMS], n, var, ndim, nread;
Symboltype type;
FILE *fp;
void endian(void *, int32_t, int32_t);
int32_t installString(char const*);
Scalar value;
Pointer pp, data;
if (!symbol_class(ps[0]) == LUX_STRING)
return cerror(NEED_STR, ps[0]);
// open the file
fp = fopen(expand_name(string_value(ps[0]), NULL), "r");
if (!fp)
return cerror(ERR_OPEN, ps[0]);
fread(bytes, 1, 4, fp);
if (ferror(fp) || feof(fp)) {
fclose(fp);
return luxerror("Could not check file %s for IDL Save format", ps[0],
expname);
}
if (bytes[0] != 83
|| bytes[1] != 82
|| bytes[2] != 0
|| bytes[3] != 4) {
fclose(fp);
return luxerror("File %s does not appear to be an IDL Save file", ps[0],
expname);
}
/* we now assume that the file is in fact an IDL save file and do not
check for I/O errors anymore */
pp.ui8 = &value.ui8;
fseek(fp, 4, SEEK_CUR); // skip one int32_t
fread(ints, 4, 1, fp); // read one int32_t
#if !LITTLEENDIAN
endian(ints, 4, LUX_INT32);
#endif
fseek(fp, ints[0], SEEK_SET); // go to the indicated offset
nread = 0;
do {
fread(ints, 4, 2, fp); // read 2 ints
#if !LITTLEENDIAN
endian(ints, 8, LUX_INT32);
#endif
if (ints[0] == 14) {
fseek(fp, ints[1], SEEK_SET);
continue;
} else if (ints[0] != 2) { // all done
fclose(fp);
if (!nread)
printf("IDLRESTORE - No variables found in IDL Save file \"%s\"??\n",
expname);
return LUX_OK;
}
nread++;
fread(ints, 4, 3, fp); // read 3 ints
#if !LITTLEENDIAN
endian(ints, 12, LUX_INT32);
#endif
n = ints[2]; // size of name
fread(curScrat, 1, n, fp);
curScrat[n] = '\0';
printf("restoring %s\n", curScrat);
n = installString(curScrat);
var = findVar(n, curContext); // get the variable
// align on next 4-Byte boundary
n = 3 - (ints[2] - 1) % 4;
if (n)
fseek(fp, n, SEEK_CUR);
fread(ints, 4, 3, fp);
#if !LITTLEENDIAN
endian(ints, 12, LUX_INT32);
#endif
if (ints[1] == 20) { // array
type = (Symboltype) ints[0];
fseek(fp, 12, SEEK_CUR);
fread(ints, 4, 1, fp);
#if !LITTLEENDIAN
endian(ints, 4, LUX_INT32);
#endif
ndim = ints[0]; // number of dimensions
fseek(fp, 12, SEEK_CUR); // skip 3 ints
fread(dims, 4, 8, fp); // read dimensions
#if !LITTLEENDIAN
endian(dims, 4*ndim, LUX_INT32);
#endif
redef_array(var, (Symboltype) (type - 1), ndim, dims);
fseek(fp, 4, SEEK_CUR);
n = array_size(var);
data.ui8 = (uint8_t*) array_data(var);
switch (type) {
case 1: // bytes stored as longs (!)
fseek(fp, 4, SEEK_CUR); // skip extra int32_t
fread(data.ui8, 1, n, fp);
n = 3 - (n - 1) % 4;
if (n) // align on int32_t boundary
fseek(fp, n, SEEK_CUR);
break;
case 2: // int16_t
/* words are stored as longs (!) so we have to read them one by
one and Byte-swap if necessary */
while (n--) {
fread(pp.ui8, 4, 1, fp);
#if !LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
*data.i16++ = *pp.i32;
}
break;
case 3: case 4: case 5: // long, float, double
fread(data.ui8, lux_type_size[type - 1], n, fp);
#if !LITTLEENDIAN
endian(data.ui8, lux_type_size[type - 1]*n, LUX_INT32);
#endif
break;
default:
fclose(fp);
return luxerror("Unsupported data type %d in IDL Save file %s\n", ps[0],
type, expname);
}
} else { // assume scalar or string
switch (ints[0]) {
case 1: // Byte
fread(pp.ui8, 1, 4, fp);
#if !LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
value.ui8 = value.i32;
redef_scalar(var, LUX_INT8, &value.ui8);
break;
case 2: // int16_t
fread(pp.ui8, 1, 4, fp); // words are stored as ints
#if !LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
value.i16 = value.i32;
redef_scalar(var, LUX_INT16, &value.i16);
break;
case 3: // long
fread(pp.ui8, 1, 4, fp);
#if !LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
redef_scalar(var, LUX_INT32, &value.i32);
break;
case 4: // float
fread(pp.ui8, 1, 4, fp);
#if !LITTLEENDIAN
endian(pp.ui8, 4, LUX_FLOAT);
#endif
redef_scalar(var, LUX_FLOAT, &value.f);
break;
case 5: // double
fread(pp.ui8, 1, 8, fp);
#if !LITTLEENDIAN
endian(pp.ui8, 8, LUX_DOUBLE);
#endif
redef_scalar(var, LUX_DOUBLE, &value.d);
break;
case 7: // string
fread(ints, 4, 2, fp);
#if !LITTLEENDIAN
endian(ints, 4, LUX_INT32);
#endif
redef_string(var, ints[0]);
p = string_value(var);
fread(p, 1, ints[0], fp);
p[ints[0]] = '\0'; // terminate string
n = 3 - (ints[0] - 1) % 4;
if (n)
fseek(fp, n, SEEK_CUR); // align on int32_t
break;
default:
fclose(fp);
return luxerror("Unsupported data type %d in IDL Save file %s\n", ps[0],
type, expname);
}
}
} while (1);
}
//-----------------------------------------------------------------------
int32_t lux_idlread_f(int32_t narg, int32_t ps[])
/* IDLREAD(<var>, <filename>) restores the first variable from the IDL
Save file with name <filename> into <var>. Supports scalars, strings,
and numerical arrays. Returns LUX_ONE on success, LUX_ZERO on failure.
LS 18sep98 */
{
uint8_t bytes[8];
char *p;
int32_t ints[3], dims[MAX_DIMS], n, var, ndim, type;
FILE *fp;
void endian(void *, int32_t, int32_t);
Scalar value;
Pointer pp, data;
if (!symbol_class(ps[1]) == LUX_STRING)
return cerror(NEED_STR, ps[1]);
// open the file
fp = fopen(expand_name(string_value(ps[1]), NULL), "r");
if (!fp)
return LUX_ZERO;
fread(bytes, 1, 4, fp);
if (ferror(fp) || feof(fp)) {
fclose(fp);
return LUX_ZERO;
}
if (bytes[0] != 83
|| bytes[1] != 82
|| bytes[2] != 0
|| bytes[3] != 4) {
fclose(fp);
return LUX_ZERO;
}
/* we now assume that the file is in fact an IDL save file and do not
check for I/O errors anymore */
pp.ui8 = &value.ui8;
fseek(fp, 4, SEEK_CUR); // skip one int32_t
fread(ints, 4, 1, fp); // read one int32_t
#if LITTLEENDIAN
endian(ints, 4, LUX_INT32);
#endif
fseek(fp, ints[0], SEEK_SET); // go to the indicated offset
do {
fread(ints, 4, 2, fp); // read 2 ints
#if LITTLEENDIAN
endian(ints, 8, LUX_INT32);
#endif
if (ints[0] == 14) {
fseek(fp, ints[1], SEEK_SET);
continue;
} else if (ints[0] != 2) { // all done, but we didn't read anything
fclose(fp);
return LUX_ZERO; // so some error must have occurred
}
break;
} while (1);
fread(ints, 4, 3, fp); // read 3 ints
#if LITTLEENDIAN
endian(ints, 12, LUX_INT32);
#endif
n = ints[2]; // size of name
fseek(fp, n, SEEK_CUR); // skip name
var = ps[0]; // get the variable
// align on next 4-Byte boundary
n = 3 - (ints[2] - 1) % 4;
if (n)
fseek(fp, n, SEEK_CUR);
fread(ints, 4, 3, fp);
#if LITTLEENDIAN
endian(ints, 12, LUX_INT32);
#endif
if (ints[1] == 20) { // array
type = ints[0];
fseek(fp, 12, SEEK_CUR);
fread(ints, 4, 1, fp);
#if LITTLEENDIAN
endian(ints, 4, LUX_INT32);
#endif
ndim = ints[0]; // number of dimensions
fseek(fp, 12, SEEK_CUR); // skip 3 ints
fread(dims, 4, 8, fp); // read dimensions
#if LITTLEENDIAN
endian(dims, 4*ndim, LUX_INT32);
#endif
redef_array(var, (Symboltype) (type - 1), ndim, dims);
fseek(fp, 4, SEEK_CUR);
n = array_size(var);
data.ui8 = (uint8_t*) array_data(var);
switch (type) {
case 1: // bytes stored as longs (!)
fseek(fp, 4, SEEK_CUR); // skip extra int32_t
fread(data.ui8, 1, n, fp);
break;
case 2: // int16_t
/* words are stored as longs (!) so we have to read them one by
one and Byte-swap if necessary */
while (n--) {
fread(pp.ui8, 4, 1, fp);
#if LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
*data.i16++ = *pp.i32;
}
break;
case 3: case 4: case 5: // long, float, double
fread(data.ui8, lux_type_size[type - 1], n, fp);
#if LITTLEENDIAN
endian(data.ui8, lux_type_size[type - 1]*n, LUX_INT32);
#endif
break;
default:
fclose(fp);
return LUX_ZERO;
}
} else { // assume scalar or string
switch (ints[0]) {
case 1: // Byte
fread(pp.ui8, 1, 4, fp);
#if LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
value.ui8 = value.i32;
redef_scalar(var, LUX_INT8, &value.ui8);
break;
case 2: // int16_t
fread(pp.ui8, 1, 4, fp); // words are stored as ints
#if LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
value.i16 = value.i32;
redef_scalar(var, LUX_INT16, &value.i16);
break;
case 3: // long
fread(pp.ui8, 1, 4, fp);
#if LITTLEENDIAN
endian(pp.ui8, 4, LUX_INT32);
#endif
redef_scalar(var, LUX_INT32, &value.i32);
break;
case 4: // float
fread(pp.ui8, 1, 4, fp);
#if LITTLEENDIAN
endian(pp.ui8, 4, LUX_FLOAT);
#endif
redef_scalar(var, LUX_FLOAT, &value.f);
break;
case 5: // double
fread(pp.ui8, 1, 8, fp);
#if LITTLEENDIAN
endian(pp.ui8, 8, LUX_DOUBLE);
#endif
redef_scalar(var, LUX_DOUBLE, &value.d);
break;
case 7: // string
redef_string(var, ints[2]);
p = string_value(var);
fread(ints, 4, 2, fp);
#if LITTLEENDIAN
endian(ints + 1, 4, LUX_INT32);
#endif
fread(p, 1, ints[1], fp);
p[ints[1]] = '\0'; // terminate string
break;
default:
fclose(fp);
return LUX_ZERO;
}
}
fclose(fp);
return LUX_ONE;
}
//-----------------------------------------------------------------------
|
gpl-3.0
|
rAthenaCN/rAthenaCN
|
src/map/achievement.cpp
|
31755
|
// Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
// For more information, see LICENCE in the main folder
#include "achievement.hpp"
#include <array>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yaml-cpp/yaml.h>
#include "../common/cbasetypes.hpp"
#include "../common/database.hpp"
#include "../common/malloc.hpp"
#include "../common/nullpo.hpp"
#include "../common/showmsg.hpp"
#include "../common/strlib.hpp"
#include "../common/utilities.hpp"
#include "../common/utils.hpp"
#include "battle.hpp"
#include "chrif.hpp"
#include "clif.hpp"
#include "intif.hpp"
#include "itemdb.hpp"
#include "map.hpp"
#include "npc.hpp"
#include "pc.hpp"
#include "script.hpp"
#include "status.hpp"
using namespace rathena;
void AchievementDatabase::clear(){
TypesafeYamlDatabase::clear();
this->achievement_mobs.clear();
}
const std::string AchievementDatabase::getDefaultLocation(){
return std::string(db_path) + "/achievement_db.yml";
}
/**
* Reads and parses an entry from the achievement_db.
* @param node: YAML node containing the entry.
* @return count of successfully parsed rows
*/
uint64 AchievementDatabase::parseBodyNode(const YAML::Node &node){
uint32 achievement_id;
// TODO: doesnt match camel case
if( !this->asUInt32( node, "ID", achievement_id ) ){
return 0;
}
std::shared_ptr<s_achievement_db> achievement = this->find( achievement_id );
bool exists = achievement != nullptr;
if( !exists ){
if( !this->nodeExists( node, "Group" ) ){
return 0;
}
if( !this->nodeExists( node, "Name" ) ){
return 0;
}
achievement = std::make_shared<s_achievement_db>();
achievement->achievement_id = achievement_id;
}
if( this->nodeExists( node, "Group" ) ){
std::string group_name;
if( !this->asString( node, "Group", group_name ) ){
return 0;
}
int64 constant;
if( !script_get_constant( group_name.c_str(), &constant ) ){
this->invalidWarning( node, "achievement_read_db_sub: Invalid group %s for achievement %d, skipping.\n", group_name.c_str(), achievement_id );
return 0;
}
achievement->group = (e_achievement_group)constant;
}
if( this->nodeExists( node, "Name" ) ){
std::string name;
if( !this->asString( node, "Name", name ) ){
return 0;
}
achievement->name = name;
}
if( this->nodeExists( node, "Target" ) ){
const YAML::Node& targets = node["Target"];
for( const YAML::Node& targetNode : targets ){
if( achievement->targets.size() >= MAX_ACHIEVEMENT_OBJECTIVES ){
this->invalidWarning( targetNode, "Node \"Target\" list exceeds the maximum of %d, skipping.\n", MAX_ACHIEVEMENT_OBJECTIVES );
return 0;
}
uint16 targetId;
if( !this->asUInt16( targetNode, "Id", targetId ) ){
continue;
}
if( targetId >= MAX_ACHIEVEMENT_OBJECTIVES ){
this->invalidWarning( targetNode["Id"], "Node \"Id\" is out of valid range [0,%d], skipping.\n", MAX_ACHIEVEMENT_OBJECTIVES );
return 0;
}
std::shared_ptr<achievement_target> target = rathena::util::map_find( achievement->targets, targetId );
bool targetExists = target != nullptr;
if( !targetExists ){
if( !this->nodeExists( targetNode, "Count" ) && !this->nodeExists( targetNode, "MobID" ) ){
this->invalidWarning( targetNode, "Node \"Target\" has no data specified, skipping.\n" );
return 0;
}
target = std::make_shared<achievement_target>();
}
if( this->nodeExists( targetNode, "Count" ) ){
uint32 count;
if( !this->asUInt32( targetNode, "Count", count ) ){
return 0;
}
target->count = count;
}else{
if( !targetExists ){
target->count = 0;
}
}
if( this->nodeExists( targetNode, "MobID" ) ){
if( achievement->group != AG_BATTLE && achievement->group != AG_TAMING ){
this->invalidWarning( targets, "Node \"MobID\" is only supported for targets in group AG_BATTLE or AG_TAMING, skipping.\n" );
return 0;
}
uint32 mob_id;
// TODO: not camel case
if( !this->asUInt32( targetNode, "MobID", mob_id ) ){
return 0;
}
if( mob_db( mob_id ) == nullptr ){
this->invalidWarning( targetNode["MobID"], "Unknown monster ID %d, skipping.\n", mob_id );
return 0;
}
if( !this->mobexists( mob_id ) ){
this->achievement_mobs.push_back( mob_id );
}
target->mob = mob_id;
}else{
if( !targetExists ){
target->mob = 0;
}
}
achievement->targets[targetId] = target;
}
}
if( this->nodeExists( node, "Condition" ) ){
std::string condition;
if( !this->asString( node, "Condition", condition ) ){
return 0;
}
if( condition.find( "achievement_condition" ) == std::string::npos ){
condition = "achievement_condition( " + condition + " );";
}
if( achievement->condition ){
aFree( achievement->condition );
achievement->condition = nullptr;
}
achievement->condition = parse_script( condition.c_str(), this->getCurrentFile().c_str(), node["Condition"].Mark().line + 1, SCRIPT_IGNORE_EXTERNAL_BRACKETS );
}else{
achievement->condition = nullptr;
}
if( this->nodeExists( node, "Map" ) ){
if( achievement->group != AG_CHAT ){
this->invalidWarning( node, "Node \"Map\" can only be used with the group AG_CHATTING, skipping.\n" );
return 0;
}
std::string mapname;
if( !this->asString( node, "Map", mapname ) ){
return 0;
}
achievement->mapindex = map_mapname2mapid( mapname.c_str() );
if( achievement->mapindex == -1 ){
this->invalidWarning( node["Map"], "Unknown map name '%s'.\n", mapname.c_str() );
return 0;
}
}else{
if( !exists ){
achievement->mapindex = -1;
}
}
if( this->nodeExists( node, "Dependent" ) ){
for( const YAML::Node& subNode : node["Dependent"] ){
uint32 dependent_achievement_id;
if( !this->asUInt32( subNode, "Id", dependent_achievement_id ) ){
return 0;
}
// TODO: import logic for clearing => continue
// TODO: change to set to prevent multiple entries with the same id?
achievement->dependent_ids.push_back( dependent_achievement_id );
}
}
// TODO: not plural
if( this->nodeExists( node, "Reward" ) ){
const YAML::Node& rewardNode = node["Reward"];
// TODO: not camel case
if( this->nodeExists( rewardNode, "ItemID" ) ){
uint16 itemId;
if( !this->asUInt16( rewardNode, "ItemID", itemId ) ){
return 0;
}
if( !itemdb_exists( itemId ) ){
this->invalidWarning( rewardNode["ItemID"], "Unknown item with ID %hu.\n", itemId );
return 0;
}
achievement->rewards.nameid = itemId;
if( achievement->rewards.amount == 0 ){
// Default the amount to 1
achievement->rewards.amount = 1;
}
}
if( this->nodeExists( rewardNode, "Amount" ) ){
uint16 amount;
if( !this->asUInt16( rewardNode, "Amount", amount ) ){
return 0;
}
achievement->rewards.amount = amount;
}
if( this->nodeExists( rewardNode, "Script" ) ){
std::string script;
if( !this->asString( rewardNode, "Script", script ) ){
return 0;
}
if( achievement->rewards.script ){
aFree( achievement->rewards.script );
achievement->rewards.script = nullptr;
}
achievement->rewards.script = parse_script( script.c_str(), this->getCurrentFile().c_str(), achievement_id, SCRIPT_IGNORE_EXTERNAL_BRACKETS );
}else{
achievement->rewards.script = nullptr;
}
// TODO: not camel case
if( this->nodeExists( rewardNode, "TitleID" ) ){
uint32 title;
if( !this->asUInt32( rewardNode, "TitleID", title ) ){
return 0;
}
achievement->rewards.title_id = title;
}
}
if( this->nodeExists( node, "Score" ) ){
uint32 score;
if( !this->asUInt32( node, "Score", score ) ){
return 0;
}
achievement->score = score;
}
if( !exists ){
this->put( achievement_id, achievement );
}
return 1;
}
AchievementDatabase achievement_db;
/**
* Searches for an achievement by monster ID
* @param mob_id: Monster ID to lookup
* @return True on success, false on failure
*/
bool AchievementDatabase::mobexists( uint32 mob_id ){
if (!battle_config.feature_achievement)
return false;
auto it = std::find(this->achievement_mobs.begin(), this->achievement_mobs.end(), mob_id);
return (it != this->achievement_mobs.end()) ? true : false;
}
const std::string AchievementLevelDatabase::getDefaultLocation(){
return std::string(db_path) + "/achievement_level_db.yml";
}
uint64 AchievementLevelDatabase::parseBodyNode( const YAML::Node &node ){
if( !this->nodesExist( node, { "Level", "Points" } ) ){
return 0;
}
uint16 level;
if( !this->asUInt16( node, "Level", level ) ){
return 0;
}
if( level == 0 ){
this->invalidWarning( node, "Invalid achievement level %hu (minimum value: 1), skipping.\n", level );
return 0;
}
// Make it zero based
level -= 1;
std::shared_ptr<s_achievement_level> ptr = this->find( level );
bool exists = ptr != nullptr;
if( !exists ){
ptr = std::make_shared<s_achievement_level>();
ptr->level = level;
}
uint16 points;
if (!this->asUInt16(node, "Points", points)) {
return 0;
}
ptr->points = points;
if( !exists ){
this->put( level, ptr );
}
return 1;
}
AchievementLevelDatabase achievement_level_db;
/**
* Add an achievement to the player's log
* @param sd: Player data
* @param achievement_id: Achievement to add
* @return NULL on failure, achievement data on success
*/
struct achievement *achievement_add(struct map_session_data *sd, int achievement_id)
{
int i, index;
nullpo_retr(NULL, sd);
std::shared_ptr<s_achievement_db> adb = achievement_db.find( achievement_id );
if( adb == nullptr ){
ShowError( "achievement_add: Achievement %d not found in DB.\n", achievement_id );
return nullptr;
}
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i < sd->achievement_data.count) {
ShowError("achievement_add: Character %d already has achievement %d.\n", sd->status.char_id, achievement_id);
return NULL;
}
index = sd->achievement_data.incompleteCount;
sd->achievement_data.count++;
sd->achievement_data.incompleteCount++;
RECREATE(sd->achievement_data.achievements, struct achievement, sd->achievement_data.count);
// The character has some completed achievements, make room before them so that they will stay at the end of the array
if (sd->achievement_data.incompleteCount != sd->achievement_data.count)
memmove(&sd->achievement_data.achievements[index + 1], &sd->achievement_data.achievements[index], sizeof(struct achievement) * (sd->achievement_data.count - sd->achievement_data.incompleteCount));
memset(&sd->achievement_data.achievements[index], 0, sizeof(struct achievement));
sd->achievement_data.achievements[index].achievement_id = achievement_id;
sd->achievement_data.achievements[index].score = adb->score;
sd->achievement_data.save = true;
clif_achievement_update(sd, &sd->achievement_data.achievements[index], sd->achievement_data.count - sd->achievement_data.incompleteCount);
return &sd->achievement_data.achievements[index];
}
/**
* Removes an achievement from a player's log
* @param sd: Player's data
* @param achievement_id: Achievement to remove
* @return True on success, false on failure
*/
bool achievement_remove(struct map_session_data *sd, int achievement_id)
{
struct achievement dummy;
int i;
nullpo_retr(false, sd);
if (!achievement_db.exists(achievement_id)) {
ShowError("achievement_delete: Achievement %d not found in DB.\n", achievement_id);
return false;
}
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i == sd->achievement_data.count) {
ShowError("achievement_delete: Character %d doesn't have achievement %d.\n", sd->status.char_id, achievement_id);
return false;
}
if (!sd->achievement_data.achievements[i].completed)
sd->achievement_data.incompleteCount--;
if (i != sd->achievement_data.count - 1)
memmove(&sd->achievement_data.achievements[i], &sd->achievement_data.achievements[i + 1], sizeof(struct achievement) * (sd->achievement_data.count - 1 - i));
sd->achievement_data.count--;
if( sd->achievement_data.count == 0 ){
aFree(sd->achievement_data.achievements);
sd->achievement_data.achievements = NULL;
}else{
RECREATE(sd->achievement_data.achievements, struct achievement, sd->achievement_data.count);
}
sd->achievement_data.save = true;
// Send a removed fake achievement
memset(&dummy, 0, sizeof(struct achievement));
dummy.achievement_id = achievement_id;
clif_achievement_update(sd, &dummy, sd->achievement_data.count - sd->achievement_data.incompleteCount);
return true;
}
/**
* Lambda function that checks for completed achievements
* @param sd: Player data
* @param achievement_id: Achievement to check if it's complete
* @return True on completed, false if not
*/
static bool achievement_done(struct map_session_data *sd, int achievement_id) {
for (int i = 0; i < sd->achievement_data.count; i++) {
if (sd->achievement_data.achievements[i].achievement_id == achievement_id && sd->achievement_data.achievements[i].completed > 0)
return true;
}
return false;
}
/**
* Checks to see if an achievement has a dependent, and if so, checks if that dependent is complete
* @param sd: Player data
* @param achievement_id: Achievement to check if it has a dependent
* @return False on failure or not complete, true on complete or no dependents
*/
bool achievement_check_dependent(struct map_session_data *sd, int achievement_id)
{
nullpo_retr(false, sd);
std::shared_ptr<s_achievement_db> adb = achievement_db.find( achievement_id );
if( adb == nullptr ){
return false;
}
// Check if the achievement has a dependent
// If so, then do a check on all dependents to see if they're complete
for (int i = 0; i < adb->dependent_ids.size(); i++) {
if (!achievement_done(sd, adb->dependent_ids[i]))
return false; // One of the dependent is not complete!
}
return true;
}
/**
* Check achievements that only have dependents and no other requirements
* @param sd: Player to update
* @param sd: Achievement to compare for completed dependents
* @return True if successful, false if not
*/
static int achievement_check_groups(struct map_session_data *sd, struct s_achievement_db *ad)
{
int i;
if (ad == NULL || sd == NULL)
return 0;
if (ad->group != AG_BATTLE && ad->group != AG_TAMING && ad->group != AG_ADVENTURE)
return 0;
if (ad->dependent_ids.empty() || ad->condition)
return 0;
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == ad->achievement_id);
if (i == sd->achievement_data.count) { // Achievement isn't in player's log
if (achievement_check_dependent(sd, ad->achievement_id) == true) {
achievement_add(sd, ad->achievement_id);
achievement_update_achievement(sd, ad->achievement_id, true);
}
}
return 1;
}
/**
* Update an achievement
* @param sd: Player to update
* @param achievement_id: Achievement ID of the achievement to update
* @param complete: Complete state of an achievement
* @return True if successful, false if not
*/
bool achievement_update_achievement(struct map_session_data *sd, int achievement_id, bool complete)
{
int i;
nullpo_retr(false, sd);
std::shared_ptr<s_achievement_db> adb = achievement_db.find( achievement_id );
if( adb == nullptr ){
return false;
}
ARR_FIND(0, sd->achievement_data.incompleteCount, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i == sd->achievement_data.incompleteCount)
return false;
if (sd->achievement_data.achievements[i].completed > 0)
return false;
// Finally we send the updated achievement to the client
if (complete) {
if (!adb->targets.empty()) { // Make sure all the objective targets are at their respective total requirement
for (const auto &it : adb->targets)
sd->achievement_data.achievements[i].count[it.first] = it.second->count;
}
sd->achievement_data.achievements[i].completed = time(NULL);
if (i < (--sd->achievement_data.incompleteCount)) { // The achievement needs to be moved to the completed achievements block at the end of the array
struct achievement tmp_ach;
memcpy(&tmp_ach, &sd->achievement_data.achievements[i], sizeof(struct achievement));
memcpy(&sd->achievement_data.achievements[i], &sd->achievement_data.achievements[sd->achievement_data.incompleteCount], sizeof(struct achievement));
memcpy(&sd->achievement_data.achievements[sd->achievement_data.incompleteCount], &tmp_ach, sizeof(struct achievement));
}
achievement_level(sd, true); // Re-calculate achievement level
// Check dependents
for (auto &ach : achievement_db)
achievement_check_groups(sd, ach.second.get());
ARR_FIND(sd->achievement_data.incompleteCount, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id); // Look for the index again, the position most likely changed
}
clif_achievement_update(sd, &sd->achievement_data.achievements[i], sd->achievement_data.count - sd->achievement_data.incompleteCount);
sd->achievement_data.save = true; // Flag to save with the autosave interval
return true;
}
/**
* Get the reward of an achievement
* @param sd: Player getting the reward
* @param achievement_id: Achievement to get reward data
*/
void achievement_get_reward(struct map_session_data *sd, int achievement_id, time_t rewarded)
{
int i;
nullpo_retv(sd);
std::shared_ptr<s_achievement_db> adb = achievement_db.find( achievement_id );
if( adb == nullptr ){
ShowError( "achievement_reward: Inter server sent a reward claim for achievement %d not found in DB.\n", achievement_id );
return;
}
if (rewarded == 0) {
clif_achievement_reward_ack(sd->fd, 0, achievement_id);
return;
}
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i == sd->achievement_data.count)
return;
// Only update in the cache, db was updated already
sd->achievement_data.achievements[i].rewarded = rewarded;
sd->achievement_data.save = true;
run_script(adb->rewards.script, 0, sd->bl.id, fake_nd->bl.id);
if (adb->rewards.title_id) {
sd->titles.push_back(adb->rewards.title_id);
clif_achievement_list_all(sd);
}else{
clif_achievement_reward_ack(sd->fd, 1, achievement_id);
clif_achievement_update(sd, &sd->achievement_data.achievements[i], sd->achievement_data.count - sd->achievement_data.incompleteCount);
}
}
/**
* Check if player has recieved an achievement's reward
* @param sd: Player to get reward
* @param achievement_id: Achievement to get reward data
*/
void achievement_check_reward(struct map_session_data *sd, int achievement_id)
{
int i;
nullpo_retv(sd);
std::shared_ptr<s_achievement_db> adb = achievement_db.find( achievement_id );
if( adb == nullptr ){
ShowError( "achievement_reward: Trying to reward achievement %d not found in DB.\n", achievement_id );
clif_achievement_reward_ack( sd->fd, 0, achievement_id );
return;
}
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i == sd->achievement_data.count) {
clif_achievement_reward_ack(sd->fd, 0, achievement_id);
return;
}
if (sd->achievement_data.achievements[i].rewarded > 0 || sd->achievement_data.achievements[i].completed == 0) {
clif_achievement_reward_ack(sd->fd, 0, achievement_id);
return;
}
if (!intif_achievement_reward(sd, adb.get())) {
clif_achievement_reward_ack(sd->fd, 0, achievement_id);
}
}
/**
* Return all titles to a player based on completed achievements
* @param char_id: Character ID requesting
*/
void achievement_get_titles(uint32 char_id)
{
struct map_session_data *sd = map_charid2sd(char_id);
if (sd) {
sd->titles.clear();
if (sd->achievement_data.count) {
for (int i = 0; i < sd->achievement_data.count; i++) {
std::shared_ptr<s_achievement_db> adb = achievement_db.find( sd->achievement_data.achievements[i].achievement_id );
// If the achievement has a title and is complete, give it to the player
if( adb != nullptr && adb->rewards.title_id && sd->achievement_data.achievements[i].completed > 0 ){
sd->titles.push_back( adb->rewards.title_id );
}
}
}
}
}
/**
* Frees the player's data for achievements
* @param sd: Player's session
*/
void achievement_free(struct map_session_data *sd)
{
nullpo_retv(sd);
if (sd->achievement_data.count) {
aFree(sd->achievement_data.achievements);
sd->achievement_data.achievements = NULL;
sd->achievement_data.count = sd->achievement_data.incompleteCount = 0;
}
}
/**
* Get an achievement's progress information
* @param sd: Player to check achievement progress
* @param achievement_id: Achievement progress to check
* @param type: Type to return
* @return The type's data, -1 if player doesn't have achievement, -2 on failure/incorrect type
*/
int achievement_check_progress(struct map_session_data *sd, int achievement_id, int type)
{
int i;
nullpo_retr(-2, sd);
// Achievement ID is not needed so skip the lookup
if (type == ACHIEVEINFO_LEVEL)
return sd->achievement_data.level;
else if (type == ACHIEVEINFO_SCORE)
return sd->achievement_data.total_score;
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == achievement_id);
if (i == sd->achievement_data.count)
return -1;
if (type >= ACHIEVEINFO_COUNT1 && type <= ACHIEVEINFO_COUNT10)
return sd->achievement_data.achievements[i].count[type - 1];
else if (type == ACHIEVEINFO_COMPLETE)
return sd->achievement_data.achievements[i].completed > 0;
else if (type == ACHIEVEINFO_COMPLETEDATE)
return (int)sd->achievement_data.achievements[i].completed;
else if (type == ACHIEVEINFO_GOTREWARD)
return sd->achievement_data.achievements[i].rewarded > 0;
return -2;
}
/**
* Calculate a player's achievement level
* @param sd: Player to check achievement level
* @param flag: If the call should attempt to give the AG_GOAL_ACHIEVE achievement
* @return Rollover and TNL EXP or 0 on failure
*/
int *achievement_level(struct map_session_data *sd, bool flag)
{
nullpo_retr(nullptr, sd);
sd->achievement_data.total_score = 0;
for (int i = 0; i < sd->achievement_data.count; i++) { // Recount total score
if (sd->achievement_data.achievements[i].completed > 0)
sd->achievement_data.total_score += sd->achievement_data.achievements[i].score;
}
int left_score, right_score, old_level = sd->achievement_data.level;
for( sd->achievement_data.level = 0; /* Break condition's inside the loop */; sd->achievement_data.level++ ){
std::shared_ptr<s_achievement_level> level = achievement_level_db.find( sd->achievement_data.level );
if( sd->achievement_data.total_score > level->points ){
std::shared_ptr<s_achievement_level> next_level = achievement_level_db.find( sd->achievement_data.level + 1 );
// Check if there is another level
if( next_level == nullptr ){
std::shared_ptr<s_achievement_level> level = achievement_level_db.find( sd->achievement_data.level );
left_score = sd->achievement_data.total_score - level->points;
right_score = 0;
// Increase the level for client side display
sd->achievement_data.level++;
break;
}else{
// Enough points for this level, check the next one
continue;
}
}
if( sd->achievement_data.level == 0 ){
left_score = sd->achievement_data.total_score;
right_score = level->points;
break;
}else{
std::shared_ptr<s_achievement_level> previous_level = achievement_level_db.find( sd->achievement_data.level - 1 );
left_score = sd->achievement_data.total_score - previous_level->points;
right_score = level->points - previous_level->points;
break;
}
}
static int info[2];
info[0] = left_score; // Left number
info[1] = right_score; // Right number
if (flag && old_level != sd->achievement_data.level) { // Give AG_GOAL_ACHIEVE
achievement_update_objective( sd, AG_GOAL_ACHIEVE, 0 );
}
return info;
}
bool achievement_check_condition( struct script_code* condition, struct map_session_data* sd ){
// Save the old script the player was attached to
struct script_state* previous_st = sd->st;
// Only if there was an old script
if( previous_st != nullptr ){
// Detach the player from the current script
script_detach_rid(previous_st);
}
run_script( condition, 0, sd->bl.id, fake_nd->bl.id );
struct script_state* st = sd->st;
int value = 0;
if( st != nullptr ){
value = script_getnum( st, 2 );
script_free_state(st);
}
// If an old script is present
if( previous_st != nullptr ){
// Because of detach the RID will be removed, so we need to restore it
previous_st->rid = sd->bl.id;
// Reattach the player to it, so that the limitations of that script kick back in
script_attach_state( previous_st );
}
return value != 0;
}
/**
* Update achievement objectives.
* @param sd: Player to update
* @param ad: Achievement data to compare for completion
* @param group: Achievement group to update
* @param update_count: Objective values from event
* @return 1 on success and false on failure
*/
static bool achievement_update_objectives(struct map_session_data *sd, std::shared_ptr<struct s_achievement_db> ad, enum e_achievement_group group, const std::array<int, MAX_ACHIEVEMENT_OBJECTIVES> &update_count)
{
if (!ad || !sd)
return false;
if (group <= AG_NONE || group >= AG_MAX)
return false;
if (group != ad->group)
return false;
struct achievement *entry = NULL;
bool isNew = false, changed = false, complete = false;
std::array<int, MAX_ACHIEVEMENT_OBJECTIVES> current_count = {}; // Player's current objective values
int i;
ARR_FIND(0, sd->achievement_data.count, i, sd->achievement_data.achievements[i].achievement_id == ad->achievement_id);
if (i == sd->achievement_data.count) { // Achievement isn't in player's log
if (!achievement_check_dependent(sd, ad->achievement_id)) // Check to see if dependents are complete before adding to player's log
return false;
isNew = true;
} else {
entry = &sd->achievement_data.achievements[i];
if (entry->completed > 0) // Player has completed the achievement
return false;
memcpy(current_count.data(), entry->count, sizeof(current_count));
}
switch (group) {
case AG_ADD_FRIEND:
case AG_BABY:
case AG_CHAT_COUNT:
case AG_CHAT_CREATE:
case AG_CHAT_DYING:
case AG_GET_ITEM:
case AG_GET_ZENY:
case AG_GOAL_LEVEL:
case AG_GOAL_STATUS:
case AG_JOB_CHANGE:
case AG_MARRY:
case AG_PARTY:
case AG_REFINE_FAIL:
case AG_REFINE_SUCCESS:
if (!ad->condition)
return false;
if (!achievement_check_condition(ad->condition, sd)) // Parameters weren't met
return false;
changed = true;
complete = true;
break;
case AG_SPEND_ZENY:
//case AG_CHAT: // No information on trigger events
if (ad->targets.empty() || !ad->condition)
return false;
//if (group == AG_CHAT) {
// if (ad->mapindex > -1 && sd->bl.m != ad->mapindex)
// return false;
//}
for (const auto &it : ad->targets) {
if (current_count[it.first] < it.second->count)
current_count[it.first] += update_count[it.first];
}
if (!achievement_check_condition(ad->condition, sd)) // Parameters weren't met
return false;
changed = true;
if (std::find_if(ad->targets.begin(), ad->targets.end(),
[current_count](const std::pair<uint16, std::shared_ptr<achievement_target>> &target) -> bool {
return current_count[target.first] < target.second->count;
}
) == ad->targets.end())
complete = true;
break;
case AG_BATTLE:
case AG_TAMING:
if (ad->targets.empty())
return false;
for (const auto &it : ad->targets) {
if (it.second->mob == update_count[0] && current_count[it.first] < it.second->count) { // Here update_count[0] contains the killed/tamed monster ID
current_count[it.first]++;
changed = true;
}
}
if (!changed)
return false;
if (std::find_if(ad->targets.begin(), ad->targets.end(),
[current_count](const std::pair<uint16, std::shared_ptr<achievement_target>> &target) -> bool {
return current_count[target.first] < target.second->count;
}
) == ad->targets.end())
complete = true;
break;
}
if( isNew ){
// Always add the achievement if it was completed
bool hasCounter = complete;
// If it was not completed
if( !hasCounter ){
// Check if it has a counter
for( int counter : current_count ){
if( counter != 0 ){
hasCounter = true;
break;
}
}
}
if( hasCounter ){
if( !( entry = achievement_add( sd, ad->achievement_id ) ) ){
return false; // Failed to add achievement
}
}else{
changed = false;
}
}
if (changed) {
memcpy(entry->count, current_count.data(), sizeof(current_count));
achievement_update_achievement(sd, ad->achievement_id, complete);
}
return true;
}
/**
* Update achievement objective count.
* @param sd: Player data
* @param group: Achievement enum type
* @param sp_value: SP parameter value
* @param arg_count: va_arg count
*/
void achievement_update_objective(struct map_session_data *sd, enum e_achievement_group group, uint8 arg_count, ...)
{
if (!battle_config.feature_achievement)
return;
if (sd) {
va_list ap;
std::array<int, MAX_ACHIEVEMENT_OBJECTIVES> count = {};
va_start(ap, arg_count);
for (int i = 0; i < arg_count; i++){
std::string name = "ARG" + std::to_string(i);
count[i] = va_arg(ap, int);
pc_setglobalreg( sd, add_str( name.c_str() ), (int)count[i] );
}
va_end(ap);
switch(group) {
case AG_CHAT: //! TODO: Not sure how this works officially
// These have no objective use.
break;
default:
for (auto &ach : achievement_db)
achievement_update_objectives(sd, ach.second, group, count);
break;
}
// Remove variables that might have been set
for (int i = 0; i < arg_count; i++){
std::string name = "ARG" + std::to_string(i);
pc_setglobalreg( sd, add_str( name.c_str() ), 0 );
}
}
}
/**
* Loads achievements from the achievement db.
*/
void achievement_read_db(void)
{
achievement_db.load();
for (auto &achit : achievement_db) {
const auto ach = achit.second;
for (int i = 0; i < ach->dependent_ids.size(); i++) {
if (!achievement_db.exists(ach->dependent_ids[i])) {
ShowWarning("achievement_read_db: An invalid Dependent ID %d was given for Achievement %d. Removing from list.\n", ach->dependent_ids[i], ach->achievement_id);
ach->dependent_ids.erase(ach->dependent_ids.begin() + i);
}
}
}
achievement_level_db.load();
}
/**
* Reloads the achievement database
*/
void achievement_db_reload(void)
{
if (!battle_config.feature_achievement)
return;
do_final_achievement();
do_init_achievement();
}
/**
* Initializes the achievement database
*/
void do_init_achievement(void)
{
if (!battle_config.feature_achievement)
return;
achievement_read_db();
}
/**
* Finalizes the achievement database
*/
void do_final_achievement(void){
achievement_db.clear();
achievement_level_db.clear();
}
/**
* Achievement constructor
*/
s_achievement_db::s_achievement_db()
: achievement_id(0)
, name("")
, group()
, targets()
, dependent_ids()
, condition(nullptr)
, mapindex(0)
, rewards()
, score(0)
, has_dependent(0)
{}
/**
* Achievement deconstructor
*/
s_achievement_db::~s_achievement_db()
{
if (condition)
script_free_code(condition);
}
/**
* Achievement reward constructor
*/
s_achievement_db::ach_reward::ach_reward()
: nameid(0)
, amount(0)
, script(nullptr)
, title_id(0)
{}
/**
* Achievement reward deconstructor
*/
s_achievement_db::ach_reward::~ach_reward()
{
if (script)
script_free_code(script);
}
|
gpl-3.0
|
596acres/django-livinglots-template
|
project_name/project_name/wsgi.py
|
848
|
"""
WSGI config for {{ project_name }}.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.local")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/bitrix/modules/forum/install/components/bitrix/forum.message.send/lang/en/component.php
|
61
|
Bitrix 16.5 Business Demo = 5ea153a89857e1baf331a86f985ad877
|
gpl-3.0
|
Moliholy/4-In-A-Row-JADE
|
src/multiagentes/jade/cuatroenraya/Player.java
|
14156
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package multiagentes.jade.cuatroenraya;
import cuatroenraya.OntologiaCuatroEnRaya;
import cuatroenraya.elementos.Ficha;
import cuatroenraya.elementos.Ganador;
import cuatroenraya.elementos.Jugador;
import cuatroenraya.elementos.Jugar;
import cuatroenraya.elementos.Movimiento;
import cuatroenraya.elementos.MovimientoRealizado;
import cuatroenraya.elementos.Posicion;
import cuatroenraya.elementos.PosicionarFicha;
import jade.content.ContentElement;
import jade.content.ContentManager;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.BeanOntologyException;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.onto.UngroundedException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.RefuseException;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.AchieveREResponder;
import jade.proto.ContractNetResponder;
import java.util.HashMap;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import multiagentes.jade.utils.AgentHelper;
/**
*
* @author Molina
*/
public class Player extends Agent {
public static final String SERVICE_NAME = "player";
public static final String SERVICE_TYPE = "4EnRayaPlayer";
protected HashMap<AID, Board> boards;//almacenamos las partidas con clave el AID del agent tablero
protected int wins;
protected int draws;
protected int loses;
protected Codec codec;
protected ContentManager manager;
/**
* Calls the AI to make a movement
*
* @param board game status' representation
* @return the movement to be made expressed as an integer
*/
protected int play(Board board) throws Exception {
int maxColumn = Board.COLUMNS;
int result = -1;
Random random = new Random();
do {
result = board.doMovement(random.nextInt(maxColumn), SquareStatus.FRIENDLY);
} while (result <= -1);
return result;
}
/**
* Revome the existing connection with the finished game
*
* @param game the game to be removed
*/
protected void finishGame(AID game) {
boards.remove(game);
}
/**
*
* @return the number of winned games
*/
public int getWins() {
return wins;
}
/**
*
* @return the number of drawed games
*/
public int getDraws() {
return draws;
}
/**
*
* @return the number of lost games
*/
public int getLoses() {
return loses;
}
/**
*
* @return the total number of games played
*/
public int getPlayerGames() {
return wins + loses + draws;
}
@Override
protected void setup() {
super.setup();
wins = draws = loses = 0;
codec = new SLCodec();
boards = new HashMap<>();
Ontology ontology = null;
try {
ontology = OntologiaCuatroEnRaya.getInstance();
} catch (BeanOntologyException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
}
manager = getContentManager();
manager.registerLanguage(codec);
manager.registerOntology(ontology);
try {
AgentHelper.registerYellowPages(this, SERVICE_NAME, SERVICE_TYPE,
OntologiaCuatroEnRaya.ONTOLOGY_NAME, FIPANames.ContentLanguage.FIPA_SL);
} catch (FIPAException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
}
AgentHelper.log(this, "Connected and successfully registered in yellow pages");
MessageTemplate template = MessageTemplate.and(
MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET),
MessageTemplate.MatchPerformative(ACLMessage.CFP));
//adding behaviours
addBehaviour(new ListenToEndGameNotification(this));
addBehaviour(new ManageGameEvents(this, template));
}
/**
* Sends an action to a game
*
* @param game the game as a message's receiver
* @param content the message to be sent
*/
protected void sendAction(AID game, String content) {
AgentHelper.sendMessage(this, game, ACLMessage.INFORM, content);
}
/////////////////////////////////////////////////////////////////
//////////////////////////Extra Classes//////////////////////////
/////////////////////////////////////////////////////////////////
/**
* Esta clase se encarga de manejar todos los mensajes que se intercambian
* entre el tablero y el jugador. Aquellos eventos de relevancia son
* tratados convenientemente actualizando los atributos del jugador.
*/
protected class ManageGameEvents extends ContractNetResponder {
public ManageGameEvents(Agent a, MessageTemplate mt) {
super(a, mt);
}
@Override
protected ACLMessage handleCfp(ACLMessage cfp) throws RefuseException, FailureException, NotUnderstoodException {
//ha recibido un call for propose. Vamos, que el tablero le informa de que está disponible
//el jugador SIEMPRE va a aceptar todas las solicitudes de los tableros mediante un PROPOSE
ACLMessage propose = cfp.createReply();
try {
Action action = (Action) manager.extractContent(cfp);
Jugar jugar = (Jugar) action.getAction();
Jugador jugador = new Jugador();
jugador.setJugador(getAID());
jugar.setOponente(jugador);
//Rellenamos el campo oponente con el agente
//que acepta la propuesta de juego
action.setAction(jugar); //La incluimos en la acción
manager.fillContent(propose, action); // Y en el mensaje
} catch (Codec.CodecException | OntologyException ex) {
ex.printStackTrace();
}
//mandamos finalmente el mensaje al tablero proponiéndole jugar
propose.setPerformative(ACLMessage.PROPOSE);
return propose;
}
@Override
protected ACLMessage handleAcceptProposal(ACLMessage cfp, ACLMessage propose, ACLMessage accept) throws FailureException {
ACLMessage inform = accept.createReply();
inform.setPerformative(ACLMessage.INFORM);
//ponemos como AID identificativa la del tablero con el que vamos a jugar
AID tablero = accept.getSender();
try {
Action action = (Action) manager.extractContent(accept);
Jugar jugar = (Jugar) action.getAction();
System.out.println("El oponente del agente: " + getLocalName() + " es el agente: " + jugar.getOponente().getJugador().getLocalName());
//añadimos al jugador a la lista de partidas que almacena la clase
boards.put(tablero, new Board());
//Informamos que estamos conformes en realizar la acción
manager.fillContent(inform, action);
} catch (Codec.CodecException | OntologyException ex) {
ex.printStackTrace();
}
//creamos el mensaje de filtro y de primer envío
MessageTemplate template = MessageTemplate.and(
MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST),
MessageTemplate.MatchPerformative(ACLMessage.REQUEST));
//añadimos el comportamiento de recepción de mensajes REQUEST de estado del juego
addBehaviour(new ListenToGameMovements(myAgent, template));
AgentHelper.log(myAgent, "Comportamiento de recepción de movimientos añadido");
//enviamos finalmente el mensaje de aceptación de juego
return inform;
}
@Override
protected void handleRejectProposal(ACLMessage cfp, ACLMessage propose, ACLMessage reject) {
super.handleRejectProposal(cfp, propose, reject);
//esto no puede pasar, pero por si acaso
System.out.println("El juego " + getLocalName() + ": Proposición rechazada");
}
}
protected class ListenToGameMovements extends AchieveREResponder {
public ListenToGameMovements(Agent a, MessageTemplate mt) {
super(a, mt);
}
@Override
protected ACLMessage prepareResponse(ACLMessage request) throws NotUnderstoodException, RefuseException {
AgentHelper.log(myAgent, "Entrando en el prepareResponse y mandando un AGREE");
ACLMessage agree = request.createReply();
agree.setPerformative(ACLMessage.AGREE);
return agree;
}
@Override
protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) throws FailureException {
AgentHelper.log(myAgent, "Entrando en el prepareResultNotification y mandando un INFORM con el contenido de la jugada que se va a realizar");
//TODO hacer la jugada
try {
//nos llega un mensaje con la actualización del tablero.
//tenemos que tratarlo convenientemente y enviar la respuesta al tablero.
ACLMessage toSendBack = request.createReply();
toSendBack.setPerformative(ACLMessage.INFORM);
//gestionamos el movimiento que hay que hacer y rellenamos el mensaje con el contenido apropiado
Action contenidoMensaje = (Action)manager.extractContent(request);
PosicionarFicha pf = (PosicionarFicha) contenidoMensaje.getAction();
Movimiento mov = pf.getAnterior();
int colorFichaRecibido = mov.getFicha().getColor();
int miColorFicha = OntologiaCuatroEnRaya.FICHA_AZUL; //ponemos esta por defecto, por si acaso
switch (colorFichaRecibido) {
case OntologiaCuatroEnRaya.LIBRE:
//estamos en el primer movimiento
miColorFicha = OntologiaCuatroEnRaya.FICHA_ROJA;
break;
case OntologiaCuatroEnRaya.FICHA_AZUL:
miColorFicha = OntologiaCuatroEnRaya.FICHA_ROJA;
break;
case OntologiaCuatroEnRaya.FICHA_ROJA:
miColorFicha = OntologiaCuatroEnRaya.FICHA_AZUL;
break;
}
Ficha ficha = new Ficha(miColorFicha);
Board board = boards.get(request.getSender());
int movement = play(board);
int row = movement / Board.COLUMNS;
int column = movement % Board.COLUMNS;
Movimiento movToSend = new Movimiento(ficha, new Posicion(row, column));
Jugador yoMismo = new Jugador(getAID(), ficha);
MovimientoRealizado mrToSend = new MovimientoRealizado(yoMismo, movToSend);
manager.fillContent(toSendBack, mrToSend);
//finalmente enviamos el mensaje de vuelta al tablero para que evalue nuestro movimiento
return toSendBack;
} catch (Codec.CodecException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
} catch (UngroundedException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
} catch (OntologyException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
protected class ListenToEndGameNotification extends CyclicBehaviour {
public ListenToEndGameNotification(Agent a) {
super(a);
}
@Override
public void action() {
//está pendiente de escuchar notificaciones de final de juego del tablero
//una vez recibida ajustará los atributos convenientemente y buscará de nuevo un tablero
ACLMessage msg = receive(MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE));
if (msg != null) {
try {
System.out.println("\nJUEGO TERMINADO");
System.out.println(msg);
Ganador ganador = (Ganador) getContentManager().extractContent(msg);
Jugador winner = ganador.getJugador();
if (winner != null) { //no ha sido empate
if (winner.getJugador().getName().equals(getAID().getName())) {
wins++;
} else {
loses++;
}
} else { //ha sido empate
draws++;
}
finishGame(msg.getSender());
//y ahora simplemente sigue recibiendo solicitudes de partidas
} catch (Codec.CodecException | OntologyException e) {
e.printStackTrace();
}
} else {
block();
}
}
}
}
|
gpl-3.0
|
Mapleroid/cm-server
|
server-5.11.0.src/com/cloudera/server/web/cmf/bdr2/ReplicationsBaseImpl.java
|
9049
|
package com.cloudera.server.web.cmf.bdr2;
import com.cloudera.server.web.common.I18n;
import java.io.IOException;
import java.io.Writer;
import org.jamon.AbstractTemplateImpl;
import org.jamon.TemplateManager;
import org.jamon.emit.StandardEmitter;
import org.jamon.escaping.Escaping;
public abstract class ReplicationsBaseImpl extends AbstractTemplateImpl
implements ReplicationsBase.Intf
{
protected static ReplicationsBase.ImplData __jamon_setOptionalArguments(ReplicationsBase.ImplData p_implData)
{
return p_implData;
}
public ReplicationsBaseImpl(TemplateManager p_templateManager, ReplicationsBase.ImplData p_implData) {
super(p_templateManager, __jamon_setOptionalArguments(p_implData));
}
public void renderNoFlush(Writer jamonWriter)
throws IOException
{
jamonWriter.write("<script type=\"text/html\" id=\"template-service-reference-multiline\">\n <span class=\"service-name\" data-bind=\"text: serviceDisplayName\"></span>\n <br>\n <span class=\"clustername\" data-bind=\"text: clusterDisplayName\"></span>\n <!-- ko if: $data.peerName -->\n @ <span class=\"peername\" data-bind=\"text: peerName\"></span>\n <!-- /ko -->\n</script>\n\n<script id=\"template-format-dry-run-label\" type=\"text/html\">\n <span class=\"dry-run-label\" data-bind=\"visible: isDryRun\" style=\"display:none\">\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.replication.dryRun")), jamonWriter);
jamonWriter.write("\n </span>\n</script>\n\n\n<script type=\"text/html\" id=\"template-objects-description\">\n\n <!-- ko with: $data.hdfsArguments -->\n <br>\n <span class=\"field-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.from")), jamonWriter);
jamonWriter.write(":</span>\n <span data-bind=\"formattedPath: sourcePath, format: 'full'\" aria-label=\"");
Escaping.STRICT_HTML.write(StandardEmitter.valueOf(I18n.t("label.source")), jamonWriter);
jamonWriter.write("\"></span>\n <span> </span>\n <span class=\"field-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.to")), jamonWriter);
jamonWriter.write(":</span>\n <span data-bind=\"formattedPath: destinationPath, format: 'full'\" aria-label=\"");
Escaping.STRICT_HTML.write(StandardEmitter.valueOf(I18n.t("label.destination")), jamonWriter);
jamonWriter.write("\"></span>\n <!-- /ko-->\n\n <!-- ko with: $data.hiveArguments -->\n <br>\n <span class=\"field-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.objects")), jamonWriter);
jamonWriter.write(": </span>\n <span data-bind=\"if: $data.tableFilters().length > 0\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.customDatabases")), jamonWriter);
jamonWriter.write("</span>\n <span data-bind=\"if: $data.tableFilters().length === 0\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.replication.allDatabases")), jamonWriter);
jamonWriter.write("</span>\n <!-- ko if: ko.unwrap($data.cloudRootPath) -->\n <span> </span>\n <span class=\"field-label\" data-bind=\"if: ko.unwrap($data.sourceAccount)\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.from")), jamonWriter);
jamonWriter.write(":</span>\n <span class=\"field-label\" data-bind=\"if: ko.unwrap($data.destinationAccount)\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.to")), jamonWriter);
jamonWriter.write(":</span>\n <span data-bind=\"text: $data.cloudRootPath\"></span>\n <!-- /ko-->\n <!-- /ko-->\n\n</script>\n\n<script type=\"text/html\" id=\"template-hdfs-objects-tooltip-content\">\n <h4>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.paths")), jamonWriter);
jamonWriter.write("</h4>\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.source")), jamonWriter);
jamonWriter.write(": <span data-bind=\"text: sourcePath\"></span><br>\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.destination")), jamonWriter);
jamonWriter.write(": <span data-bind=\"text: destinationPath\"></span><br>\n</script>\n\n<script type=\"text/html\" id=\"template-hive-objects-tooltip-content\">\n <h4>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.tables")), jamonWriter);
jamonWriter.write("</h4>\n <span data-bind=\"foreach: $data.tableFilters\">\n <span data-bind=\"text: database\"></span>:<span data-bind=\"text: tableName\"></span><br>\n </span>\n</script>\n\n<script type=\"text/html\" id=\"template-nextrun-cell\">\n <!-- ko if: paused-->\n <i class=\"glyphicon small calendar muted\" aria-hidden=\"true\"></i>\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.state.disabled")), jamonWriter);
jamonWriter.write("\n <!-- /ko -->\n <!-- ko ifnot: paused -->\n <span class=\"nextrun-tooltip-container tooltip-trigger nowrap\">\n <!-- ko if: nextRun -->\n <span data-bind=\"tooltip: {\n titleTemplate: 'template-nextrun-tooltip-content',\n titleCssClass: 'nextrun-tooltip',\n placement: 'bottom',\n container: '#' + ");
__jamon_innerUnit__generateIdFromSchedule(jamonWriter, __jamon__get_Method_Opt_data_default());
jamonWriter.write(" + ' .nextrun-tooltip-container'\n }\">\n <i class=\"glyphicon small calendar\" aria-hidden=\"true\"></i>\n <span data-bind=\"formattedDate: nextRun, formattedDateMethod: 'humanizeDateShort'\"></span>\n </span>\n <!-- /ko -->\n <!-- ko ifnot: nextRun -->\n <span data-bind=\"tooltip: {\n titleTemplate: 'template-nextrun-tooltip-content',\n titleCssClass: 'nextrun-tooltip',\n placement: 'bottom',\n container: '#' + ");
__jamon_innerUnit__generateIdFromSchedule(jamonWriter, __jamon__get_Method_Opt_data_default());
jamonWriter.write(" + ' .nextrun-tooltip-container'\n }\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("message.replication.noneScheduled")), jamonWriter);
jamonWriter.write("</span>\n <!-- /ko -->\n </span>\n <!-- /ko -->\n</script>\n\n<script type=\"text/html\" id=\"template-nextrun-tooltip-content\">\n <h4>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.replication.schedulingInfo")), jamonWriter);
jamonWriter.write("</h4>\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.runsFrom")), jamonWriter);
jamonWriter.write(": <span data-bind=\"formattedDate: startTime\"></span><br>\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.repeats")), jamonWriter);
jamonWriter.write(": <span data-bind=\"text: formattedPeriodicity\"></span><br>\n <!-- ko if: endTime -->\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.runsUntil")), jamonWriter);
jamonWriter.write(": <span data-bind=\"formattedDate: endTime\"></span><br>\n <!-- /ko -->\n <!-- ko if: nextRun -->\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.nextRun")), jamonWriter);
jamonWriter.write(": <span data-bind=\"formattedDate: nextRun\"></span><br>\n <!-- /ko -->\n</script>\n\n<script type=\"text/html\" id=\"tmpl-icon-lastrun-result\">\n <!-- ko if: success -->\n <i class=\"glyphicon tiny success ok_2\" title=\"");
Escaping.STRICT_HTML.write(StandardEmitter.valueOf(I18n.t("label.successful")), jamonWriter);
jamonWriter.write("\"></i>\n <!-- /ko -->\n <!-- ko if: !success() -->\n <i class=\"glyphicon tiny error remove\" title=\"");
Escaping.STRICT_HTML.write(StandardEmitter.valueOf(I18n.t("label.failed")), jamonWriter);
jamonWriter.write("\"></i>\n <!-- /ko -->\n</script>\n\n<script type=\"text/html\" id=\"template-replication-command-progress\">\n <!-- ko with: $data.result -->\n <div class=\"usage\" data-bind=\"if: $data.progress\">\n <span class=\"usage-reading\" data-bind=\"text: progress.displayString\"></span>\n <span class=\"usage-bar usage-low\" data-bind=\"style: {width: progress.percent}\"></span>\n <span class=\"usage-bar-rest\"></span>\n </div>\n <!-- /ko -->\n</script>\n\n\n");
child_render_1(jamonWriter);
jamonWriter.write("\n");
}
protected abstract void child_render_1(Writer paramWriter)
throws IOException;
protected void __jamon_innerUnit__generateIdFromSchedule(Writer jamonWriter, String data)
throws IOException
{
jamonWriter.write("'schedule-id-'+ ");
Escaping.HTML.write(StandardEmitter.valueOf(data), jamonWriter);
jamonWriter.write(".id()\n");
}
protected String __jamon__get_Method_Opt_data_default()
{
return "$data";
}
}
|
gpl-3.0
|
Alberto-Beralix/Beralix
|
i386-squashfs-root/usr/share/pyshared/orca/scripts/apps/planner/script.py
|
1875
|
# Orca
#
# Copyright 2006-2008 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
"""Custom script for planner."""
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2006-2008 Sun Microsystems Inc."
__license__ = "LGPL"
import orca.scripts.default as default
from braille_generator import BrailleGenerator
from speech_generator import SpeechGenerator
########################################################################
# #
# The planner script class. #
# #
########################################################################
class Script(default.Script):
def __init__(self, app):
"""Creates a new script for the given application.
Arguments:
- app: the application to create a script for.
"""
default.Script.__init__(self, app)
def getBrailleGenerator(self):
return BrailleGenerator(self)
def getSpeechGenerator(self):
return SpeechGenerator(self)
|
gpl-3.0
|
ILogre/ToyExample
|
src/equation/Complex.java
|
502
|
package equation;
/**
* Created by ivan on 15/09/2014.
*/
public class Complex extends Expression{
private Expression left;
private Operator op;
private Expression right;
public Complex(Expression left, Operator op, Expression right) {
super();
this.left = left;
this.op = op;
this.right = right;
}
@Override
public String toString() {
return "( " + left.toString() + " " + op.toString()+ " " + right.toString() + " )";
}
}
|
gpl-3.0
|
chanzler/piwik-performance-monitor
|
Menu.php
|
630
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\PerformanceMonitor;
use Piwik\Menu\MenuTop;
use Piwik\Piwik;
class Menu extends \Piwik\Plugin\Menu
{
public function configureTopMenu(MenuTop $menu)
{
$urlParams = array('module' => 'PerformanceMonitor', 'action' => 'summary', 'segment' => false);
$tooltip = Piwik::translate('PerformanceMonitor_TopLinkTooltip');
$menu->add('PerformanceMonitor_PerformanceSummary', null, $urlParams, true, 3, $tooltip);
}
}
|
gpl-3.0
|
sozemego/multilife
|
server/src/main/java/soze/multilife/messages/incoming/IncomingMessageConverter.java
|
2574
|
package soze.multilife.messages.incoming;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Optional;
public class IncomingMessageConverter {
private static final PingMessage PING_MESSAGE = new PingMessage();
public static Optional<IncomingMessage> convert(byte[] payload) {
if (payload.length == 0) {
throw new IllegalArgumentException("Outgoing byte array message cannot have 0 length.");
}
final byte firstByte = payload[0];
try {
switch (firstByte) {
case 1:
return Optional.of(convertClickMessage(payload));
case 3:
return Optional.of(convertPingMessage(payload));
}
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
return Optional.empty();
}
private static ClickMessage convertClickMessage(byte[] payload) {
ClickMessage message = new ClickMessage();
int[] indices = convertPayloadToIntArray(getByteArrayWithoutTypeMarker(payload, 4));
message.setIndices(indices);
return message;
}
private static int[] convertPayloadToIntArray(byte[] payload) {
int intNumber = payload.length / 4;
int[] integers = new int[intNumber];
ByteBuffer buffer = ByteBuffer.wrap(reverseArray(payload));
for (int i = 0; i < integers.length; i++) {
int index = buffer.getInt();
integers[i] = index;
}
return integers;
}
private static String getString(byte[] payload) {
try {
return new String(payload, "UTF-16");
} catch (UnsupportedEncodingException e) {
}
throw new IllegalStateException("Invalid payload");
}
private static String getString(byte[] payload, int start, int length) {
byte[] strArray = copyArray(payload, start, length);
return getString(strArray);
}
private static byte[] getByteArrayWithoutTypeMarker(byte[] payload, int markerLength) {
byte[] message = new byte[payload.length - markerLength];
System.arraycopy(payload, markerLength, message, 0, payload.length - markerLength);
return message;
}
private static byte[] copyArray(byte[] from, int srcPos, int length) {
byte[] to = new byte[length];
System.arraycopy(from, srcPos, to, 0, length);
return to;
}
private static byte[] reverseArray(byte[] arr) {
byte[] result = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
result[arr.length - i - 1] = arr[i];
}
return result;
}
private static PingMessage convertPingMessage(byte[] payload) {
return PING_MESSAGE;
}
}
|
gpl-3.0
|
devbridge/BetterCMS
|
Modules/BetterCms.Module.Api.Abstractions/Operations/Pages/Sitemaps/Sitemap/Tree/SitemapTreeNodeModel.cs
|
4397
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SitemapTreeNodeModel.cs" company="Devbridge Group LLC">
//
// Copyright (C) 2015,2016 Devbridge Group LLC
//
// 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.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//
// <summary>
// Better CMS is a publishing focused and developer friendly .NET open source CMS.
//
// Website: https://www.bettercms.com
// GitHub: https://github.com/devbridge/bettercms
// Email: info@bettercms.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using BetterCms.Module.Api.Infrastructure;
using BetterCms.Module.Api.Infrastructure.Attributes;
namespace BetterCms.Module.Api.Operations.Pages.Sitemaps.Sitemap.Tree
{
[Serializable]
[DataContract]
public class SitemapTreeNodeModel : ModelBase
{
/// <summary>
/// Gets or sets the parent node id.
/// </summary>
/// <value>
/// The parent node id.
/// </value>
[DataMember]
public Guid? ParentId { get; set; }
/// <summary>
/// Gets or sets the node title.
/// </summary>
/// <value>
/// The node title.
/// </value>
[DataMember]
public string Title { get; set; }
/// <summary>
/// Gets or sets the node URL.
/// </summary>
/// <value>
/// The node URL.
/// </value>
[DataMember]
public string Url { get; set; }
/// <summary>
/// Gets or sets the page identifier.
/// </summary>
/// <value>
/// The page identifier.
/// </value>
[DataMember]
public Guid? PageId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether page is published.
/// </summary>
/// <value>
/// <c>true</c> if page is published; otherwise, <c>false</c>.
/// </value>
[DataMember]
public bool PageIsPublished { get; set; }
/// <summary>
/// Gets or sets the page language identifier.
/// </summary>
/// <value>
/// The page language identifier.
/// </value>
[DataMember]
public Guid? PageLanguageId { get; set; }
/// <summary>
/// Gets or sets the node display order.
/// </summary>
/// <value>
/// The node display order.
/// </value>
[DataMember]
public int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets the children nodes.
/// </summary>
/// <value>
/// The children nodes.
/// </value>
[DataMember]
public IList<SitemapTreeNodeModel> ChildrenNodes { get; set; }
/// <summary>
/// Gets or sets the translations.
/// </summary>
/// <value>
/// The translations.
/// </value>
[DataMember]
public IList<SitemapTreeNodeTranslationModel> Translations { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use page title as node title.
/// </summary>
/// <value>
/// <c>true</c> if to use page title as node title; otherwise, <c>false</c>.
/// </value>
[DataMemberIgnore]
public bool UsePageTitleAsNodeTitle { get; set; }
/// <summary>
/// Gets or sets the macro.
/// </summary>
/// <value>
/// The macro.
/// </value>
[DataMember]
public string Macro { get; set; }
}
}
|
gpl-3.0
|
lawl-dev/Kiwi
|
src/Kiwi.Lexer/Properties/AssemblyInfo.cs
|
1473
|
using System.Reflection;
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("Kiwi.Lexer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Kiwi.Lexer")]
[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("87fae805-1868-467e-9c1f-5e0cdce8a284")]
// 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
|
droidefense/engine
|
mods/simplemagic/src/main/java/com/j256/simplemagic/logger/Logger.java
|
19636
|
package com.j256.simplemagic.logger;
import com.j256.simplemagic.logger.Log.Level;
/**
* Class which wraps our {@link Log} interface and provides {} argument features like slf4j. It allows us to plug in
* additional log systems if necessary.
* <p>
* <p>
* <b>NOTE:</b> We do the (msg, arg0), (msg, arg0, arg1), (msg, arg0, arg1, arg2), and (msg, argArray) patterns because
* if we do ... for everything, we will get a new Object[] each log call which we don't want -- even if the message is
* never logged because of the log level. Also, we don't use ... at all because we want to know <i>when</i> we are
* creating a new Object[] so we can make sure it is what we want. I thought ... was so much better than slf4j but it
* turns out they were spot on. Sigh.
* </p>
* <p>
* <p>
* <b>NOTE:</b> When you are using the argArray methods, you should consider wrapping the call in an {@code if} so the
* {@code Object[]} won't be created unnecessarily.
* </p>
* <p>
* <pre>
* if (logger.isLevelEnabled(Level...)) ...
* </pre>
*
* @author graywatson
*/
public class Logger {
private final static String ARG_STRING = "{}";
private final static Object UNKNOWN_ARG = new Object();
private final static int DEFAULT_FULL_MESSAGE_LENGTH = 128;
private final Log log;
public Logger(Log log) {
this.log = log;
}
/**
* Return if logging level is enabled.
*/
public boolean isLevelEnabled(Level level) {
return log.isLevelEnabled(level);
}
/**
* Log a trace message.
*/
public void trace(String msg) {
logIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a trace message.
*/
public void trace(String msg, Object arg0) {
logIfEnabled(Level.TRACE, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a trace message.
*/
public void trace(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.TRACE, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a trace message.
*/
public void trace(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.TRACE, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a trace message.
*/
public void trace(String msg, Object[] argArray) {
logIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a trace message with a throwable.
*/
public void trace(Throwable throwable, String msg) {
logIfEnabled(Level.TRACE, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a trace message with a throwable.
*/
public void trace(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.TRACE, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a trace message with a throwable.
*/
public void trace(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.TRACE, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a trace message with a throwable.
*/
public void trace(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.TRACE, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a trace message with a throwable.
*/
public void trace(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.TRACE, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a debug message.
*/
public void debug(String msg) {
logIfEnabled(Level.DEBUG, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a debug message.
*/
public void debug(String msg, Object arg0) {
logIfEnabled(Level.DEBUG, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a debug message.
*/
public void debug(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.DEBUG, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a debug message.
*/
public void debug(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.DEBUG, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a debug message.
*/
public void debug(String msg, Object[] argArray) {
logIfEnabled(Level.DEBUG, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a debug message with a throwable.
*/
public void debug(Throwable throwable, String msg) {
logIfEnabled(Level.DEBUG, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a debug message with a throwable.
*/
public void debug(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.DEBUG, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a debug message with a throwable.
*/
public void debug(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.DEBUG, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a debug message with a throwable.
*/
public void debug(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.DEBUG, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a debug message with a throwable.
*/
public void debug(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.DEBUG, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a info message.
*/
public void info(String msg) {
logIfEnabled(Level.INFO, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a info message.
*/
public void info(String msg, Object arg0) {
logIfEnabled(Level.INFO, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a info message.
*/
public void info(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.INFO, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a info message.
*/
public void info(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.INFO, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a info message.
*/
public void info(String msg, Object[] argArray) {
logIfEnabled(Level.INFO, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a info message with a throwable.
*/
public void info(Throwable throwable, String msg) {
logIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a info message with a throwable.
*/
public void info(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.INFO, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a info message with a throwable.
*/
public void info(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.INFO, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a info message with a throwable.
*/
public void info(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.INFO, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a info message with a throwable.
*/
public void info(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a warning message.
*/
public void warn(String msg) {
logIfEnabled(Level.WARNING, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a warning message.
*/
public void warn(String msg, Object arg0) {
logIfEnabled(Level.WARNING, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a warning message.
*/
public void warn(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.WARNING, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a warning message.
*/
public void warn(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.WARNING, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a warning message.
*/
public void warn(String msg, Object[] argArray) {
logIfEnabled(Level.WARNING, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a warning message with a throwable.
*/
public void warn(Throwable throwable, String msg) {
logIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a warning message with a throwable.
*/
public void warn(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.WARNING, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a warning message with a throwable.
*/
public void warn(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.WARNING, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a warning message with a throwable.
*/
public void warn(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.WARNING, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a warning message with a throwable.
*/
public void warn(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a error message.
*/
public void error(String msg) {
logIfEnabled(Level.ERROR, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a error message.
*/
public void error(String msg, Object arg0) {
logIfEnabled(Level.ERROR, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a error message.
*/
public void error(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.ERROR, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a error message.
*/
public void error(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.ERROR, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a error message.
*/
public void error(String msg, Object[] argArray) {
logIfEnabled(Level.ERROR, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a error message with a throwable.
*/
public void error(Throwable throwable, String msg) {
logIfEnabled(Level.ERROR, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a error message with a throwable.
*/
public void error(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.ERROR, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a error message with a throwable.
*/
public void error(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.ERROR, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a error message with a throwable.
*/
public void error(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.ERROR, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a error message with a throwable.
*/
public void error(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.ERROR, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a fatal message.
*/
public void fatal(String msg) {
logIfEnabled(Level.FATAL, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a fatal message.
*/
public void fatal(String msg, Object arg0) {
logIfEnabled(Level.FATAL, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a fatal message.
*/
public void fatal(String msg, Object arg0, Object arg1) {
logIfEnabled(Level.FATAL, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a fatal message.
*/
public void fatal(String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.FATAL, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a fatal message.
*/
public void fatal(String msg, Object[] argArray) {
logIfEnabled(Level.FATAL, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a fatal message with a throwable.
*/
public void fatal(Throwable throwable, String msg) {
logIfEnabled(Level.FATAL, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a fatal message with a throwable.
*/
public void fatal(Throwable throwable, String msg, Object arg0) {
logIfEnabled(Level.FATAL, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a fatal message with a throwable.
*/
public void fatal(Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(Level.FATAL, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a fatal message with a throwable.
*/
public void fatal(Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(Level.FATAL, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a fatal message with a throwable.
*/
public void fatal(Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(Level.FATAL, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a message at the provided level.
*/
public void log(Level level, String msg) {
logIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a message at the provided level.
*/
public void log(Level level, String msg, Object arg0) {
logIfEnabled(level, null, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a message at the provided level.
*/
public void log(Level level, String msg, Object arg0, Object arg1) {
logIfEnabled(level, null, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a message at the provided level.
*/
public void log(Level level, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(level, null, msg, arg0, arg1, arg2, null);
}
/**
* Log a message at the provided level.
*/
public void log(Level level, String msg, Object[] argArray) {
logIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
/**
* Log a message with a throwable at the provided level.
*/
public void log(Level level, Throwable throwable, String msg) {
logIfEnabled(level, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a message with a throwable at the provided level.
*/
public void log(Level level, Throwable throwable, String msg, Object arg0) {
logIfEnabled(level, throwable, msg, arg0, UNKNOWN_ARG, UNKNOWN_ARG, null);
}
/**
* Log a message with a throwable at the provided level.
*/
public void log(Level level, Throwable throwable, String msg, Object arg0, Object arg1) {
logIfEnabled(level, throwable, msg, arg0, arg1, UNKNOWN_ARG, null);
}
/**
* Log a message with a throwable at the provided level.
*/
public void log(Level level, Throwable throwable, String msg, Object arg0, Object arg1, Object arg2) {
logIfEnabled(level, throwable, msg, arg0, arg1, arg2, null);
}
/**
* Log a message with a throwable at the provided level.
*/
public void log(Level level, Throwable throwable, String msg, Object[] argArray) {
logIfEnabled(level, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);
}
private void logIfEnabled(Level level, Throwable throwable, String msg, Object arg0, Object arg1, Object arg2,
Object[] argArray) {
if (log.isLevelEnabled(level)) {
String fullMsg = buildFullMessage(msg, arg0, arg1, arg2, argArray);
if (throwable == null) {
log.log(level, fullMsg);
} else {
log.log(level, fullMsg, throwable);
}
}
}
/**
* Return a combined single message from the msg (with possible {}) and optional arguments.
*/
private String buildFullMessage(String msg, Object arg0, Object arg1, Object arg2, Object[] argArray) {
StringBuilder sb = null;
int lastIndex = 0;
int argC = 0;
while (true) {
int argIndex = msg.indexOf(ARG_STRING, lastIndex);
// no more {} arguments?
if (argIndex == -1) {
break;
}
if (sb == null) {
// we build this lazily in case there is no {} in the msg
sb = new StringBuilder(DEFAULT_FULL_MESSAGE_LENGTH);
}
// add the string before the arg-string
sb.append(msg, lastIndex, argIndex);
// shift our last-index past the arg-string
lastIndex = argIndex + ARG_STRING.length();
// add the argument, if we still have any
if (argArray == null) {
if (argC == 0) {
appendArg(sb, arg0);
} else if (argC == 1) {
appendArg(sb, arg1);
} else if (argC == 2) {
appendArg(sb, arg2);
} else {
// we have too many {} so we just ignore them
}
} else if (argC < argArray.length) {
appendArg(sb, argArray[argC]);
} else {
// we have too many {} so we just ignore them
}
argC++;
}
if (sb == null) {
// if we have yet to create a StringBuilder then just append the msg which has no {}
return msg;
} else {
// spit out the end of the msg
sb.append(msg, lastIndex, msg.length());
return sb.toString();
}
}
private void appendArg(StringBuilder sb, Object arg) {
if (arg == UNKNOWN_ARG) {
// ignore it
} else if (arg == null) {
// this is what sb.append(null) does
sb.append("null");
} else if (arg.getClass().isArray()) {
// we do a special thing if we have an array argument
Object[] array = (Object[]) arg;
sb.append('[');
for (int i = 0; i < array.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(array[i]);
}
sb.append(']');
} else {
// might as well to the toString here because we know it isn't null
sb.append(arg.toString());
}
}
}
|
gpl-3.0
|
juzzlin/DustRacing2D
|
src/game/MiniCore/src/Asset/mcsurfaceconfigloader.cc
|
10264
|
// This file belongs to the "MiniCore" game engine.
// Copyright (C) 2015 Jussi Lind <jussi.lind@iki.fi>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
#include <QDir>
#include <QDomDocument>
#include <QDomElement>
#include <QFile>
#include "mclogger.hh"
#include "mcsurfaceconfigloader.hh"
#include "mcsurfacemetadata.hh"
#include <cassert>
#include <exception>
MCSurfaceConfigLoader::MCSurfaceConfigLoader()
: m_surfaces()
{
m_blendFuncMap["one"] = GL_ONE;
m_blendFuncMap["zero"] = GL_ZERO;
m_blendFuncMap["srcColor"] = GL_SRC_COLOR;
m_blendFuncMap["oneMinusSrcColor"] = GL_ONE_MINUS_SRC_COLOR;
m_blendFuncMap["srcAlpha"] = GL_SRC_ALPHA;
m_blendFuncMap["oneMinusSrcAlpha"] = GL_ONE_MINUS_SRC_ALPHA;
m_blendFuncMap["dstColor"] = GL_DST_COLOR;
m_blendFuncMap["oneMinusDstColor"] = GL_ONE_MINUS_DST_COLOR;
}
void MCSurfaceConfigLoader::parseAttributes(const QDomElement & element, SurfaceDataPtr newData, const std::string & baseImagePath)
{
if (element.hasAttribute("image"))
{
const std::string image = element.attribute("image", "").toStdString();
newData->imagePath = baseImagePath + QDir::separator().toLatin1() + image;
}
else
{
throw std::runtime_error("Attribute 'image' is required for a surface!");
}
if (element.hasAttribute("handle"))
{
newData->handle = element.attribute("handle", "").toStdString();
}
else
{
throw std::runtime_error("Attribute 'handle' is required for a surface!");
}
newData->handle2 = element.attribute("handle2", "").toStdString();
newData->handle3 = element.attribute("handle3", "").toStdString();
newData->xAxisMirror = element.attribute("xAxisMirror", "0").toInt();
newData->yAxisMirror = element.attribute("yAxisMirror", "0").toInt();
if (element.hasAttribute("z")) // Shorthand z
{
const float z = element.attribute("z", "0").toFloat();
newData->z0 = z;
newData->z1 = z;
newData->z2 = z;
newData->z3 = z;
}
else if (
element.hasAttribute("z0") || element.hasAttribute("z1") || element.hasAttribute("z2") || element.hasAttribute("z3"))
{
newData->z0 = element.attribute("z0", "0").toFloat();
newData->z1 = element.attribute("z1", "0").toFloat();
newData->z2 = element.attribute("z2", "0").toFloat();
newData->z3 = element.attribute("z3", "0").toFloat();
}
if (element.hasAttribute("w"))
{
const unsigned int width = element.attribute("w", "0").toUInt();
newData->width = std::pair<int, bool>(width, width > 0);
}
if (element.hasAttribute("h"))
{
const unsigned int height = element.attribute("h", "0").toUInt();
newData->height = std::pair<int, bool>(height, height > 0);
}
if (element.hasAttribute("specularCoeff"))
{
const float specularCoeff = element.attribute("specularCoeff", "1").toFloat();
newData->specularCoeff = std::pair<GLfloat, bool>(specularCoeff, specularCoeff > 1.0f);
}
}
void MCSurfaceConfigLoader::parseChildNodes(const QDomNode & node, SurfaceDataPtr newData)
{
// Read child nodes of surface node.
auto && childNode = node.firstChild();
while (!childNode.isNull())
{
if (childNode.nodeName() == "color")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
newData->color.setR(element.attribute("r", "1").toFloat());
newData->color.setG(element.attribute("g", "1").toFloat());
newData->color.setB(element.attribute("b", "1").toFloat());
newData->color.setA(element.attribute("a", "1").toFloat());
}
}
else if (childNode.nodeName() == "colorKey")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
newData->colorKey.m_r = element.attribute("r", "0").toUInt();
newData->colorKey.m_g = element.attribute("g", "0").toUInt();
newData->colorKey.m_b = element.attribute("b", "0").toUInt();
newData->colorKeySet = true;
}
}
else if (childNode.nodeName() == "alphaBlend")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
newData->alphaBlend.first.m_src =
alphaBlendStringToEnum(
element.attribute("src", "srcAlpha").toStdString());
newData->alphaBlend.first.m_dst =
alphaBlendStringToEnum(
element.attribute(
"dst", "srcAlphaMinusOne")
.toStdString());
newData->alphaBlend.second = true;
}
}
else if (childNode.nodeName() == "alphaClamp")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
newData->alphaClamp.first = element.attribute("val", "0.5").toFloat();
newData->alphaClamp.second = true;
}
}
else if (childNode.nodeName() == "filter")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
const std::string min = element.attribute("min", "").toStdString();
const std::string mag = element.attribute("mag", "").toStdString();
if (min == "linear")
{
newData->minFilter = std::pair<GLint, bool>(GL_LINEAR, true);
}
else if (min == "nearest")
{
newData->minFilter = std::pair<GLint, bool>(GL_NEAREST, true);
}
else
{
throw std::runtime_error("Unknown min filter '" + min + "'");
}
if (mag == "linear")
{
newData->magFilter = std::pair<GLint, bool>(GL_LINEAR, true);
}
else if (mag == "nearest")
{
newData->magFilter = std::pair<GLint, bool>(GL_NEAREST, true);
}
else
{
throw std::runtime_error("Unknown mag filter '" + mag + "'");
}
}
}
else if (childNode.nodeName() == "wrap")
{
const auto && element = childNode.toElement();
if (!element.isNull())
{
const std::string s = element.attribute("s", "").toStdString();
const std::string t = element.attribute("t", "").toStdString();
// Windows build hack
#ifndef GL_CLAMP_TO_EDGE
#define GL_CLAMP_TO_EDGE 0x812F
#endif
if (s == "clamp")
{
newData->wrapS = std::pair<GLint, bool>(GL_CLAMP_TO_EDGE, true);
}
else if (s == "repeat")
{
newData->wrapS = std::pair<GLint, bool>(GL_REPEAT, true);
}
else
{
throw std::runtime_error("Unknown s wrap '" + s + "'");
}
if (t == "clamp")
{
newData->wrapT = std::pair<GLint, bool>(GL_CLAMP_TO_EDGE, true);
}
else if (t == "repeat")
{
newData->wrapT = std::pair<GLint, bool>(GL_REPEAT, true);
}
else
{
throw std::runtime_error("Unknown t wrap '" + t + "'");
}
}
}
else
{
throw std::runtime_error("Unknown element '" + childNode.nodeName().toStdString() + "'");
}
childNode = childNode.nextSibling();
}
}
bool MCSurfaceConfigLoader::load(const std::string & path)
{
QDomDocument doc;
QFile file(path.c_str());
if (!file.open(QIODevice::ReadOnly))
{
return false;
}
if (!doc.setContent(&file))
{
file.close();
return false;
}
file.close();
const auto && root = doc.documentElement();
if (root.nodeName() == "surfaces")
{
const std::string baseImagePath = root.attribute("baseImagePath", "./").toStdString();
auto && node = root.firstChild();
while (!node.isNull() && node.nodeName() == "surface")
{
auto newData = std::make_shared<MCSurfaceMetaData>();
auto element = node.toElement();
if (!element.isNull())
{
parseAttributes(element, newData, baseImagePath);
parseChildNodes(node, newData);
}
m_surfaces.push_back(newData);
node = node.nextSibling();
}
}
return true;
}
GLenum MCSurfaceConfigLoader::alphaBlendStringToEnum(const std::string & function) const
{
try
{
return m_blendFuncMap.at(function);
} catch (...)
{
throw std::runtime_error("Unknown alpha blend function '" + function + "'");
}
return GL_SRC_ALPHA;
}
size_t MCSurfaceConfigLoader::surfaceCount() const
{
return m_surfaces.size();
}
const MCSurfaceMetaData & MCSurfaceConfigLoader::surface(size_t index) const
{
assert(index < m_surfaces.size());
assert(m_surfaces.at(index));
return *m_surfaces.at(index);
}
|
gpl-3.0
|
lucabaldini/ixpepg
|
Geometry/src/ixpeHexagonalGrid.cpp
|
2742
|
/***********************************************************************
Copyright (C) 2017 the Imaging X-ray Polarimetry Explorer (IXPE) team.
For the license terms see the file LICENSE, distributed along with this
software.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
***********************************************************************/
#include <cmath>
#include "ixpeHexagonalGrid.h"
#include "ixpeHexagonalCoordinates.h"
#include "ixpeMath.h"
ixpeHexagonalGrid::ixpeHexagonalGrid(int numColumns, int numRows,
double columnPitch) :
m_numColumns(numColumns),
m_numRows(numRows),
m_columnPitch(columnPitch),
m_rowPitch(m_columnPitch * ixpeMath::xpolSqrt3() / 2.),
m_columnOffset(0.5 * (m_numColumns - 1.5) * m_columnPitch),
m_rowOffset(0.5 * (m_numRows - 1) * m_rowPitch),
m_hexagonSize(m_columnPitch / ixpeMath::xpolSqrt3())
{}
ixpeCartesianCoordinate ixpeHexagonalGrid::pixelToWorld(int col, int row) const
{
double x = (col - 0.5 * (row & 1)) * m_columnPitch - m_columnOffset;
double y = m_rowOffset - row * m_rowPitch;
return ixpeCartesianCoordinate(x, y);
}
ixpeCartesianCoordinate
ixpeHexagonalGrid::pixelToWorld(const ixpeOffsetCoordinate& off) const
{
return pixelToWorld(off.column(), off.row());
}
ixpeOffsetCoordinate ixpeHexagonalGrid::worldToPixel(double x, double y) const
{
x = m_columnOffset + x;
y = m_rowOffset - y;
double fq = (x * ixpeMath::xpolSqrt3() / 3. - y / 3.) / m_hexagonSize;
double fr = y * 2. / 3. / m_hexagonSize;
ixpeCubeCoordinate cube = cubeRound(fq, fr, -fq - fr);
ixpeOffsetCoordinate offset = cubeToEroffset(cube);
if (not contains(offset)) {
throw coordinate_out_of_grid();
}
return offset;
}
ixpeOffsetCoordinate
ixpeHexagonalGrid::worldToPixel(const ixpeCartesianCoordinate& cart) const
{
return worldToPixel(cart.x(), cart.y());
}
bool ixpeHexagonalGrid::contains(int col, int row) const
{
return (col >= 0 && col < m_numColumns && row >= 0 && row < m_numRows);
}
bool ixpeHexagonalGrid::contains(const ixpeOffsetCoordinate& off) const
{
return contains(off.column(), off.row());
}
|
gpl-3.0
|
kriztan/Pix-Art-Messenger
|
src/main/java/eu/siacs/conversations/entities/ReadByMarker.java
|
5511
|
package eu.siacs.conversations.entities;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import eu.siacs.conversations.xmpp.Jid;
public class ReadByMarker {
private ReadByMarker() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReadByMarker marker = (ReadByMarker) o;
if (fullJid != null ? !fullJid.equals(marker.fullJid) : marker.fullJid != null)
return false;
return realJid != null ? realJid.equals(marker.realJid) : marker.realJid == null;
}
@Override
public int hashCode() {
int result = fullJid != null ? fullJid.hashCode() : 0;
result = 31 * result + (realJid != null ? realJid.hashCode() : 0);
return result;
}
private Jid fullJid;
private Jid realJid;
public Jid getFullJid() {
return fullJid;
}
public Jid getRealJid() {
return realJid;
}
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (fullJid != null) {
try {
jsonObject.put("fullJid", fullJid.toString());
} catch (JSONException e) {
//ignore
}
}
if (realJid != null) {
try {
jsonObject.put("realJid", realJid.toString());
} catch (JSONException e) {
//ignore
}
}
return jsonObject;
}
public static Set<ReadByMarker> fromJson(final JSONArray jsonArray) {
final Set<ReadByMarker> readByMarkers = new CopyOnWriteArraySet<>();
for (int i = 0; i < jsonArray.length(); ++i) {
try {
readByMarkers.add(fromJson(jsonArray.getJSONObject(i)));
} catch (JSONException e) {
//ignored
}
}
return readByMarkers;
}
public static ReadByMarker from(Jid fullJid, Jid realJid) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = fullJid;
marker.realJid = realJid == null ? null : realJid.asBareJid();
return marker;
}
public static ReadByMarker from(Message message) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = message.getCounterpart();
marker.realJid = message.getTrueCounterpart();
return marker;
}
public static ReadByMarker from(MucOptions.User user) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = user.getFullJid();
marker.realJid = user.getRealJid();
return marker;
}
public static Set<ReadByMarker> from(Collection<MucOptions.User> users) {
final Set<ReadByMarker> markers = new CopyOnWriteArraySet<>();
for (MucOptions.User user : users) {
markers.add(from(user));
}
return markers;
}
public static ReadByMarker fromJson(JSONObject jsonObject) {
ReadByMarker marker = new ReadByMarker();
try {
marker.fullJid = Jid.of(jsonObject.getString("fullJid"));
} catch (JSONException e) {
marker.fullJid = null;
} catch (IllegalArgumentException e) {
marker.fullJid = null;
}
try {
marker.realJid = Jid.of(jsonObject.getString("realJid"));
} catch (JSONException e) {
marker.realJid = null;
} catch (IllegalArgumentException e) {
marker.realJid = null;
}
return marker;
}
public static Set<ReadByMarker> fromJsonString(String json) {
try {
return fromJson(new JSONArray(json));
} catch (JSONException e) {
return new CopyOnWriteArraySet<>();
} catch (NullPointerException e) {
return new CopyOnWriteArraySet<>();
}
}
public static JSONArray toJson(final Set<ReadByMarker> readByMarkers) {
JSONArray jsonArray = new JSONArray();
for (final ReadByMarker marker : readByMarkers) {
jsonArray.put(marker.toJson());
}
return jsonArray;
}
public static boolean contains(ReadByMarker needle, final Set<ReadByMarker> readByMarkers) {
for(final ReadByMarker marker : readByMarkers) {
if (marker.realJid != null && needle.realJid != null) {
if (marker.realJid.asBareJid().equals(needle.realJid.asBareJid())) {
return true;
}
} else if (marker.fullJid != null && needle.fullJid != null) {
if (marker.fullJid.equals(needle.fullJid)) {
return true;
}
}
}
return false;
}
public static boolean allUsersRepresented(Collection<MucOptions.User> users, Set<ReadByMarker> markers) {
for(MucOptions.User user : users) {
if (!contains(from(user),markers)) {
return false;
}
}
return true;
}
public static boolean allUsersRepresented(Collection<MucOptions.User> users, Set<ReadByMarker> markers, ReadByMarker marker) {
final Set<ReadByMarker> markersCopy = new CopyOnWriteArraySet<>(markers);
markersCopy.add(marker);
return allUsersRepresented(users, markersCopy);
}
}
|
gpl-3.0
|
unicesi/academ
|
ACADEM-EJBClient/ejbModule/co/edu/icesi/academ/bo/UsuarioBO.java
|
1884
|
/**
* Copyright © 2013 Universidad Icesi
*
* This file is part of ACADEM.
*
* ACADEM 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.
*
* ACADEM 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 ACADEM. If not, see <http://www.gnu.org/licenses/>.
**/
package co.edu.icesi.academ.bo;
import java.io.Serializable;
import java.util.List;
public class UsuarioBO implements Serializable {
private static final long serialVersionUID = 1L;
private String nombre;
private String contraseña;
private String perfil;
private List<RolBO> roles;
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getContraseña() {
return this.contraseña;
}
public void setContraseña(String contraseña) {
this.contraseña = contraseña;
}
public String getPerfil() {
return this.perfil;
}
public void setPerfil(String perfil) {
this.perfil = perfil;
}
public List<RolBO> getRoles() {
return roles;
}
public void setRoles(List<RolBO> roles) {
this.roles = roles;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
UsuarioBO usuario = (UsuarioBO) obj;
if (nombre.equals(usuario.nombre)) return true;
return false;
}
@Override
public int hashCode() {
return nombre.hashCode();
}
@Override
public String toString() {
return nombre;
}
}
|
gpl-3.0
|
jhjguxin/PyCDC
|
pycdc-v1.0.py
|
1731
|
# -*- coding: utf-8 -*-
import sys,cmd
from cdctools import *
class PyCDC(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)#initialize the base class
self.CDROM='/media/cdrom0'
# self.CDROM=os.getcwd()
self.CDDIR='cdc/'
self.prompt='(PyCDC)>'
self.intro='''PyCDC v1.0 使用说明:
dir 目录名 #指定保存和搜索目录,默认是 "cdc"
walk 文件名 #指定光盘信息文件名,使用 "*.cdc"
find 关键词 #使用在保存和搜索目录中遍历所有.cdc 文件,输出含有关键词的行
? #查询
EOF # 退出系统,也可以使用 Crtl+D(Unix)|Ctrl+Z(Dos/Windows)
'''
def help_EOF(self):
print '退出程序 Quits the program'
def do_EOF(self,line):
sys.exit()
def help_walk(self):
print '扫描光盘内容 walk cd and export into *.cdc'
def do_walk(self,filename):
if filename=="":filename = raw_input("输入 cdc 文件名:: ")
print "扫描光盘内容保存到:'%s'" % filename
cdWalker(self.CDROM,self.CDDIR+filename)
def help_dir(self):
print "指定保存/搜索目录"
def do_dir(self,pathname):
if pathname=="": pathname = raw_input("输入指定保存/搜索目录: ")
default=self.CDDIR
self.CDDIR=pathname
print "指定保存/搜索目录:'%s' ;默认是:'%s'" % (self.CDDIR,default)
def help_find(self):
print "搜索关键词"
def do_find(self,keyword):
if keyword=="":keyword=raw_input("输入搜索关键字: ")
print "搜索关键词:'%s'" % keyword
cdcGrep(self.CDDIR,keyword)
if __name__=='__main__': #this way the module can be
cdc=PyCDC() #imported by other programs as well
cdc.cmdloop()
# CDROM=os.getcwd()
# cdWalker(CDROM,'cdc/cdctools.cdc')
|
gpl-3.0
|
expez/EASY
|
EASY/src/edu/ntnu/EASY/IntegerArrayFitnessCalculators.java
|
1502
|
/*Copyright (C) 2012 Lars Andersen, Tormund S. Haus.
larsan@stud.ntnu.no
tormunds@stud.ntnu.no
EASY 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.
EASY 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 EASY. If not, see <http://www.gnu.org/licenses/>.*/
package edu.ntnu.EASY;
public class IntegerArrayFitnessCalculators {
public static final FitnessCalculator<int[]> ONE_MAX_FITNESS = new FitnessCalculator<int[]>(){
{};
@Override
public void setPopulation(Population<?, int[]> population) {
}
@Override
/**
* Fitness is equal to sum of 1s in the individual's phenotype.
* @param individual to get the fitness for.
* @return A double, in the interval [0,1], representing the fitness.
*/
public double calculate(int[] phenome) {
double fitness = 0.0;
for (int i = 0; i < phenome.length; i++) {
if( phenome[ i ] == 1 ) {
fitness++;
}
}
return fitness / phenome.length;
}
};
}
|
gpl-3.0
|
tsdfsetatata/xserver
|
config/server/fb_yxtz_005Table.lua
|
348
|
local fb_yxtz_005 = {
[1000001] = {
['uid'] = 1000001,
['ID'] = 151005089,
['ResType'] = "Monster",
['PointPosX'] = 68.56927,
['PointPosY'] = 59.5217,
['PointPosZ'] = 44.76086,
['Yaw'] = 0,
['Level'] = 34,
['TargetInfoList'] = {
}
},
}
return fb_yxtz_005
|
gpl-3.0
|
mikemirten/ZExt
|
library/ZExt/Validator/Digits.php
|
1381
|
<?php
/**
* ZExt Framework (http://z-ext.com)
* Copyright (C) 2012 Mike.Mirten
*
* LICENSE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright (c) 2012, Mike.Mirten
* @license http://www.gnu.org/licenses/gpl.html GPL License
* @category ZExt
* @version 1.0
*/
namespace ZExt\Validator;
/**
* Digital (int or float) type validator
*
* @category ZExt
* @package Validator
* @subpackage Digits
* @author Mike.Mirten
* @version 1.0
*/
class Digits extends ValidatorAbstract {
/**
* Is the value valid
*
* @param mixed $value
* @return bool
*/
public function isValid($value) {
if (is_int($value) || is_float($value)) {
return true;
}
$this->addMessage('Value must be a digital');
return false;
}
}
|
gpl-3.0
|
bkazez/bmpm-cpp
|
bmpm-cpp/languages.cpp
|
2466
|
#include "cpp/php2cpp.h"
#ifndef LANGUAGES_CPP
#define LANGUAGES_CPP
#include "languages.h"
php_type Language(php_type name, php_type rules, php_type allLanguagesBitmap)
{
// convert $name to utf8
name = utf8_encode(name);
// takes care of things in the upper half of the ascii chart, e.g., u-umlaut
if (strpos(name, "&") != /* ORIG: !== */ false) {
// takes care of ampersand-notation encoding of unicode (&#...;)
name = html_entity_decode(name, ENT_NOQUOTES, "UTF-8");
}
return Language_UTF8(name, rules, allLanguagesBitmap);
}
php_type Language_UTF8(php_type name, php_type rules, php_type allLanguagesBitmap)
{
// $name = mb_strtolower($name, mb_detect_encoding($name));
name = mb_strtolower(name, "UTF-8");
choicesRemaining = allLanguagesBitmap;
for (i = 0; i < count(rules); i++) {
list(letters, languages, accept) = rules[i];
//echo "testing name=$name letters=$letters languages=$languages accept=$accept<br>";
if (preg_match(letters, name)) {
if (accept) {
choicesRemaining &= languages;
} else {
// reject
choicesRemaining &= ~languages % (allLanguagesBitmap + 1);
}
}
}
if (choicesRemaining == 0) {
choicesRemaining = 1;
}
return choicesRemaining;
}
php_type LanguageIndex(php_type langName, php_type languages)
{
for (i = 0; i < count(languages); i++) {
if (languages[i] == langName) {
//echo "LanguageIndex: $i\n";
return i;
}
}
//echo "LanguageIndex Not Found\n";
return 0;
// name not found
}
php_type LanguageName(php_type index, php_type languages)
{
if (index < 0 || index > count(languages)) {
std::cout << "index out of range: " + index + "\n";
exit;
return "any";
// index out of range
}
return languages[index];
}
php_type LanguageCode(php_type langName, php_type languages)
{
return 1 << LanguageIndex(langName, languages);
}
php_type LanguageIndexFromCode(php_type code, php_type languages)
{
if (code < 0 || code > 1 << count(languages) - 1) {
// code out of range
return 0;
}
log = log(code, 2);
result = floor(log);
if (result != log) {
// choice was more than one language, so use "any"
result = LanguageIndex("any", languages);
}
return result;
}
#else
#endif
|
gpl-3.0
|
idega/platform2
|
src/com/idega/user/presentation/SubsetSelector.java
|
4566
|
package com.idega.user.presentation;
import com.idega.util.IWColor;
import com.idega.idegaweb.browser.presentation.IWBrowserView;
import com.idega.presentation.*;
import com.idega.event.IWPresentationEvent;
import com.idega.user.event.PartitionSelectEvent;
import com.idega.presentation.text.Link;
/**
* <p>Title: idegaWeb</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: idega Software</p>
* @author <a href="gummi@idega.is">Gu�mundur �g�st S�mundsson</a>
* @version 1.0
*/
public class SubsetSelector extends PresentationObjectContainer implements IWBrowserView
{
private static final String spacer = " ";
private int _maxShowedPartitions = 6;
private int _maxPartitions;
private int _firstPartition = 0;
private int _selectedSubset = 0;
private int _subsetSize;
private int _size = 0;
private String _controlTarget = null;
private IWPresentationEvent _contolEvent = null;
public SubsetSelector(int subsetSize, int size, int maxShowedPartitions)
{
this._maxShowedPartitions = maxShowedPartitions;
this._size = size;
this._maxPartitions= size/subsetSize + ((size%subsetSize > 0)?1:0);
this._subsetSize = subsetSize;
}
public void setFirstSubset(int index){
this._firstPartition = index;
}
public void setSelectedSubset(int index){
this._selectedSubset = index;
}
public void setControlEventModel(IWPresentationEvent model){
this._contolEvent = model;
}
public void setControlTarget(String controlTarget){
this._controlTarget = controlTarget;
}
public void main(IWContext iwc) throws Exception
{
Layer partitionSelection = new Layer();
partitionSelection.setHorizontalAlignment("center");
partitionSelection.setBackgroundColor(new IWColor(230,230,230).getHexColorString());
if (this._size > this._subsetSize){
for( int i = this._firstPartition; ((i < this._maxPartitions)&&((i-this._firstPartition) < this._maxShowedPartitions)); i++)
{
if(this._firstPartition == i && this._firstPartition != 0)
{
Link begin = new Link();
begin.setText("<");
PartitionSelectEvent event = new PartitionSelectEvent();
//event.setSource(this.getLocation());
event.setSource(this);
int newFirstPartition = Math.max(0,this._firstPartition-this._maxShowedPartitions);
event.setFirstPartitionIndex(newFirstPartition);
event.setPartitionSize(this._subsetSize);
int newSelectedPartition = newFirstPartition+this._maxShowedPartitions-1;
event.setSelectedPartition(newSelectedPartition);
begin.addEventModel(event);
if (this._controlTarget != null)
{
begin.setTarget(this._controlTarget);
}
if (this._contolEvent != null)
{
begin.addEventModel(this._contolEvent);
}
begin.addEventModel(this._contolEvent);
partitionSelection.add(begin);
partitionSelection.add(spacer);
}
Link l = new Link();
if(i != this._firstPartition){
partitionSelection.add(spacer);
}
l.setText(((i*this._subsetSize)+1)+"-"+(((i+1)*this._subsetSize)));
PartitionSelectEvent event = new PartitionSelectEvent();
event.setSource(this.getLocation());
event.setPartitionSize(this._subsetSize);
event.setFirstPartitionIndex(this._firstPartition);
event.setSelectedPartition(i);
l.addEventModel(event);
if (this._controlTarget != null)
{
l.setTarget(this._controlTarget);
}
if (this._contolEvent != null)
{
l.addEventModel(this._contolEvent);
}
if(i == this._selectedSubset)
{
l.setBold();
}
partitionSelection.add(l);
if(((i == this._maxPartitions-1)||((i-this._firstPartition) == this._maxShowedPartitions-1)) && this._maxPartitions > (i+1))
{
partitionSelection.add(spacer);
Link end = new Link();
end.setText(">");
PartitionSelectEvent event2 = new PartitionSelectEvent();
event2.setSource(this.getLocation());
int newFirstPartition = Math.min(this._maxPartitions-this._maxShowedPartitions,this._firstPartition+this._maxShowedPartitions);
event2.setFirstPartitionIndex(newFirstPartition);
event2.setPartitionSize(this._subsetSize);
event2.setSelectedPartition(newFirstPartition);
end.addEventModel(event2);
if (this._controlTarget != null)
{
end.setTarget(this._controlTarget);
}
if (this._contolEvent != null)
{
end.addEventModel(this._contolEvent);
}
partitionSelection.add(end);
}
}
this.add(partitionSelection);
}
}
}
|
gpl-3.0
|
fabienbaron/splash
|
src/mse.cpp
|
470
|
#include "core.h"
#include "similarityMetric.h"
#include "mse.h"
calcMSE :: calcMSE()
{
for (int i = 0; i < 4; i++)
mse.val[i] = -1;
}
float calcMSE :: compare(const Mat &mat1, const Mat &mat2)
{
//creating diff and difference squares
Mat diff;
Mat diff_sq;
absdiff(mat1, mat2, diff);
pow(diff, 2, diff_sq);
Scalar num = mean(diff_sq);
pow(mat1, 2, diff_sq); // re-using diff_sq
Scalar denom = mean(diff_sq);
return (num / denom).val[0];
}
|
gpl-3.0
|
jindrapetrik/jpexs-decompiler
|
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/action/model/TargetPathActionItem.java
|
3504
|
/*
* Copyright (C) 2010-2021 JPEXS, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package com.jpexs.decompiler.flash.action.model;
import com.jpexs.decompiler.flash.SourceGeneratorLocalData;
import com.jpexs.decompiler.flash.action.swf5.ActionTargetPath;
import com.jpexs.decompiler.flash.helpers.GraphTextWriter;
import com.jpexs.decompiler.graph.CompilationException;
import com.jpexs.decompiler.graph.GraphSourceItem;
import com.jpexs.decompiler.graph.GraphSourceItemPos;
import com.jpexs.decompiler.graph.GraphTargetItem;
import com.jpexs.decompiler.graph.SourceGenerator;
import com.jpexs.decompiler.graph.model.LocalData;
import java.util.List;
import java.util.Objects;
/**
*
* @author JPEXS
*/
public class TargetPathActionItem extends ActionItem {
public TargetPathActionItem(GraphSourceItem instruction, GraphSourceItem lineStartIns, GraphTargetItem object) {
super(instruction, lineStartIns, PRECEDENCE_PRIMARY, object);
}
@Override
public GraphTextWriter appendTo(GraphTextWriter writer, LocalData localData) throws InterruptedException {
writer.append("targetPath");
writer.spaceBeforeCallParenthesies(1);
writer.append("(");
value.toString(writer, localData);
return writer.append(")");
}
@Override
public List<GraphSourceItemPos> getNeededSources() {
List<GraphSourceItemPos> ret = super.getNeededSources();
ret.addAll(value.getNeededSources());
return ret;
}
@Override
public List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException {
return toSourceMerge(localData, generator, value, new ActionTargetPath());
}
@Override
public boolean hasReturnValue() {
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GraphTargetItem other = (GraphTargetItem) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
return true;
}
@Override
public boolean valueEquals(GraphTargetItem obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GraphTargetItem other = (GraphTargetItem) obj;
if (!GraphTargetItem.objectsValueEquals(this.value, other.value)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean hasSideEffect() {
return true;
}
}
|
gpl-3.0
|
ruymanengithub/vison
|
vison/eyegore/eyeObs.py
|
11189
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Eyegore: Exposure Log Monitoring.
Created on Fri Oct 13 16:22:36 2017
:author: raf
"""
# IMPORT STUFF
from pdb import set_trace as stop
#import matplotlib
# matplotlib.use("TkAgg")
import glob
from astropy.table import Table
import os
import time
import string as st
import numpy as np
from vison.datamodel import EXPLOGtools as ELtools
from vison.support import context
from vison.eyegore.eyelib import get_bitsize
import tkinter as tk
import tkinter.ttk
import tkinter.font as tkFont
try:
import pyds9
except ImportError:
print('pyds9 not installed in the system. Will not be possible to liaise with SAO-ds9.')
# END IMPORT
LARGE_FONT = ("Helvetica", 12)
small_font = ("Verdana", 8)
medium_font = ("Verdana", 10)
def isNumeric(s):
"""
test if a string s is numeric
"""
for c in s:
if c in "1234567890-.+":
numeric = True
else:
return False
return numeric
def changeNumeric(data):
"""
if the data to be sorted is numeric change to float
"""
new_data = []
if isNumeric(data[0][0]):
# change child to a float
for child, col in data:
new_data.append((float(child), col))
return new_data
return data
class ExpLogDisplay(tk.Toplevel):
""" """
def __init__(self, parent, path, interval, elvis=context.elvis, ds9target='DS9:*',
tag=''):
self.path = path
self.elvis = elvis
self.ds9target = ds9target
self.date = '21-02-80'
self.interval = interval
self.explogfs = None
self.EXPLOG = Table()
self.nEL = 0 # Nr. lines in EXPLOG
self.sEL = 0 # size of EXPLOG, bytes
self.log = parent.log
self.tag = tag
self.labels = {}
self.elementHeader = []
self.elementList = []
self.info = ""
self.tree = None
#self.NObsID = 0
#self.Nentries = 0
#self.updating = True
tk.Toplevel.__init__(self, parent)
self.updating = tk.BooleanVar()
self.updating.set(True)
# self.minsize(width=850,height=500)
self.info = """\
Click on header to sort by that column. To change width of column drag boundary.
"""
title = 'EXP-LOG'
if self.tag != '':
title = '%s: %s' % (title, self.tag)
self.wm_title(title)
self.fr0 = tk.Frame(self)
self.fr0.pack(fill='both', expand=False)
# self.fr0.grid()
# msg = ttk.Label(self,wraplength="4i", justify="left", anchor="n",
# padding=(10, 2, 10, 6), text=self.info)
# msg.grid(row=0,column=0,columnspan=2,in_=self.frame)
self.fr1 = tk.Frame(self)
self.fr1.grid(row=0, in_=self.fr0)
self.labels['NObsIDs'] = dict()
self.labels['NObsIDs']['var'] = tk.StringVar()
self.labels['NObsIDs']['var'].set("NObs = 0")
self.labels['NObsIDs']['app'] = tk.Label(self, textvariable=self.labels['NObsIDs']['var'],
font=medium_font, bd=2, relief='groove')
self.labels['NObsIDs']['app'].grid(
row=0, column=0, in_=self.fr1, sticky='w')
self.labels['NEntries'] = dict()
self.labels['NEntries']['var'] = tk.StringVar()
self.labels['NEntries']['var'].set("NEntries = 0")
self.labels['NEntries']['app'] = tk.Label(self, textvariable=self.labels['NEntries']['var'],
font=medium_font, bd=2, relief='groove')
self.labels['NEntries']['app'].grid(
row=0, column=1, in_=self.fr1, sticky='w')
pause_check = tk.Checkbutton(self, text='PAUSED', variable=self.updating,
onvalue=False, offvalue=True, height=5,
width=20, command=self.print_paused)
pause_check.grid(column=0, row=1, sticky='w', padx=0, in_=self.fr1)
self.fr1.grid_columnconfigure(0, weight=1)
self.fr1.grid_rowconfigure(0, weight=1)
self.search_EXPLOGs()
_ = self.get_data()
self.elementHeader = self.EXPLOG.colnames
self.build_elementList()
self.createScrollableTreeview()
self.fr0.grid_columnconfigure(0, weight=1)
self.fr0.grid_rowconfigure(0, weight=1)
self.update(startup=True)
# self.update()
def print_paused(self):
print('self.updating is %s' % self.updating.get())
def update(self, startup=False):
print(('entering ExpLogDisplay.update. Interval=%i' % self.interval))
if self.updating.get():
self.search_EXPLOGs()
theresnewdata = self.get_data()
if theresnewdata or startup:
self.tree.yview_moveto(1)
self.build_elementList()
self.buildTree()
self.tree.yview_moveto(1)
self.after(self.interval, self.update)
def createScrollableTreeview(self):
# create a treeview with dual scrollbars
self.fr2 = tk.Frame(self)
#self.subframe.pack(fill='both', expand=True)
self.fr2.grid(row=1, column=0, in_=self.fr0)
self.tree = tkinter.ttk.Treeview(
self, columns=self.elementHeader, show="headings")
for col in self.elementHeader:
self.tree.column(col, minwidth=100, width=100, stretch=True)
vsb = tkinter.ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
hsb = tkinter.ttk.Scrollbar(self, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.tree.grid(column=0, row=0, sticky='nsew', in_=self.fr2)
vsb.grid(column=1, row=0, sticky='ns', in_=self.fr2)
hsb.grid(column=0, row=1, sticky='ew', in_=self.fr2)
# self.tree.yview_scroll(-1,'units')
# self.tree.yview_moveto(0.5)
self.tree['height'] = 30
self.fr2.grid_columnconfigure(0, weight=1)
self.fr2.grid_rowconfigure(0, weight=1)
def build_elementList(self):
""" """
self.elementList = []
for ix in range(len(self.EXPLOG)):
row = []
for jx, colname in enumerate(self.elementHeader):
row.append(self.EXPLOG[colname][ix])
self.elementList.append(tuple(row))
def search_EXPLOGs(self):
""" """
if self.path is None:
self.explogfs = None
return
struct_date = time.strptime(os.path.split(
self.path.replace('_', ''))[-1], '%d%b%y')
date_infile = time.strftime('%d%m%y', struct_date)
self.date = date_infile
tmp_EL = 'EXP_LOG_*.txt'
tmp_EL = os.path.join(self.path, tmp_EL)
explogfs = glob.glob(tmp_EL)
arethere = len(explogfs) > 0
if arethere:
self.explogfs = explogfs
else:
print('EXPLOGs %s not found' % tmp_EL)
self.explogfs = None
def loadExplogs(self):
""" """
ELList = []
for item in self.explogfs:
ELList.append(ELtools.loadExpLog(item, elvis=self.elvis, safe=True))
if len(ELList) < 2:
return ELList[0]
else:
return ELtools.mergeExpLogs(ELList, addpedigree=False)
def get_data(self):
""" """
if self.explogfs is None:
return False
sEL = get_bitsize(self.explogfs)
if sEL <= self.sEL:
return False
try:
EXPLOG = self.loadExplogs()
except BaseException:
return False
#EXPLOG = ELtools.loadExpLog(self.explogf,elvis=self.elvis)
NObsIDs = len(np.unique(EXPLOG['ObsID']))
nEL = len(EXPLOG) # commented on TESTS
# nEL = self.nEL + 5 # TESTS
self.EXPLOG = EXPLOG[self.nEL:nEL]
self.nEL = nEL
self.sEL = sEL
self.labels['NEntries']['var'].set('Nentries = %i' % len(EXPLOG))
self.labels['NObsIDs']['var'].set('NObsIDs = %i' % NObsIDs)
return True
def growTree(self):
for i, item in enumerate(self.elementList):
#print i+self.nEL
if (i + self.nEL) % 2 == 0:
parity = 'odd'
elif (i + self.nEL) % 2 != 0:
parity = 'pair'
self.tree.insert('', 'end', values=item, tags=(parity,))
# adjust column's width if necessary to fit each value
# for ix, val in enumerate(item):
# col_w = tkFont.Font().measure(val)
# if self.tree.column(self.elementHeader[ix], width=None) < col_w:
# self.tree.column(self.elementHeader[ix], width=col_w)
self.elementList = []
def buildTree(self):
# add possibility to sort by each column
for col in self.elementHeader:
self.tree.heading(col, text=col,
command=lambda c=col: self.sortBy(self.tree, c, 0))
# adjust the column's width to the header string
self.tree.column(col, width=int(tkFont.Font(
font='Helvetica', size=12).measure(col) * 1.5))
self.growTree()
self.tree.yview_moveto(1)
# for i in range(1,2*growth+1):
# self.tree.yview_scroll(1,'units')
self.tree.tag_configure('pair', background='#B6D2D2')
self.tree.tag_configure('odd', background='#AFE0B5')
self.tree.bind("<Double-1>", self.OnDoubleClick)
def OnDoubleClick(self, event):
#item = self.tree.selection()[0]
item = self.tree.identify('item', event.x, event.y)
values = self.tree.item(item, "value")
ObsID = int(values[0])
try:
d = pyds9.DS9(target=self.ds9target)
except NameError:
print("pyds9 not installed, can't open DS9!")
return
for CCD in [1, 2, 3]:
tmpfits = os.path.join(
self.path, 'EUC_%i_*D*T_ROE1_CCD%i.fits' % (ObsID, CCD))
try:
iFITSf = glob.glob(tmpfits)[0]
except IndexError:
#print tmpfits
iFITSf = None
if iFITSf is not None:
d.set("frame %i" % CCD)
d.set("file %s" % iFITSf)
d.set("zoom to fit")
d.set("scale mode zscale")
def sortBy(self, tree, col, descending):
"""
sort tree contents when a column header is clicked
"""
# grab values to sort
data = [(tree.set(child, col), child)
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
data = changeNumeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so that it will sort in the opposite direction
tree.heading(col,
command=lambda col=col: self.sortBy(tree, col, int(not descending)))
|
gpl-3.0
|
Jules-/terraingis
|
src/TerrainGIS/src/cz/kalcik/vojta/shapefilelib/files/shp/shapeTypes/ShpPolyVertices.java
|
9576
|
/**
* shapefilelib
* based on Thomas Diewald's diewald_shapeFileReader
* http://thomasdiewald.com/blog/?p=1382
*
* Copyright (c) 2013 Vojtech Kalcik - http://vojta.kalcik.cz/
*
* 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 cz.kalcik.vojta.shapefilelib.files.shp.shapeTypes;
import java.nio.ByteBuffer;
import java.util.Locale;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import cz.kalcik.vojta.shapefilelib.shapeFile.ShapeFile;
/**
* @author jules
*
*/
public abstract class ShpPolyVertices extends ShpShape
{
// SHAPE RECORD CONTENT
protected double[][] SHP_bbox = new double[3][2]; // [x, y, z][min, max]
protected double[] SHP_range_m = new double[2]; // [min, max]
protected int SHP_num_parts, SHP_num_points;
protected int[] SHP_parts;
protected double[][] SHP_xyz_points; // [number of points][x,y,z]
protected double[] SHP_m_values; // [number of points][m-value]
protected double[][][] parts = null; // [number of parts][vertices][x, y,
// z, w]
protected ShpPolyVertices(Type shape_type)
{
super(shape_type);
}
@Override
protected void setBytesRecord(ByteBuffer buffer)
{
buffer.putDouble(SHP_bbox[0][0]); // x-min
buffer.putDouble(SHP_bbox[1][0]); // y-min
buffer.putDouble(SHP_bbox[0][1]); // x-max
buffer.putDouble(SHP_bbox[1][1]); // y-max
buffer.putInt(SHP_num_parts);
buffer.putInt(SHP_num_points);
for(int i=0; i < SHP_num_parts; i++)
{
buffer.putInt(SHP_parts[i]);
}
for(int i=0; i < SHP_num_points; i++)
{
buffer.putDouble(SHP_xyz_points[i][0]);
buffer.putDouble(SHP_xyz_points[i][1]);
}
// if SHAPE-TYPE: 13
if (shape_type.hasZvalues())
{
throw new RuntimeException("Unimplemented");
}
// if SHAPE-TYPE: 13 | 23
if (shape_type.hasMvalues())
{
throw new RuntimeException("Unimplemented");
}
}
@Override
protected int sizeOfObject()
{
int size = ShapeFile.SIZE_OF_MBR + 2 * ShapeFile.SIZE_OF_INT +
SHP_num_parts * ShapeFile.SIZE_OF_INT +
SHP_num_points * ShapeFile.SIZE_OF_POINTXY;
// if SHAPE-TYPE: 15
if (shape_type.hasZvalues())
{
size += 2 * ShapeFile.SIZE_OF_DOUBLE +
SHP_num_points * ShapeFile.SIZE_OF_DOUBLE;
}
// if SHAPE-TYPE: 15 | 25
if (shape_type.hasMvalues())
{
size += 2 * ShapeFile.SIZE_OF_DOUBLE +
SHP_num_points * ShapeFile.SIZE_OF_DOUBLE;
}
return size;
}
@Override
public void loadFromJTS(Geometry geom)
{
Envelope envelope = geom.getEnvelopeInternal();
SHP_bbox[0][0] = envelope.getMinX();
SHP_bbox[1][0] = envelope.getMinY();
SHP_bbox[0][1] = envelope.getMaxX();
SHP_bbox[1][1] = envelope.getMaxY();
SHP_num_parts = geom.getNumGeometries();
SHP_num_points = geom.getNumPoints();
// parts
int partPosition = 0;
SHP_parts = new int[SHP_num_parts];
for(int i=0; i < SHP_num_parts; i++)
{
SHP_parts[i] = partPosition;
partPosition += geom.getGeometryN(i).getNumPoints();
}
//points
int countDimensions = shape_type.hasZvalues() ? 3 : 2;
SHP_xyz_points = new double[SHP_num_points][countDimensions];
Coordinate[] points = geom.getCoordinates();
for(int i=0; i < SHP_num_points; i++)
{
SHP_xyz_points[i][0] = points[i].x;
SHP_xyz_points[i][1] = points[i].y;
// if SHAPE-TYPE: 15
if (shape_type.hasZvalues())
{
SHP_xyz_points[i][2] = points[i].z;
}
}
computeLengthOfContent();
}
/**
* get the number of points(vertices).
*
* @return the number of points(vertices).
*/
public int getNumberOfPoints()
{
return SHP_num_points;
}
/**
* get the number of parts(Polygons)
*
* @return the number of parts(Polygons).
*/
public int getNumberOfParts()
{
return SHP_num_parts;
}
/**
* get an array of all points(vertices).
*
* @return an array of all points(vertices).
*/
public double[][] getPoints()
{
return SHP_xyz_points;
}
@Override
public void print()
{
System.out.printf(Locale.ENGLISH, " _ _ _ _ _ \n");
System.out.printf(Locale.ENGLISH, " / SHAPE \\_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n");
System.out.printf(Locale.ENGLISH, " | \\\n");
System.out.printf(Locale.ENGLISH, " | <RECORD HEADER>\n");
System.out.printf(Locale.ENGLISH, " | SHP_record_number = %d\n", SHP_record_number);
System.out.printf(Locale.ENGLISH, " | SHP_content_length = %d bytes (check: start/end/size = %d/%d/%d)\n", SHP_content_length*2, position_start, position_end, content_length);
System.out.printf(Locale.ENGLISH, " |\n");
System.out.printf(Locale.ENGLISH, " | <RECORD CONTENT>\n");
System.out.printf(Locale.ENGLISH, " | shape_type = %s (%d)\n", shape_type, shape_type.ID() );
System.out.printf(Locale.ENGLISH, " | SHP_bbox: xmin, xmax = %+7.3f, %+7.3f\n", SHP_bbox[0][0], SHP_bbox[0][1]);
System.out.printf(Locale.ENGLISH, " | SHP_bbox: ymin, ymax = %+7.3f, %+7.3f\n", SHP_bbox[1][0], SHP_bbox[1][1]);
System.out.printf(Locale.ENGLISH, " | SHP_bbox: zmin, zmax = %+7.3f, %+7.3f\n", SHP_bbox[2][0], SHP_bbox[2][1]);
System.out.printf(Locale.ENGLISH, " | SHP_measure: mmin, mmax = %+7.3f, %+7.3f\n", SHP_range_m[0], SHP_range_m[1]);
System.out.printf(Locale.ENGLISH, " | SHP_num_parts = %d\n", SHP_num_parts );
System.out.printf(Locale.ENGLISH, " | SHP_num_points = %d\n", SHP_num_points );
// for(int i = 0; i < SHP_num_parts; i++){
// System.out.printf(Locale.ENGLISH, " | part_idx[%d] = %d\n", i, SHP_parts[i] );
// }
//
System.out.printf(Locale.ENGLISH, " \\_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /\n");
}
/**
* get the BoundingBox..<br>
* data storage: [x, y, z][min, max] <br>
*
* @return 2d-array (double), dim-size:[3][2]
*/
public double[][] getBoundingBox()
{
return SHP_bbox;
}
/**
* get range of Measure-Values.<br>
* data storage: [min, max] <br>
*
* @return 1d-array (double), dim-size:[2]
*/
public double[] getMeasureRange()
{
return SHP_range_m;
}
/**
* generates a list of polygons or polylines, and returns a 3d-double array.<br>
* [number of poly*][number of points per poly*][x, y, z, m].
*
* @return 3d-double array.
*/
public double[][][] getPointsAs3DArray()
{
// if the method was called before, we already have the array.
if (parts != null)
{
return parts;
}
int[] indices = new int[SHP_num_parts + 1]; // generate new indices
// array
System.arraycopy(SHP_parts, 0, indices, 0, SHP_num_parts); // copy start
// indices
indices[indices.length - 1] = SHP_num_points; // and add last index
parts = new double[SHP_num_parts][][];
for (int i = 0; i < indices.length - 1; i++)
{
int from = indices[i]; // start index
int to = indices[i + 1]; // end-index + 1
int size = to - from;
parts[i] = new double[size][4];
for (int j = from, idx = 0; j < to; j++, idx++)
{
parts[i][idx][0] = SHP_xyz_points[j][0]; // copy of x-value
parts[i][idx][1] = SHP_xyz_points[j][1]; // copy of y-value
parts[i][idx][2] = SHP_xyz_points[j][2]; // copy of z-value
if (shape_type.hasMvalues())
{
parts[i][idx][3] = SHP_m_values[j]; // copy of m-value
}
}
}
return parts;
}
/**
* get the Measure Values as an Array.
*
* @return measure-values. (size=.getNumberOfPoints()).
*/
public double[] getMeasureValues()
{
return SHP_m_values;
}
}
|
gpl-3.0
|
thomasfannes/gf2algebra
|
gf2Algebra/gf256.hpp
|
1942
|
/*******************************************************************
* Copyright (c) 2010-2013 MiGraNT - DTAI.cs.kuleuven.be
* License details in the root directory of this distribution in
* the LICENSE file
********************************************************************/
#ifndef GF2ALGEBRA_GF256_HPP
#define GF2ALGEBRA_GF256_HPP
#include <string>
namespace gf2Algebra {
/*
* Element of the Galois Field of size 2^N = GF(256)
*/
class GF256
{
public:
typedef unsigned char storage_type;
static const std::size_t CHARACTERISTIC = 2;
static const std::size_t POWER = 8;
static const std::size_t ORDER = 256;
// constructors
GF256() : _m(0) { }
explicit GF256(storage_type m) : _m(m){ }
GF256(const GF256 & rhs) : _m(rhs._m) { }
// assignment operator
GF256 & operator=(const GF256 & rhs);
// addition assignment
GF256 & operator+=(const GF256 & rhs) { _m ^= rhs._m; return *this; }
GF256 & operator-=(const GF256 & rhs) { _m ^= rhs._m; return *this; }
// addition and multiplication
GF256 operator+(const GF256 & rhs) const { return GF256(_m ^ rhs._m); }
GF256 operator-(const GF256 & rhs) const { return GF256(_m ^ rhs._m); }
GF256 operator*(const GF256 & rhs) const;
// equality
bool operator==(const GF256 & rhs) const { return _m == rhs._m; }
bool operator!=(const GF256 & rhs) const { return _m != rhs._m; }
// information functions
std::string polyRepresentation() const;
storage_type integralRepresentation() const { return _m; }
static const GF256 zero;
// swap function for efficient use in stl
friend void swap(GF256 & lhs, GF256 & rhs) { std::swap(lhs._m, rhs._m); }
private:
storage_type _m;
};
std::ostream & operator<<(std::ostream & stream, const GF256 & element);
} // gf2Algebra namespace
#endif // GF2ALGEBRA_GF256_HPP
|
gpl-3.0
|
00-Evan/shattered-pixel-dungeon-gdx
|
core/src/com/shatteredpixel/shatteredpixeldungeon/items/stones/StoneOfIntuition.java
|
8809
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.stones;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.effects.Identification;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfExperience;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfFrost;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHaste;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHealing;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfInvisibility;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfLevitation;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfLiquidFlame;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfMindVision;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfParalyticGas;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfPurity;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfStrength;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfToxicGas;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.exotic.ExoticPotion;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.Scroll;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfIdentify;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfLullaby;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfMagicMapping;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfMirrorImage;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRage;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRecharging;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRemoveCurse;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRetribution;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTeleportation;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTerror;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTransmutation;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfUpgrade;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.exotic.ExoticScroll;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.IconButton;
import com.shatteredpixel.shatteredpixeldungeon.ui.RedButton;
import com.shatteredpixel.shatteredpixeldungeon.ui.RenderedTextBlock;
import com.shatteredpixel.shatteredpixeldungeon.ui.Window;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.shatteredpixel.shatteredpixeldungeon.windows.IconTitle;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndBag;
import com.watabou.noosa.Image;
import java.util.HashSet;
public class StoneOfIntuition extends InventoryStone {
{
mode = WndBag.Mode.UNIDED_POTION_OR_SCROLL;
image = ItemSpriteSheet.STONE_INTUITION;
}
@Override
protected void onItemSelected(Item item) {
GameScene.show( new WndGuess(item));
}
//in order of their consumable icon
public static Class[] potions = new Class[]{
PotionOfExperience.class,
PotionOfFrost.class,
PotionOfHaste.class,
PotionOfHealing.class,
PotionOfInvisibility.class,
PotionOfLevitation.class,
PotionOfLiquidFlame.class,
PotionOfMindVision.class,
PotionOfParalyticGas.class,
PotionOfPurity.class,
PotionOfStrength.class,
PotionOfToxicGas.class
};
public static Class[] scrolls = new Class[]{
ScrollOfIdentify.class,
ScrollOfLullaby.class,
ScrollOfMagicMapping.class,
ScrollOfMirrorImage.class,
ScrollOfRetribution.class,
ScrollOfRage.class,
ScrollOfRecharging.class,
ScrollOfRemoveCurse.class,
ScrollOfTeleportation.class,
ScrollOfTerror.class,
ScrollOfTransmutation.class,
ScrollOfUpgrade.class
};
static Class curGuess = null;
public class WndGuess extends Window {
private static final int WIDTH = 120;
private static final int BTN_SIZE = 20;
public WndGuess(final Item item){
IconTitle titlebar = new IconTitle();
titlebar.icon( new ItemSprite(ItemSpriteSheet.STONE_INTUITION, null) );
titlebar.label( Messages.get(StoneOfIntuition.class, "name") );
titlebar.setRect( 0, 0, WIDTH, 0 );
add( titlebar );
RenderedTextBlock text = PixelScene.renderTextBlock(6);
text.text( Messages.get(this, "text") );
text.setPos(0, titlebar.bottom());
text.maxWidth( WIDTH );
add(text);
final RedButton guess = new RedButton(""){
@Override
protected void onClick() {
super.onClick();
useAnimation();
if (item.getClass() == curGuess){
item.identify();
GLog.p( Messages.get(WndGuess.class, "correct") );
curUser.sprite.parent.add( new Identification( curUser.sprite.center().offset( 0, -16 ) ) );
} else {
GLog.n( Messages.get(WndGuess.class, "incorrect") );
}
curGuess = null;
hide();
}
};
guess.visible = false;
guess.icon( new ItemSprite(item) );
guess.enable(false);
guess.setRect(0, 80, WIDTH, 20);
add(guess);
float left;
float top = text.bottom() + 5;
int rows;
int placed = 0;
HashSet<Class<?extends Item>> unIDed = new HashSet<>();
final Class[] all;
final int row;
if (item.isIdentified()){
hide();
return;
} else if (item instanceof Potion){
unIDed.addAll(Potion.getUnknown());
all = potions.clone();
if (item instanceof ExoticPotion){
row = 8;
for (int i = 0; i < all.length; i++){
all[i] = ExoticPotion.regToExo.get(all[i]);
}
HashSet<Class<?extends Item>> exoUID = new HashSet<>();
for (Class<?extends Item> i : unIDed){
exoUID.add(ExoticPotion.regToExo.get(i));
}
unIDed = exoUID;
} else {
row = 0;
}
} else if (item instanceof Scroll){
unIDed.addAll(Scroll.getUnknown());
all = scrolls.clone();
if (item instanceof ExoticScroll){
row = 24;
for (int i = 0; i < all.length; i++){
all[i] = ExoticScroll.regToExo.get(all[i]);
}
HashSet<Class<?extends Item>> exoUID = new HashSet<>();
for (Class<?extends Item> i : unIDed){
exoUID.add(ExoticScroll.regToExo.get(i));
}
unIDed = exoUID;
} else {
row = 16;
}
} else {
hide();
return;
}
if (unIDed.size() < 6){
rows = 1;
top += BTN_SIZE/2f;
left = (WIDTH - BTN_SIZE*unIDed.size())/2f;
} else {
rows = 2;
left = (WIDTH - BTN_SIZE*((unIDed.size()+1)/2))/2f;
}
for (int i = 0; i < all.length; i++){
if (!unIDed.contains(all[i])) {
continue;
}
final int j = i;
IconButton btn = new IconButton(){
@Override
protected void onClick() {
curGuess = all[j];
guess.visible = true;
guess.text( Messages.get(curGuess, "name") );
guess.enable(true);
super.onClick();
}
};
Image im = new Image(Assets.CONS_ICONS, 7*i, row, 7, 8);
im.scale.set(2f);
btn.icon(im);
btn.setRect(left + placed*BTN_SIZE, top, BTN_SIZE, BTN_SIZE);
add(btn);
placed++;
if (rows == 2 && placed == ((unIDed.size()+1)/2)){
placed = 0;
if (unIDed.size() % 2 == 1){
left += BTN_SIZE/2f;
}
top += BTN_SIZE;
}
}
resize(WIDTH, 100);
}
@Override
public void onBackPressed() {
super.onBackPressed();
new StoneOfIntuition().collect();
}
}
}
|
gpl-3.0
|
ddeeps2610/NLP_PA2_QA
|
src/qa/QuestionProcessing/IQuestionReader.java
|
264
|
/**
*
*/
package qa.QuestionProcessing;
import java.util.LinkedList;
import qa.IQuestion;
/**
* @author Deepak
*
*/
public interface IQuestionReader {
public LinkedList<IQuestion> readQuestions();
public void classifyQuestions();
}
|
gpl-3.0
|
jakenjarvis/ChatLoggerPlus
|
src/com/tojc/minecraft/mod/ChatLogger/Plugin/Order/PluginOrderStatus.java
|
5143
|
/*
* ChatLoggerPlus (Minecraft MOD)
*
* Copyright (C) 2012 Members of the ChatLoggerPlus 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 com.tojc.minecraft.mod.ChatLogger.Plugin.Order;
import net.minecraft.util.EnumChatFormatting;
import com.tojc.minecraft.mod.ChatLogger.Plugin.PluginState;
import com.tojc.minecraft.mod.ChatLogger.Plugin.Implements.v1.PluginInformation;
import com.tojc.minecraft.mod.ChatLogger.Plugin.Type.PluginType;
public class PluginOrderStatus
{
private PluginType type = null;
private PluginOrderKey key = null;
private PluginInformation plugin = null;
public PluginOrderStatus(PluginType type, PluginOrderKey key, PluginInformation plugin)
{
this.type = type;
this.key = key;
this.plugin = plugin;
if(this.isError())
{
this.key.setState(PluginState.Error);
}
}
public boolean isError()
{
return !((this.plugin != null) && (this.plugin.isEnabled()));
}
public PluginType getPluginType()
{
return this.type;
}
public PluginOrderKey getPluginOrderKey()
{
return this.key;
}
public PluginInformation getPlugin()
{
return this.plugin;
}
public void setPlugin(PluginInformation plugin)
{
this.plugin = plugin;
}
public PluginState getPluginState()
{
return this.key.getState();
}
public void setPluginState(PluginState state)
{
this.key.setState(state);
}
public boolean isEnabled()
{
return this.key.getState().getCode();
}
public void setEnabled(boolean enabled)
{
if(!this.isError())
{
switch(this.key.getState())
{
case Disabled:
case Enabled:
if(enabled)
{
this.key.setState(PluginState.Enabled);
}
else
{
this.key.setState(PluginState.Disabled);
}
break;
case Error:
break;
default:
break;
}
}
else
{
switch(this.key.getState())
{
case Disabled:
case Enabled:
this.key.setState(PluginState.Error);
break;
case Error:
break;
default:
break;
}
}
}
public String makePermissionString(boolean inColorCode)
{
StringBuilder result = new StringBuilder();
String colorDefault = "";
String colorWriteStackTitle = "";
String colorReadStackTitle = "";
String colorMessageModification = "";
String colorAddAfterMessage = "";
String colorWriteStack = "";
String colorReadStack = "";
if(inColorCode)
{
colorDefault = "" + EnumChatFormatting.GRAY;
colorWriteStackTitle = "" + EnumChatFormatting.DARK_PURPLE;
colorReadStackTitle = "" + EnumChatFormatting.DARK_AQUA;
colorMessageModification = "" + EnumChatFormatting.YELLOW;
colorAddAfterMessage = "" + EnumChatFormatting.GREEN;
colorWriteStack = "" + EnumChatFormatting.LIGHT_PURPLE;
colorReadStack = "" + EnumChatFormatting.AQUA;
}
boolean messageModification = plugin.getSettings().getMessageModification();
boolean addAfterMessage = plugin.getSettings().getAddAfterMessage();
String writeStack = plugin.getSettings().makeWriteStackListString();
String readStack = plugin.getSettings().makeReadStackListString();
if((!messageModification) && (!addAfterMessage) && (writeStack.length() <= 0) && (readStack.length() <= 0))
{
result.append(colorDefault);
result.append(" This does not use the permission.");
}
else
{
boolean separator = false;
result.append(colorDefault);
result.append("Permission: ");
if(messageModification)
{
if(separator)
{
result.append(colorDefault);
result.append(", ");
separator = false;
}
result.append(colorMessageModification);
result.append("Modify");
separator = true;
}
if(addAfterMessage)
{
if(separator)
{
result.append(colorDefault);
result.append(", ");
separator = false;
}
result.append(colorAddAfterMessage);
result.append("Add");
separator = true;
}
if(writeStack.length() >= 1)
{
if(separator)
{
result.append(colorDefault);
result.append(", ");
separator = false;
}
result.append(colorWriteStackTitle);
result.append("WS/");
result.append(colorWriteStack);
result.append(writeStack);
separator = true;
}
if(readStack.length() >= 1)
{
if(separator)
{
result.append(colorDefault);
result.append(", ");
separator = false;
}
result.append(colorReadStackTitle);
result.append("RS/");
result.append(colorReadStack);
result.append(readStack);
separator = true;
}
}
return result.toString();
}
}
|
gpl-3.0
|
anarang/robottelo
|
robottelo/cli/proxy.py
|
3221
|
# -*- encoding: utf-8 -*-
"""
Usage::
hammer proxy [OPTIONS] SUBCOMMAND [ARG] ...
Parameters::
SUBCOMMAND subcommand
[ARG] ... subcommand arguments
Subcommands::
create Create a smart proxy.
delete Delete a smart_proxy.
import_classes Import puppet classes from puppet proxy.
info Show a smart proxy.
list List all smart_proxies.
refresh-features Refresh smart proxy features
update Update a smart proxy.
"""
import contextlib
import logging
from robottelo import ssh
from robottelo.cli.base import Base
from robottelo.config import settings
from time import sleep
class SSHTunnelError(Exception):
"""Raised when ssh tunnel creation fails."""
@contextlib.contextmanager
def default_url_on_new_port(oldport, newport):
"""Creates context where the default smart-proxy is forwarded on a new port
REQUIRES GatewayPorts yes in sshd_config
:param int oldport: Port to be forwarded.
:param int newport: New port to be used to forward `oldport`.
:return: A string containing the new capsule URL with port.
:rtype: str
"""
logger = logging.getLogger('robottelo')
command_timeout = 2
domain = settings.server.hostname
user = settings.server.ssh_username
key = settings.server.ssh_key
ssh.upload_file(key, '/tmp/dsa_{0}'.format(newport))
ssh.command('chmod 700 /tmp/dsa_{0}'.format(newport))
with ssh._get_connection() as connection:
command = (
u'ssh -i {0} -o StrictHostKeyChecking=no -R {1}:{2}:{3} {4}@{5}'
).format(
'/tmp/dsa_{0}'.format(newport),
newport, domain, oldport, user, domain)
logger.debug('Creating tunnel {0}'.format(command))
transport = connection.get_transport()
channel = transport.open_session()
channel.exec_command(command)
# if exit_status appears until command_timeout, throw error
for _ in range(command_timeout):
if channel.exit_status_ready():
if channel.recv_exit_status() != 0:
stderr = u''
while channel.recv_stderr_ready():
stderr += channel.recv_stderr(1)
logger.debug('Tunnel failed: {0}'.format(stderr))
# Something failed, so raise an exception.
raise SSHTunnelError(stderr)
sleep(1)
yield 'https://{0}:{1}'.format(domain, newport)
ssh.command('rm -f /tmp/dsa_{0}'.format(newport))
class Proxy(Base):
"""Manipulates Foreman's smart proxies. """
command_base = 'proxy'
@classmethod
def importclasses(cls, options=None):
"""Import puppet classes from puppet proxy."""
cls.command_sub = 'import-classes'
return cls.execute(cls._construct_command(options))
@classmethod
def refresh_features(cls, options=None):
"""Refreshes smart proxy features"""
cls.command_sub = 'refresh-features'
return cls.execute(cls._construct_command(options))
|
gpl-3.0
|
srinivasanmit/all-in-all
|
codewars/find_next_square.py
|
555
|
import math
def find_next_square(n) :
sqrt_of_n = int(math.sqrt(n))
return (sqrt_of_n+1)**2 if sqrt_of_n ** 2 == n else -1
print find_next_square(121)
print find_next_square(625)
print find_next_square(114)
print find_next_square(319225)
print find_next_square(15241383936)
print find_next_square(155)
print find_next_square(342786627)
'''
def find_next_square(sq):
root = sq ** 0.5
if root.is_integer():
return (root + 1)**2
return -1
def find_next_square(sq):
x = sq**0.5
return -1 if x % 1 else (x+1)**2
'''
|
gpl-3.0
|
peterfuture/dttv-android
|
dttv/dttv-samples/src/main/java/dttv/app/frament/LocalVideoFragment.java
|
5487
|
package dttv.app.frament;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import butterknife.BindView;
import dttv.app.R;
import dttv.app.base.SimpleFragment;
import dttv.app.utils.DateUtils;
import dttv.app.utils.FileNewUtils;
import dttv.app.utils.Log;
import dttv.app.utils.PlayerUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class LocalVideoFragment extends SimpleFragment {
@BindView(R.id.local_video_list)
ListView localVideoListView;
private Cursor videocursor;
private int video_column_index;
int count;
@Override
protected int getLayoutId() {
return R.layout.fragment_local_video;
}
@Override
protected void initEventAndData() {
initVideos();
}
public LocalVideoFragment() {
// Required empty public constructor
}
private void initVideos() {
//System.gc();
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATE_MODIFIED,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DEFAULT_SORT_ORDER
};
videocursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = videocursor.getCount();
Log.i(TAG,"count is:"+count);
localVideoListView.setAdapter(new VideoAdapter(getActivity().getApplicationContext()));
localVideoListView.setOnItemClickListener(videogridlistener);
}
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(vContext).inflate(R.layout.dt_video_item,null);
viewHolder.nameTxt = (TextView) convertView.findViewById(R.id.media_row_name);
viewHolder.dateTxt = (TextView) convertView.findViewById(R.id.media_row_date);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.media_row_icon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
String name = videocursor.getString(video_column_index);
viewHolder.nameTxt.setText(name);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED);
String date = videocursor.getString(video_column_index);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
String size = videocursor.getString(video_column_index);
try {
viewHolder.dateTxt.setText(DateUtils.getInstanse().getmstodate(Long.parseLong(date+"000"), DateUtils.YYYYMMDDHHMMSS
) + " " + FileNewUtils.getInstance().FormetFileSize(Long.parseLong(size)));
videocursor.moveToPosition(position);
}catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
class ViewHolder{
ImageView imageView;
TextView nameTxt;
TextView dateTxt;
}
}
private AdapterView.OnItemClickListener videogridlistener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filePathName = videocursor.getString(video_column_index);
String fileName = "";
try {
File file = new File(filePathName);
if (file.exists()){
fileName = file.getName();
}
}catch (Exception e){
e.printStackTrace();
}
PlayerUtil.getInstance().beginToPlayer(getActivity(),filePathName,fileName,1);
//Toast.makeText(getActivity().getApplicationContext(), filePathName, Toast.LENGTH_SHORT).show();
}
};
@Override
public void onDestroy() {
super.onDestroy();
videocursor.close();
}
}
|
gpl-3.0
|
KermitCode/keframe-php.framework
|
keframe/corehelp/KermitCode.class.php
|
4143
|
<?php
/*************************
*Note: :生成验证码类
*Author :Kermit
*QQ :956952515
*note :中国.山东.青岛
*date :2014-12
keframe:仅为自己方便而写,不做为对外应用.
格言:适合自己的就是最好的!我只为自己代言。
************************/
#控制器中调用示例:$this->KE('kermitCode')->makecode(2,5,50,30)->createcode();
class KermitCode{
private $codetype; //验证码类别 1,四位数字 2,字母 3,字母加数字 4,汉字验证码
private $area=array(40,18); //验证码的长宽数组
private $codenum; //验证码位数
public $code;
/*************************
以前写的程序放此保存
************************/
public function makecode($codetype=1,$codenum=4,$area_wid=40,$area_heig=18){
$this->codetype=$codetype;
$this->codenum=$codenum;
if($area_wid && $area_heig){$this->area=array($area_wid,$area_heig);}
return $this;
}
/*************************
验证码检验
************************/
public function checkCode($code){
if($code==$_SESSION["code"]) return true;
else return false;
}
/*************************
创建验证码
************************/
public function createcode(){
$codetype=$this->codetype;
$codenum=$this->codenum;
switch($codetype){
case 1:$codechar=$this->makechar_num($codenum);break;
case 2:$codechar=$this->makechar_letter($codenum);break;
case 3:$codechar=$this->makechar_mix($codenum);break;
case 4:$codechar=$this->makechar_chinese($codenum);break;
default:$codechar=$this->makechar_num($codenum);break;
}
Header("Content-type: image/png");
$_SESSION["code"]=$codechar;
$area=$this->area;
$im=imagecreate($area[0],$area[1]) or die("Cannot Initialize new GD image stream");//生成一个长40高18的图片
$black=imagecolorallocate($im,255,255,255);
$white=imagecolorallocate($im,0,0,0);
$white1=imagecolorallocate($im,215,55,155);//定义字体颜色
if($codetype=='4'){
$font=FRAMEPATH.'coreAsset/font/kermitcode.ttf';
imagettftext($im,12,0,2,15,$white1,$font,$codechar);
}else imagestring($im,5,3,2,$codechar,$white1);
$white1=imagecolorallocate($im,200,55,150);//定义干扰颜色
imageline($im,rand(0,10), rand(0,10), rand($area[0]/2,$area[0]), rand($area[1]/2,$area[1]),$white1);
for($i=0;$i<20;$i++){ //加入干扰象素
imagesetpixel($im,(rand(0,100)*$area[0])/100,(rand(0,100)*$area[1])/100,$black);
}
imagepng($im);
imagedestroy($im);
}//end function--2
public function makechar_num($codenum){
return substr(rand(1000000,9999999),0,$codenum);
}//end function--3
public function makechar_letter($codenum){
$letter='abcdefghijklmnopqrstuvwxyz';
$letter_char='';
for($i=0;$i<$codenum;$i++) $letter_char.=$letter[rand(0,25)];
return $letter_char;
}//end function--4
public function makechar_mix($codenum){
$letter='0123456789abcdefghijklmnopqrstuvwxyz';
$letter_char='';
for($i=0;$i<$codenum;$i++) $letter_char.=$letter[rand(0,35)];
return $letter_char;
}//end function--5
public function makechar_chinese($codenum){
$letter=array('大','小','多','少','工','人','车','马','左','右','上','下','关','云','太','阳','子','爸','妈','爷','奶',
'一','二','三','四','五','六','七','八','九','十','牛','今','天','金','木','水','火','土','红','色','衣',
'花','士','失','母','哭','笑','苦','兴','未','来','生','日','月','方','中','后','开','会','内','在','白',
'各','国','有','足','手','头','公','共','去','口','心','非','回','东','南','西','北','电','闪','雷','星',
'不','过','这','那','什','么','田','用','元','发','又','及','早','出','厂','长','合','女','年','岁','见');
$letter_char='';
for($i=0;$i<$codenum;$i++) $letter_char.=$letter[rand(0,104)];
return $letter_char;
}//end function--6
}//end class
?>
|
gpl-3.0
|
VinyPinheiro/DeManS
|
system/tests/MemberTest.java
|
5278
|
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import exception.AddressException;
import exception.MemberException;
import exception.UfException;
import junit.framework.TestCase;
import model.Address;
import model.Member;
import model.UF;
public class MemberTest extends TestCase {
private Member member;
private Integer id;
private String name;
private Date birthdate;
private String password;
private String phone;
private String dad_phone;
private Address address;
private String degree;
private String situation;
protected void setUp() throws UfException, AddressException, ParseException {
id = 44199;
name = "Vinicius Pinheiro da Silva Correa";
birthdate = new SimpleDateFormat("dd/MM/yyyy").parse("14/02/1995");
password = "1234567";
phone = "(61)98145-8085";
dad_phone = "(61)98145-8085";
degree = "DeMolay";
situation = "Ativo";
String street = "Rua dos alveneiros";
Integer number = 25;
String complement = "A2065";
String zipcode = "11520-000";
String city = "Santos";
UF uf = new UF(UF.STATES[2][0]);
address = new Address(street, number, complement, zipcode, city, uf);
}
public void testCreateMember() throws MemberException {
member = new Member(id, name, birthdate, password, phone, dad_phone, address);
assertEquals(member.getId(), id);
assertEquals(member.getName(), name);
assertEquals(member.getBirthdate(), birthdate);
assertEquals(member.getPassword(), password);
assertEquals(member.getPhone(), phone);
assertEquals(member.getDad_phone(), dad_phone);
assertEquals(member.getAddress(), address);
}
public void testCreateMemberWithDegreeAndSituation() throws MemberException {
member = new Member(id, name, birthdate, password, phone, dad_phone, address,degree,situation);
assertEquals(member.getId(), id);
assertEquals(member.getName(), name);
assertEquals(member.getBirthdate(), birthdate);
assertEquals(member.getPassword(), password);
assertEquals(member.getPhone(), phone);
assertEquals(member.getDad_phone(), dad_phone);
assertEquals(member.getAddress(), address);
assertEquals(member.getDegree(), degree);
assertEquals(member.getSituation(), situation);
}
public void testNullID() {
try {
member = new Member(null, name, birthdate, password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNegativeID() {
try {
member = new Member(-615, name, birthdate, password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNullName() {
try {
member = new Member(id, null, birthdate, password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testLargeName() {
try {
member = new Member(id,
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
birthdate, password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNullBirthdate() {
try {
member = new Member(id, name, null, password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testInvaidBirthdate() {
try {
member = new Member(id, name, Calendar.getInstance().getTime(), password, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNullPassword() {
try {
member = new Member(id, name, birthdate, null, phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testPasswordLess6Characters() {
try {
member = new Member(id, name, birthdate, "12", phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testPasswordMore20Characters() {
try {
member = new Member(id, name, birthdate, "012345678901234567891", phone, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNullPhone() {
try {
member = new Member(id, name, birthdate, password, null, dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testInvalidPhone() {
try {
member = new Member(id, name, birthdate, password, "(13) 988452000", dad_phone, address);
fail();
} catch (MemberException e) {
}
}
public void testNullDadPhone() {
try {
member = new Member(id, name, birthdate, password, phone, null, address);
fail();
} catch (MemberException e) {
}
}
public void testInvalidDadPhone() {
try {
member = new Member(id, name, birthdate, password, phone,"(13) 988452000", address);
fail();
} catch (MemberException e) {
}
}
public void testNullAddress() {
try {
member = new Member(id, name, birthdate, password, phone, dad_phone, null);
fail();
} catch (MemberException e) {
}
}
public void testInvalidDegree() {
try {
member = new Member(id, name, birthdate, password, phone, dad_phone, address,"ciático",situation);
fail();
} catch (MemberException e) {
}
}
public void testInvalidsituation() {
try {
member = new Member(id, name, birthdate, password, phone, dad_phone, address,degree,"reg");
fail();
} catch (MemberException e) {
}
}
}
|
gpl-3.0
|
plusend/DiyCode
|
app/src/main/java/com/plusend/diycode/util/PrefUtil.java
|
7521
|
package com.plusend.diycode.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.plusend.diycode.model.user.entity.Token;
import com.plusend.diycode.model.user.entity.UserDetailInfo;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
* 偏好参数存储工具类
*/
public class PrefUtil {
private static volatile PrefUtil prefUtil;
private SharedPreferences mSharedPreferences;
private Editor mEditor;
private PrefUtil(Context context, String name) {
mSharedPreferences =
context.getApplicationContext().getSharedPreferences(name, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
}
public static PrefUtil getInstance(Context context, String name) {
if (prefUtil == null) {
synchronized (PrefUtil.class) {
if (prefUtil == null) {
prefUtil = new PrefUtil(context, name);
}
}
}
return prefUtil;
}
/**
* 存储登录 Token
*/
public static void saveToken(Context context, Token token) {
Constant.VALUE_TOKEN = token.getAccessToken();
try {
token.setAccessToken(
KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getAccessToken()));
token.setTokenType(
KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getTokenType()));
token.setRefreshToken(
KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getRefreshToken()));
} catch (InvalidKeyException | BadPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | UnrecoverableEntryException | KeyStoreException | IOException | NoSuchPaddingException | CertificateException e) {
e.printStackTrace();
Constant.VALUE_TOKEN = "";
return;
}
PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME);
prefUtil.putString(Constant.Token.ACCESS_TOKEN, token.getAccessToken());
prefUtil.putString(Constant.Token.TOKEN_TYPE, token.getTokenType());
prefUtil.putInt(Constant.Token.EXPIRES_IN, token.getExpiresIn());
prefUtil.putString(Constant.Token.REFRESH_TOKEN, token.getRefreshToken());
prefUtil.putInt(Constant.Token.CREATED_AT, token.getCreatedAt());
}
/**
* 获取登录 Token
*/
public static Token getToken(Context context) {
PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME);
Token token = new Token();
token.setAccessToken(prefUtil.getString(Constant.Token.ACCESS_TOKEN, ""));
token.setTokenType(prefUtil.getString(Constant.Token.TOKEN_TYPE, ""));
token.setExpiresIn(prefUtil.getInt(Constant.Token.EXPIRES_IN, 0));
token.setRefreshToken(prefUtil.getString(Constant.Token.REFRESH_TOKEN, ""));
token.setCreatedAt(prefUtil.getInt(Constant.Token.CREATED_AT, 0));
try {
token.setAccessToken(
KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getAccessToken()));
token.setTokenType(
KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getTokenType()));
token.setRefreshToken(
KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getRefreshToken()));
} catch (InvalidKeyException | BadPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | UnrecoverableEntryException | KeyStoreException | IOException | NoSuchPaddingException | CertificateException e) {
e.printStackTrace();
}
Constant.VALUE_TOKEN = token.getAccessToken();
return token;
}
/**
* 存储登录信息
*/
public static void saveMe(Context context, UserDetailInfo userDetailInfo) {
PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME);
prefUtil.putString(Constant.User.LOGIN, userDetailInfo.getLogin());
prefUtil.putString(Constant.User.AVATAR_URL, userDetailInfo.getAvatarUrl());
prefUtil.putString(Constant.User.EMAIL, userDetailInfo.getEmail());
}
/**
* 获取登录信息
*/
public static UserDetailInfo getMe(Context context) {
PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME);
UserDetailInfo userDetailInfo = new UserDetailInfo();
userDetailInfo.setLogin(prefUtil.getString(Constant.User.LOGIN, ""));
userDetailInfo.setAvatarUrl(prefUtil.getString(Constant.User.AVATAR_URL, ""));
userDetailInfo.setEmail(prefUtil.getString(Constant.User.EMAIL, ""));
return userDetailInfo;
}
/**
* 清理登录信息
*/
public static void clearMe(Context context) {
PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME);
// User
prefUtil.putString(Constant.User.LOGIN, "");
prefUtil.putString(Constant.User.AVATAR_URL, "");
prefUtil.putString(Constant.User.EMAIL, "");
// Token
prefUtil.putString(Constant.Token.ACCESS_TOKEN, "");
prefUtil.putString(Constant.Token.TOKEN_TYPE, "");
prefUtil.putInt(Constant.Token.EXPIRES_IN, -1);
prefUtil.putString(Constant.Token.REFRESH_TOKEN, "");
prefUtil.putInt(Constant.Token.CREATED_AT, -1);
Constant.VALUE_TOKEN = "";
}
public SharedPreferences getSP() {
return mSharedPreferences;
}
public Editor getEditor() {
return mEditor;
}
/**
* 存储数据(Long)
*/
public void putLong(String key, long value) {
mEditor.putLong(key, value).apply();
}
/**
* 存储数据(Int)
*/
public void putInt(String key, int value) {
mEditor.putInt(key, value).apply();
}
/**
* 存储数据(String)
*/
public void putString(String key, String value) {
mEditor.putString(key, value).apply();
}
/**
* 存储数据(boolean)
*/
public void putBoolean(String key, boolean value) {
mEditor.putBoolean(key, value).apply();
}
/**
* 取出数据(Long)
*/
public long getLong(String key, long defValue) {
return mSharedPreferences.getLong(key, defValue);
}
/**
* 取出数据(int)
*/
public int getInt(String key, int defValue) {
return mSharedPreferences.getInt(key, defValue);
}
/**
* 取出数据(boolean)
*/
public boolean getBoolean(String key, boolean defValue) {
return mSharedPreferences.getBoolean(key, defValue);
}
/**
* 取出数据(String)
*/
public String getString(String key, String defValue) {
return mSharedPreferences.getString(key, defValue);
}
/**
* 清空所有数据
*/
public void clear() {
mEditor.clear().apply();
}
/**
* 移除指定数据
*/
public void remove(String key) {
mEditor.remove(key).apply();
}
}
|
gpl-3.0
|
cSploit/android.MSF
|
lib/anemone/storage.rb
|
882
|
module Anemone
module Storage
def self.Hash(*args)
hash = Hash.new(*args)
# add close method for compatibility with Storage::Base
class << hash; def close; end; end
hash
end
def self.PStore(*args)
require 'anemone/storage/pstore'
self::PStore.new(*args)
end
def self.TokyoCabinet(file = 'anemone.tch')
require 'anemone/storage/tokyo_cabinet'
self::TokyoCabinet.new(file)
end
def self.MongoDB(mongo_db = nil, collection_name = 'pages')
require 'anemone/storage/mongodb'
mongo_db ||= Mongo::Connection.new.db('anemone')
raise "First argument must be an instance of Mongo::DB" unless mongo_db.is_a?(Mongo::DB)
self::MongoDB.new(mongo_db, collection_name)
end
def self.Redis(opts = {})
require 'anemone/storage/redis'
self::Redis.new(opts)
end
end
end
|
gpl-3.0
|
MaxTyutyunnikov/lino
|
lino/utils/dataserializer.py
|
4365
|
## Copyright 2009 Luc Saffre
## This file is part of the Lino project.
## Lino 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.
## Lino 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 Lino; if not, see <http://www.gnu.org/licenses/>.
"""
YAML serializer.
Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
"""
from StringIO import StringIO
import yaml
try:
import decimal
except ImportError:
from django.utils import _decimal as decimal # Python 2.3 fallback
from django.core.serializers import base
from django.db import models
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer as PythonDeserializer
class DjangoSafeDumper(yaml.SafeDumper):
def represent_decimal(self, data):
return self.represent_scalar('tag:yaml.org,2002:str', str(data))
DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal)
class FakeDeserializedObject(base.DeserializedObject):
"""loaddata requires DeserializedObject instances,
but this Deserializer does *not* bypass pre_save/save methods.
"""
def __init__(self, obj):
self.object = obj
def save(self, save_m2m=True):
self.object.save()
# my code
from lino.utils.instantiator import Instantiator
class Serializer(PythonSerializer):
internal_use_only = False
#~ """
#~ Convert a queryset to YAML.
#~ """
#~ def handle_field(self, obj, field):
#~ # A nasty special case: base YAML doesn't support serialization of time
#~ # types (as opposed to dates or datetimes, which it does support). Since
#~ # we want to use the "safe" serializer for better interoperability, we
#~ # need to do something with those pesky times. Converting 'em to strings
#~ # isn't perfect, but it's better than a "!!python/time" type which would
#~ # halt deserialization under any other language.
#~ if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None:
#~ self._current[field.name] = str(getattr(obj, field.name))
#~ else:
#~ super(Serializer, self).handle_field(obj, field)
#~ def end_serialization(self):
#~ self.options.pop('stream', None)
#~ self.options.pop('fields', None)
#~ yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options)
#~ def getvalue(self):
#~ return self.stream.getvalue()
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of YAML data.
"""
if isinstance(stream_or_string, basestring):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
model_builder = None
for values in yaml.load_all(stream):
if values.has_key('model'):
modelspec = values.pop('model')
#model_class = eval(modelspec)
app,model = modelspec.split(".")
#print app,model
model_class = models.get_model(app,model)
if not model_class:
raise Exception("invalid model:" + modelspec)
model_builder = Instantiator(model_class)
if model_builder is None:
raise DataError("No model specified")
#print model_class
instance = model_builder.build(**values)
#yield instance
#~ if model_class == User:
#~ instance.set_password(yamldict.get('password'))
# data files are required to use "!!python/object:", so the
# yamldict is a Python object
#self.add_node(yamldict)
#print instance.pk, instance
#~ instance.save()
#~ m2m_data = {}
yield FakeDeserializedObject(instance)
#~ instance.save()
#~ print "Saved:", instance
#self.modelspec = modelspec
|
gpl-3.0
|
Walkman100/TSGE
|
frmMain.cs
|
120123
|
// -----------------------------------------------------------------------
// This file is part of TSGE.
//
// TSGE 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.
//
// TSGE 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 TSGE. If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------
namespace TSGE
{
using Classes;
using Comparers;
using Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Linq;
public partial class frmMain : Form
{
/// <summary>
/// Tooltip object to attach helpful text to controls.
/// </summary>
private readonly ToolTip m_Tooltip;
/// <summary>
/// The current player object being edited.
/// </summary>
public Player Player { get; set; }
/// <summary>
/// Internal list of all inventory item labels.
/// </summary>
private readonly List<ItemLabel> m_InventoryLabels;
/// <summary>
/// Internal list of all equipment item labels.
/// </summary>
private readonly List<ItemLabel> m_EquipmentLabels;
/// <summary>
/// Internal list of all bank and safe item labels.
/// </summary>
private readonly List<ItemLabel> m_BankSafeLabels;
/// <summary>
/// The currently selected inventory item.
/// </summary>
public Label m_SelectedInventoryItem;
/// <summary>
/// The currently selected equipment item.
/// </summary>
public Label m_SelectedEquipmentItem;
/// <summary>
/// The currently selected bank/safe item.
/// </summary>
public Label m_SelectedBankSafeItem;
/// <summary>
/// Default Constructor
/// </summary>
public frmMain()
{
InitializeComponent();
// Set the default size..
this.Width = DpiHelper.ScaleAsDpi(628);
this.Height = DpiHelper.ScaleAsDpi(493);
// Initialize the Terraria class..
Terraria.Instance.Initialize();
// Set data source to various lists..
this.lstBuffSelection.DataSource = Terraria.Instance.Buffs;
this.lstInventoryItems.DataSource = Terraria.Instance.Items;
this.lstBankSafeItems.DataSource = Terraria.Instance.Items;
this.cboInventoryPrefix.DataSource = Terraria.Instance.Prefixes;
this.cboEquipmentPrefix.DataSource = Terraria.Instance.Prefixes;
this.cboBankSafePrefix.DataSource = Terraria.Instance.Prefixes;
// Initialize tooltip object..
this.m_Tooltip = new ToolTip();
// Initialize internal item label lists..
this.m_InventoryLabels = new List<ItemLabel>();
this.m_EquipmentLabels = new List<ItemLabel>();
this.m_BankSafeLabels = new List<ItemLabel>();
var nullItemIcon = new Bitmap(Application.StartupPath + "\\Data\\Items\\item_0.png");
var nullItemName = Terraria.Instance.Items.Single(i => i.NetID == 0).ToString();
// Prepare inventory item label list..
for (var x = 0; x < 58; x++)
{
// Find the label..
var label = (ItemLabel)this.Controls.Find(string.Format("inventoryItem{0:d2}", x), true)[0];
this.m_InventoryLabels.Add(label);
// Update the label defaults..
label.Image = nullItemIcon;
label.Text = "0";
label.Tag = x;
// Set the default tooltip..
this.m_Tooltip.SetToolTip(label, nullItemName);
}
// Prepare equipment item label list..
for (var x = 0; x < 24; x++)
{
// Find the label..
var label = (ItemLabel)this.Controls.Find(string.Format("equipmentItem{0:d2}", x), true)[0];
this.m_EquipmentLabels.Add(label);
// Update the label defaults.
label.ShowItemCount = false;
label.Image = nullItemIcon;
label.Text = "";
label.Tag = x;
// Set the default tooltip..
this.m_Tooltip.SetToolTip(label, nullItemName);
}
// Prepare the bank/safe label list..
for (var x = 0; x < 80; x++)
{
// Find the label..
var label = (ItemLabel)this.Controls.Find(string.Format("bankSafeItem{0:d2}", x), true)[0];
this.m_BankSafeLabels.Add(label);
// Update the label defaults..
label.Image = nullItemIcon;
label.Text = "0";
label.Tag = x;
// Set the default tooltip..
this.m_Tooltip.SetToolTip(label, nullItemName);
}
// Initialize the default player object..
this.modelViewer.SuspendModelUpdates();
this.Player = new Player
{
EyeColor = this.pbEyesColor.BackColor = Color.FromArgb(255, 105, 90, 75),
HairColor = this.pbHairColor.BackColor = Color.FromArgb(255, 215, 90, 55),
SkinColor = this.pbSkinColor.BackColor = Color.FromArgb(255, 255, 125, 75),
PantsColor = this.pbPantsColor.BackColor = Color.FromArgb(255, 255, 230, 175),
ShirtColor = this.pbShirtColor.BackColor = Color.FromArgb(255, 175, 165, 140),
ShoesColor = this.pbShoesColor.BackColor = Color.FromArgb(255, 160, 106, 60),
UndershirtColor = this.pbUndershirtColor.BackColor = Color.FromArgb(255, 160, 180, 215)
};
// Set the binding object data source..
playerBindingSource.DataSource = this.Player;
this.modelViewer.ResumeModelUpdates();
}
/// <summary>
/// Creates a filtered item list.
/// </summary>
/// <param name="nameFilter"></param>
/// <param name="categoryFilter"></param>
/// <returns></returns>
private static IEnumerable<Item> CreateFilteredItemList(string nameFilter, int categoryFilter)
{
// Should we filter by name first..?
var items = Terraria.Instance.Items;
if (!string.IsNullOrEmpty(nameFilter))
items = items.Where(i => i.Name.ToLower().Contains(nameFilter.ToLower()) || i.NetID == 0).ToList();
// Next filter by category..
switch (categoryFilter)
{
case 0: // All
break;
case 1: // Armor / Social Gear
{
items = items.Where(i => i.WornArmor || i.Social || i.Vanity || i.HeadSlot > -1 || i.BodySlot > -1 || i.LegSlot > -1 || i.NetID == 0).ToList();
break;
}
case 2: // Accessories
{
items = items.Where(i => i.Accessory || i.NetID == 0).ToList();
break;
}
case 3: // Ammunition
{
items = items.Where(i => i.Ammo > 0 || i.NetID == 0).ToList();
break;
}
case 4: // Building Objects
{
items = items.Where(i => i.HeadSlot <= 0 && i.BodySlot <= 0 && i.LegSlot <= 0 && i.Ammo <= 0 && i.Material || i.NetID == 0).ToList();
break;
}
case 5: // Consumables
{
items = items.Where(i => i.Consumable || i.NetID == 0).ToList();
break;
}
case 6: // Money
{
items = items.Where(i => i.Name.ToLower().Contains("coin") || i.NetID == 0).ToList();
break;
}
case 7: // Tools
{
items = items.Where(i => i.Axe > 0 || i.Hammer > 0 || i.Pick > 0 || i.NetID == 0).ToList();
break;
}
case 8: // Weapons
{
items = items.Where(i => i.HeadSlot <= 0 && i.BodySlot <= 0 && i.LegSlot <= 0 && i.Ammo <= 0 &&
!i.WornArmor && !i.Accessory && !i.Social && !i.Vanity &&
!i.Consumable || i.NetID == 0).ToList();
break;
}
}
// Return the filtered list..
return items;
}
/// <summary>
/// Creates a filtered item prefix list.
/// </summary>
/// <param name="categoryFilter"></param>
/// <returns></returns>
private static IEnumerable<ItemPrefix> CreateFilteredPrefixList(int categoryFilter)
{
// Filter the prefix list..
var items = Terraria.Instance.Prefixes;
switch (categoryFilter)
{
case 0: // All
break;
case 1: // Universal
items = items.Where(i => i.Category == -1 || i.Category == 0).ToList();
break;
case 2: // Common
items = items.Where(i => i.Category == -1 || i.Category == 1).ToList();
break;
case 3: // Melee
items = items.Where(i => i.Category == -1 || i.Category == 2).ToList();
break;
case 4: // Ranged
items = items.Where(i => i.Category == -1 || i.Category == 3).ToList();
break;
case 5: // Magic
items = items.Where(i => i.Category == -1 || i.Category == 4).ToList();
break;
case 6: // Accessories
items = items.Where(i => i.Category == -1 || i.Category == 5).ToList();
break;
}
return items;
}
/// <summary>
/// Updates the selected equipment label with the given item info.
/// </summary>
/// <param name="label"></param>
/// <param name="item"></param>
private void UpdateEquipmentLabel(ItemLabel label, Item item)
{
label.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_Tooltip.SetToolTip(label, item.ToString());
}
/// <summary>
/// Refreshes the non-bound UI items.
/// </summary>
private void RefreshLoadedPlayer()
{
// Update the inventory..
foreach (var label in this.m_InventoryLabels)
{
label.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, this.Player.Inventory[(int)label.Tag].NetID));
label.Text = this.Player.Inventory[(int)label.Tag].Count.ToString();
this.m_Tooltip.SetToolTip(label, this.Player.Inventory[(int)label.Tag].ToString());
}
// Update the equipment..
UpdateEquipmentLabel(this.m_EquipmentLabels[00], this.Player.Armor[0]);
UpdateEquipmentLabel(this.m_EquipmentLabels[01], this.Player.Armor[1]);
UpdateEquipmentLabel(this.m_EquipmentLabels[02], this.Player.Armor[2]);
UpdateEquipmentLabel(this.m_EquipmentLabels[03], this.Player.Vanity[0]);
UpdateEquipmentLabel(this.m_EquipmentLabels[04], this.Player.Vanity[1]);
UpdateEquipmentLabel(this.m_EquipmentLabels[05], this.Player.Vanity[2]);
UpdateEquipmentLabel(this.m_EquipmentLabels[06], this.Player.Dye[0]);
UpdateEquipmentLabel(this.m_EquipmentLabels[07], this.Player.Dye[1]);
UpdateEquipmentLabel(this.m_EquipmentLabels[08], this.Player.Dye[2]);
UpdateEquipmentLabel(this.m_EquipmentLabels[09], this.Player.Dye[3]);
UpdateEquipmentLabel(this.m_EquipmentLabels[10], this.Player.Dye[4]);
UpdateEquipmentLabel(this.m_EquipmentLabels[11], this.Player.Dye[5]);
UpdateEquipmentLabel(this.m_EquipmentLabels[12], this.Player.Dye[6]);
UpdateEquipmentLabel(this.m_EquipmentLabels[13], this.Player.Dye[7]);
UpdateEquipmentLabel(this.m_EquipmentLabels[14], this.Player.Accessories[0]);
UpdateEquipmentLabel(this.m_EquipmentLabels[15], this.Player.Accessories[1]);
UpdateEquipmentLabel(this.m_EquipmentLabels[16], this.Player.Accessories[2]);
UpdateEquipmentLabel(this.m_EquipmentLabels[17], this.Player.Accessories[3]);
UpdateEquipmentLabel(this.m_EquipmentLabels[18], this.Player.Accessories[4]);
UpdateEquipmentLabel(this.m_EquipmentLabels[19], this.Player.SocialAccessories[0]);
UpdateEquipmentLabel(this.m_EquipmentLabels[20], this.Player.SocialAccessories[1]);
UpdateEquipmentLabel(this.m_EquipmentLabels[21], this.Player.SocialAccessories[2]);
UpdateEquipmentLabel(this.m_EquipmentLabels[22], this.Player.SocialAccessories[3]);
UpdateEquipmentLabel(this.m_EquipmentLabels[23], this.Player.SocialAccessories[4]);
// Update the bank/safe..
for (var x = 0; x < this.m_BankSafeLabels.Count; x++)
{
// Update the item label..
var item = (x < 40) ? this.Player.Bank1[x] : this.Player.Bank2[x - 40];
this.m_BankSafeLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_BankSafeLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_BankSafeLabels[x], item.ToString());
}
}
#region "==> Menu Command Handlers"
/// <summary>
/// Fills the quick-select character box with known profiles.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tscboQuickSelect_DropDown(object sender, EventArgs e)
{
// Clear the current items..
this.tscboQuickSelect.Items.Clear();
// Find all current profiles..
var dir = new DirectoryInfo(Terraria.ProfilePath);
var files = dir.GetFiles("*.plr").OrderBy(f => f, new NaturalFileInfoNameComparer());
// Insert each file into the combobox..
foreach (var f in files)
{
var name = Terraria.Instance.GetProfileName(f.FullName);
if (string.IsNullOrEmpty(name))
name = f.Name;
this.tscboQuickSelect.Items.Add(string.Format("{0} -- {1}", name, f.Name));
}
}
/// <summary>
/// Attempts to load the quick-selected character.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tscboQuickSelect_SelectedIndexChanged(object sender, EventArgs e)
{
// Attempt to get the file name from the list..
var selectedItem = this.tscboQuickSelect.SelectedItem;
var file = selectedItem.ToString().Split(new[] { " -- " }, StringSplitOptions.RemoveEmptyEntries)[1];
if (string.IsNullOrEmpty(file))
return;
// Attempt to load the profile..
this.Player = Terraria.Instance.LoadProfile(string.Format("{0}\\{1}", Terraria.ProfilePath, file));
if (this.Player == null)
{
this.Player = new Player();
this.playerBindingSource.DataSource = this.Player;
this.modelViewer.UpdateTextures();
return;
}
this.Player.File = string.Format("{0}\\{1}", Terraria.ProfilePath, file);
this.playerBindingSource.DataSource = this.Player;
this.modelViewer.UpdateTextures();
this.RefreshLoadedPlayer();
}
/// <summary>
/// Creates a new player profile.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void newCharacterToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Player = new Player();
this.playerBindingSource.DataSource = this.Player;
this.RefreshLoadedPlayer();
}
/// <summary>
/// Opens an existing profile.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var ofd = new OpenFileDialog())
{
ofd.AddExtension = true;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.DefaultExt = "plr";
ofd.Filter = "Terraria Player Files (*.plr)|*.plr|All files (*.*)|*.*";
ofd.InitialDirectory = Terraria.ProfilePath;
ofd.ValidateNames = true;
if (ofd.ShowDialog() != DialogResult.OK)
return;
// Load the profile..
this.Player = Terraria.Instance.LoadProfile(ofd.FileName);
if (this.Player == null)
{
this.Player = new Player();
this.playerBindingSource.DataSource = this.Player;
this.modelViewer.UpdateTextures();
return;
}
this.Player.File = ofd.FileName;
this.playerBindingSource.DataSource = this.Player;
this.modelViewer.UpdateTextures();
this.RefreshLoadedPlayer();
}
}
/// <summary>
/// Saves a profile to its known location.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Execute save-as if we have no file..
if (string.IsNullOrEmpty(this.Player.File))
{
saveAsToolStripMenuItem_Click(sender, e);
return;
}
// Save the profile..
Terraria.Instance.SaveProfile(this.Player, this.Player.File);
}
/// <summary>
/// Saves a profile to the selected location.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var sfd = new SaveFileDialog())
{
sfd.AddExtension = true;
sfd.CheckPathExists = true;
sfd.DefaultExt = "plr";
sfd.Filter = "Terraria Player Files (*.plr)|*.plr|All files (*.*)|*.*";
sfd.InitialDirectory = Terraria.ProfilePath;
sfd.ValidateNames = true;
if (sfd.ShowDialog() != DialogResult.OK)
return;
// Save the profile..
this.Player.File = sfd.FileName;
Terraria.Instance.SaveProfile(this.Player, this.Player.File);
}
}
/// <summary>
/// Exits this appliction.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
/// <summary>
/// Displays the about form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void aboutTSGEToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var aboutForm = new frmAbout())
{
aboutForm.ShowDialog();
}
}
/// <summary>
/// Checks for updates.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// Attempt to download the latest info..
var client = new WebClient();
var latest = client.DownloadString("https://raw.github.com/atom0s/TSGE/master/latest.txt");
if (string.IsNullOrEmpty(latest))
throw new Exception("No update found!");
// Attempt to get the update parts..
var parts = latest.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
throw new Exception("No update found!");
// See if we have the latest version..
if (Assembly.GetExecutingAssembly().GetName().Version < new Version(parts[0]))
{
// Update found..
var ret = MessageBox.Show("Update available!\r\nVersion: " + parts[0], "Update available!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (ret == DialogResult.Yes)
Process.Start(parts[1]);
return;
}
MessageBox.Show("No updates found at this time.", "No Update Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("No updates found at this time.", "No Update Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region "==> Player Tab"
/// <summary>
/// Adjusts the hair color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbHairColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbHairColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.HairColor = this.modelViewer.HairColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the skin color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbSkinColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbSkinColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.SkinColor = this.modelViewer.HandsColor = this.modelViewer.HeadColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the eyes color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbEyesColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbEyesColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.EyeColor = this.modelViewer.EyeColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the shirt color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbShirtColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbShirtColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.ShirtColor = this.modelViewer.ShirtColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the undershirt color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbUndershirtColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbUndershirtColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.UndershirtColor = this.modelViewer.UndershirtColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the pants color
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbPantsColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbPantsColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.PantsColor = this.modelViewer.PantsColor = cdlg.Color;
}
}
/// <summary>
/// Adjusts the shoes color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbShoesColor_Click(object sender, EventArgs e)
{
using (var cdlg = new ColorDialog())
{
cdlg.Color = this.pbShoesColor.BackColor;
if (cdlg.ShowDialog() != DialogResult.OK)
return;
this.Player.ShoesColor = this.modelViewer.ShoesColor = cdlg.Color;
}
}
/// <summary>
/// Opens the hair selector.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectHair_Click(object sender, EventArgs e)
{
var frmHair = new frmHairSelection { HairId = this.Player.Hair };
if (frmHair.ShowDialog() != DialogResult.OK)
return;
this.Player.Hair = frmHair.HairId;
this.modelViewer.HairId = frmHair.HairId;
this.modelViewer.UpdateTextures();
}
/// <summary>
/// Selects a random hair file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRandomHair_Click(object sender, EventArgs e)
{
var rand = new Random((int)DateTime.Now.Ticks);
var hair = rand.Next(0, 50);
this.Player.Hair = hair;
this.modelViewer.HairId = hair;
this.modelViewer.UpdateTextures();
}
/// <summary>
/// Selects random colors.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRandomColors_Click(object sender, EventArgs e)
{
var rand = new Random((int)DateTime.Now.Ticks);
var btColors = new byte[21];
rand.NextBytes(btColors);
this.modelViewer.SuspendModelUpdates();
this.Player.HairColor = this.modelViewer.HairColor = Color.FromArgb(255, btColors[0], btColors[1], btColors[2]);
this.Player.SkinColor = this.modelViewer.HandsColor = this.modelViewer.HeadColor = Color.FromArgb(255, btColors[3], btColors[4], btColors[5]);
this.Player.EyeColor = this.modelViewer.EyeColor = Color.FromArgb(255, btColors[6], btColors[7], btColors[8]);
this.Player.ShirtColor = this.modelViewer.ShirtColor = Color.FromArgb(255, btColors[9], btColors[10], btColors[11]);
this.Player.UndershirtColor = this.modelViewer.UndershirtColor = Color.FromArgb(255, btColors[12], btColors[13], btColors[14]);
this.Player.PantsColor = this.modelViewer.PantsColor = Color.FromArgb(255, btColors[15], btColors[16], btColors[17]);
this.Player.ShoesColor = this.modelViewer.ShoesColor = Color.FromArgb(255, btColors[18], btColors[19], btColors[20]);
this.modelViewer.ResumeModelUpdates();
}
/// <summary>
/// Exports the current players hair type and colors.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveColorHair_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Hair and Color Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
var ret = sfd.ShowDialog();
if (ret != DialogResult.OK)
{
if (ret == DialogResult.Cancel || ret == DialogResult.Abort)
return;
MessageBox.Show("Failed to save hair and color!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("HairColor"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save hair and color!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Add the hair id element..
xml.Root.Add(new XElement("hair", new object[]
{
new XAttribute("id", this.Player.Hair)
}));
// Add the color elements..
xml.Root.Add(new XElement("HairColor", new object[]
{
new XAttribute("a", this.Player.HairColor.A),
new XAttribute("r", this.Player.HairColor.R),
new XAttribute("g", this.Player.HairColor.G),
new XAttribute("b", this.Player.HairColor.B)
}));
xml.Root.Add(new XElement("SkinColor", new object[]
{
new XAttribute("a", this.Player.SkinColor.A),
new XAttribute("r", this.Player.SkinColor.R),
new XAttribute("g", this.Player.SkinColor.G),
new XAttribute("b", this.Player.SkinColor.B)
}));
xml.Root.Add(new XElement("EyeColor", new object[]
{
new XAttribute("a", this.Player.EyeColor.A),
new XAttribute("r", this.Player.EyeColor.R),
new XAttribute("g", this.Player.EyeColor.G),
new XAttribute("b", this.Player.EyeColor.B)
}));
xml.Root.Add(new XElement("ShirtColor", new object[]
{
new XAttribute("a", this.Player.ShirtColor.A),
new XAttribute("r", this.Player.ShirtColor.R),
new XAttribute("g", this.Player.ShirtColor.G),
new XAttribute("b", this.Player.ShirtColor.B)
}));
xml.Root.Add(new XElement("UndershirtColor", new object[]
{
new XAttribute("a", this.Player.UndershirtColor.A),
new XAttribute("r", this.Player.UndershirtColor.R),
new XAttribute("g", this.Player.UndershirtColor.G),
new XAttribute("b", this.Player.UndershirtColor.B)
}));
xml.Root.Add(new XElement("PantsColor", new object[]
{
new XAttribute("a", this.Player.PantsColor.A),
new XAttribute("r", this.Player.PantsColor.R),
new XAttribute("g", this.Player.PantsColor.G),
new XAttribute("b", this.Player.PantsColor.B)
}));
xml.Root.Add(new XElement("ShoesColor", new object[]
{
new XAttribute("a", this.Player.ShoesColor.A),
new XAttribute("r", this.Player.ShoesColor.R),
new XAttribute("g", this.Player.ShoesColor.G),
new XAttribute("b", this.Player.ShoesColor.B)
}));
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a hair type and color profile.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadColorHair_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Hair and Color Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
var ret = ofd.ShowDialog();
if (ret != DialogResult.OK)
{
if (ret == DialogResult.Cancel || ret == DialogResult.Abort)
return;
MessageBox.Show("Failed to open hair and color file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the hair and color dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("HairColor");
if (root == null)
throw new InvalidDataException("File data is not valid.");
var element = root.Element("hair");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var hairId = int.Parse(element.Attribute("id").Value);
element = root.Element("HairColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var hairColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("SkinColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var skinColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("EyeColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var eyeColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("ShirtColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var shirtColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("UndershirtColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var undershirtColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("PantsColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var pantsColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
element = root.Element("ShoesColor");
if (element == null)
throw new InvalidDataException("File data is not valid.");
var shoesColor = Color.FromArgb(int.Parse(element.Attribute("a").Value),
int.Parse(element.Attribute("r").Value),
int.Parse(element.Attribute("g").Value),
int.Parse(element.Attribute("b").Value));
// Update the player..
this.modelViewer.SuspendModelUpdates();
this.Player.Hair = hairId;
this.Player.HairColor = hairColor;
this.Player.SkinColor = skinColor;
this.Player.EyeColor = eyeColor;
this.Player.ShirtColor = shirtColor;
this.Player.UndershirtColor = undershirtColor;
this.Player.PantsColor = pantsColor;
this.Player.ShoesColor = shoesColor;
this.modelViewer.ResumeModelUpdates();
}
catch
{
MessageBox.Show("Failed to open hair and color file!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
#endregion
#region "==> Buffs Tab"
/// <summary>
/// Deletes the selected buff.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteBuff_Click(object sender, EventArgs e)
{
if (this.lstPlayerBuffs.SelectedIndex < 0)
return;
// Delete the buff..
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].SetBuff(0);
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Maxes the selected buffs duration.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMaxBuffDuration_Click(object sender, EventArgs e)
{
if (this.lstPlayerBuffs.SelectedIndex < 0 &&
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].Id != 0)
return;
// Max the buff duration..
var buff = Terraria.Instance.Buffs.Single(b => b.Id == this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].Id);
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].Duration = buff.Duration;
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Hacks the buffs duration.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnHackBuffDuration_Click(object sender, EventArgs e)
{
if (this.lstPlayerBuffs.SelectedIndex < 0 &&
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].Id != 0)
return;
// Hack the buff duration..
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].Duration = int.MaxValue;
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Deletes all buffs.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteAllBuffs_Click(object sender, EventArgs e)
{
foreach (var buff in this.Player.Buffs)
buff.SetBuff(0);
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Maxes all the buff durations.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMaxAllBuffDurations_Click(object sender, EventArgs e)
{
foreach (var buff in this.Player.Buffs.Where(b => b.Id > 0))
{
var origBuff = Terraria.Instance.Buffs.Single(b => b.Id == buff.Id);
buff.Duration = origBuff.Duration;
}
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Hacks all the buff durations.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnHackAllBuffDurations_Click(object sender, EventArgs e)
{
foreach (var buff in this.Player.Buffs.Where(b => b.Id > 0))
buff.Duration = int.MaxValue;
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Changes the players buff with the selected one.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstBuffSelection_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.lstBuffSelection.SelectedIndex < 0 ||
this.lstPlayerBuffs.SelectedIndex < 0)
return;
// Set the new buff..
var buff = Terraria.Instance.Buffs[this.lstBuffSelection.SelectedIndex];
this.Player.Buffs[this.lstPlayerBuffs.SelectedIndex].SetBuff(buff.Id);
// Update the buff list..
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
/// <summary>
/// Saves the current buff list to an xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveBuffs_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Buff Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to save buffs!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("Buffs"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save buffs!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Loop each buff in the players buff list..
foreach (var b in this.Player.Buffs)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("buff", new object[]
{
new XAttribute("id", b.Id),
new XAttribute("duration", b.Duration)
}));
}
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a saved buffs xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadBuffs_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Buff Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
if (ofd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to open buff list!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the buff list dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("Buffs");
if (root == null)
throw new InvalidDataException("File data is not valid.");
// Obtain the buff entries..
var itemElements = root.Elements("buff");
var items = itemElements as IList<XElement> ?? itemElements.ToList();
// Update each item..
for (var x = 0; x < items.Count; x++)
{
int buffId;
int buffDuration;
int.TryParse(items[x].Attribute("id").Value, out buffId);
int.TryParse(items[x].Attribute("duration").Value, out buffDuration);
this.Player.Buffs[x].SetBuff(buffId);
this.Player.Buffs[x].Duration = buffDuration;
}
this.RefreshLoadedPlayer();
this.lstPlayerBuffs.Invalidate(true);
this.lstPlayerBuffs.Refresh();
}
catch
{
MessageBox.Show("Failed to open buff list!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
#endregion
#region "==> Inventory Tab"
/// <summary>
/// Filters the inventory items list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtInvItemFilter_TextChanged(object sender, EventArgs e)
{
this.lstInventoryItems.SelectedIndexChanged -= this.lstInventoryItems_SelectedIndexChanged;
var items = CreateFilteredItemList(this.txtInvItemFilter.Text, this.cboInvItemFilter.SelectedIndex);
this.lstInventoryItems.DataSource = items.ToList();
this.lstInventoryItems.SelectedIndexChanged += this.lstInventoryItems_SelectedIndexChanged;
}
/// <summary>
/// Filters the item list based on the given selected category.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboInvItemFilter_SelectedIndexChanged(object sender, EventArgs e)
{
this.lstInventoryItems.SelectedIndexChanged -= this.lstInventoryItems_SelectedIndexChanged;
var items = CreateFilteredItemList(this.txtInvItemFilter.Text, this.cboInvItemFilter.SelectedIndex);
this.lstInventoryItems.DataSource = items.ToList();
this.lstInventoryItems.SelectedIndexChanged += this.lstInventoryItems_SelectedIndexChanged;
}
/// <summary>
/// Filters the prefix list based on the given selected category.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboInventoryPrefixCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.cboInventoryPrefixCategory.SelectedItem == null)
{
return;
}
this.cboInventoryPrefix.SelectedIndexChanged -= this.cboInventoryPrefix_SelectedIndexChanged;
var item = CreateFilteredPrefixList(this.cboInventoryPrefixCategory.SelectedIndex);
this.cboInventoryPrefix.DataSource = item.ToList();
this.cboInventoryPrefix.SelectedIndexChanged += this.cboInventoryPrefix_SelectedIndexChanged;
}
/// <summary>
/// Selects the hovered inventory label.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void inventoryItem_Click(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.FromArgb(64, 127, 255, 0);
this.m_SelectedInventoryItem = lbl;
lbl.Focus();
foreach (var label in this.m_InventoryLabels.Where(label => label != this.m_SelectedInventoryItem))
label.BackColor = Color.Transparent;
// Attempt to update the lists with the selected items properties..
var item = this.Player.Inventory[(int)lbl.Tag];
if (item != null && item.NetID != 0)
{
this.cboInventoryPrefixCategory.SelectedIndex = 0;
if (item.Prefix != 0)
{
for (var x = 0; x < this.cboInventoryPrefix.Items.Count; x++)
{
if (((ItemPrefix)this.cboInventoryPrefix.Items[x]).Id == item.Prefix)
{
this.cboInventoryPrefix.SelectedIndex = x;
return;
}
}
}
else
{
var none = (from ItemPrefix i in this.cboInventoryPrefix.Items
where i.Prefix == "None"
select i).SingleOrDefault();
if (none != null)
this.cboInventoryPrefix.SelectedItem = none;
}
}
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void inventoryItem_MouseEnter(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.LightSkyBlue;
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void inventoryItem_MouseLeave(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = lbl != this.m_SelectedInventoryItem ? Color.Transparent : Color.FromArgb(64, 127, 255, 0);
}
/// <summary>
/// Updates the current item.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstInventoryItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedInventoryItem == null)
return;
// Set the inventory item..
var item = (Item)this.lstInventoryItems.SelectedItem;
var slot = (int)this.m_SelectedInventoryItem.Tag;
this.Player.Inventory[slot].SetItem(item.NetID);
this.Player.Inventory[slot].Count = this.Player.Inventory[slot].Stack = this.Player.Inventory[slot].MaxStack;
if (item.NetID == 0)
this.Player.Inventory[slot].Count = this.Player.Inventory[slot].Stack = 0;
else
{
// Add the selected prefix to the item..
this.Player.Inventory[slot].Prefix = (byte)((ItemPrefix)this.cboInventoryPrefix.SelectedItem).Id;
}
// Update the inventory label..
this.m_SelectedInventoryItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedInventoryItem.Text = this.Player.Inventory[slot].Count.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, this.Player.Inventory[slot].ToString());
}
/// <summary>
/// Updates the current items prefix.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboInventoryPrefix_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedInventoryItem == null)
return;
if (this.cboInventoryPrefix.SelectedItem == null)
{
return;
}
// Set the inventory item..
var prefix = (ItemPrefix)this.cboInventoryPrefix.SelectedItem;
var slot = (int)this.m_SelectedInventoryItem.Tag;
// Ensure the slot has an item..
if (this.Player.Inventory[slot].NetID == 0)
return;
// Update the prefix and tooltip..
this.Player.Inventory[slot].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, this.Player.Inventory[slot].ToString());
}
/// <summary>
/// Prevents the stack count from having non-numeric characters typed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtInventoryStackCount_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
/// <summary>
/// Updates the current items stack count with the entered amount.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtInventoryStackCount_TextChanged(object sender, EventArgs e)
{
if (this.m_SelectedInventoryItem == null)
return;
// Ensure the slot has an item..
var slot = (int)this.m_SelectedInventoryItem.Tag;
if (this.Player.Inventory[slot].NetID == 0)
return;
// Attempt to parse the new count..
int count;
if (!int.TryParse(this.txtInventoryStackCount.Text, out count))
return;
// Update the stack count..
this.Player.Inventory[slot].Count = this.Player.Inventory[slot].Stack = count;
this.m_SelectedInventoryItem.Text = count.ToString();
}
/// <summary>
/// Deletes the selected inventory item.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInventoryDeleteItem_Click(object sender, EventArgs e)
{
if (this.m_SelectedInventoryItem == null)
return;
// Ensure the slot has an item..
var slot = (int)this.m_SelectedInventoryItem.Tag;
if (this.Player.Inventory[slot].NetID == 0)
return;
// Update the inventory item..
this.Player.Inventory[slot].SetItem(0);
this.Player.Inventory[slot].Count = 0;
// Update the inventory label..
this.m_SelectedInventoryItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, this.Player.Inventory[slot].NetID));
this.m_SelectedInventoryItem.Text = "0";
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, this.Player.Inventory[slot].ToString());
}
/// <summary>
/// Maxes all inventory item stacks.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInventoryMaxAllStacks_Click(object sender, EventArgs e)
{
for (var x = 0; x < this.m_InventoryLabels.Count; x++)
{
// Update the item..
var item = this.Player.Inventory[x];
if (item.Id != 0)
item.Count = item.Stack = item.MaxStack;
// Update the item label..
this.m_InventoryLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_InventoryLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_InventoryLabels[x], item.ToString());
}
}
/// <summary>
/// Deletes all inventory items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInventoryDeleteAllItems_Click(object sender, EventArgs e)
{
for (var x = 0; x < this.m_InventoryLabels.Count; x++)
{
// Update the item..
var item = this.Player.Inventory[x];
item.SetItem(0);
item.Count = 0;
// Update the item label..
this.m_InventoryLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_InventoryLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_InventoryLabels[x], item.ToString());
}
}
/// <summary>
/// Hacks all inventory item stacks.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInventoryHackAllStacks_Click(object sender, EventArgs e)
{
for (var x = 0; x < this.m_InventoryLabels.Count; x++)
{
// Update the item..
var item = this.Player.Inventory[x];
if (item.Id != 0 && item.MaxStack > 1)
item.Count = item.Stack = int.MaxValue;
// Update the item label..
this.m_InventoryLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_InventoryLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_InventoryLabels[x], item.ToString());
}
}
/// <summary>
/// Saves the current inventory to an xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveInventory_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Inventory Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to save inventory!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("Inventory"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save inventory!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Loop each item in the players inventory..
foreach (var i in this.Player.Inventory)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("item", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("count", i.Count),
new XAttribute("prefix", i.Prefix)
}));
}
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a saved inventory xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadInventory_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Inventory Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
if (ofd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to open inventory!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the inventory dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("Inventory");
if (root == null)
throw new InvalidDataException("File data is not valid.");
// Obtain the item entries..
var itemElements = root.Elements("item");
var items = itemElements as IList<XElement> ?? itemElements.ToList();
if (items.Count != 58)
throw new InvalidDataException("File data is not valid.");
// Update each item..
for (var x = 0; x < items.Count; x++)
{
int itemId;
int itemCount;
int itemPrefix;
int.TryParse(items[x].Attribute("id").Value, out itemId);
int.TryParse(items[x].Attribute("count").Value, out itemCount);
int.TryParse(items[x].Attribute("prefix").Value, out itemPrefix);
this.Player.Inventory[x].SetItem(itemId);
this.Player.Inventory[x].Count = itemCount;
this.Player.Inventory[x].Prefix = (byte)itemPrefix;
}
this.RefreshLoadedPlayer();
}
catch
{
MessageBox.Show("Failed to open inventory!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
#endregion
#region "==> Equipment Tab"
/// <summary>
/// Selects the hovered equipment label.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void equipmentItem_Click(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.FromArgb(64, 127, 255, 0);
this.m_SelectedEquipmentItem = lbl;
lbl.Focus();
foreach (var label in this.m_EquipmentLabels.Where(label => label != this.m_SelectedEquipmentItem))
label.BackColor = Color.Transparent;
this.SetEquipmentListContext();
// Attempt to set the selected items prefix..
var slot = (int)this.m_SelectedEquipmentItem.Tag;
this.cboEquipmentPrefixCategory.SelectedIndex = 0;
var prefix = 0;
switch (slot)
{
case 0:
case 1:
case 2:
prefix = this.Player.Armor[slot].Prefix;
break;
case 3:
case 4:
case 5:
prefix = this.Player.Vanity[slot - 3].Prefix;
break;
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
prefix = this.Player.Dye[slot - 6].Prefix;
break;
case 14:
case 15:
case 16:
case 17:
case 18:
prefix = this.Player.Accessories[slot - 14].Prefix;
break;
default:
prefix = this.Player.SocialAccessories[slot - 19].Prefix;
break;
}
var prefixEntry = (from ItemPrefix i in this.cboEquipmentPrefix.Items
where i.Id == prefix
select i).SingleOrDefault();
if (prefixEntry != null)
this.cboEquipmentPrefix.SelectedItem = prefixEntry;
this.cboEquipmentPrefix_SelectedIndexChanged(null, null);
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void equipmentItem_MouseEnter(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.LightSkyBlue;
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void equipmentItem_MouseLeave(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = lbl != this.m_SelectedEquipmentItem ? Color.Transparent : Color.FromArgb(64, 127, 255, 0);
}
/// <summary>
/// Filters the equipment item list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtEquipmentFilter_TextChanged(object sender, EventArgs e)
{
this.SetEquipmentListContext();
}
/// <summary>
/// Selects and sets the equipment item.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstEquipmentItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedEquipmentItem == null || this.lstEquipmentItems.SelectedIndex < 0)
return;
var item = (Item)this.lstEquipmentItems.SelectedItem;
var slot = (int)this.m_SelectedEquipmentItem.Tag;
// Equipment..
if (slot == 0 || slot == 1 || slot == 2)
{
this.Player.Armor[slot].SetItem(item.NetID);
if (item.NetID != 0)
this.Player.Armor[slot].Prefix = (byte)((ItemPrefix)this.cboEquipmentPrefix.SelectedItem).Id;
item = this.Player.Armor[slot];
}
// Vanity..
else if (slot == 3 || slot == 4 || slot == 5)
{
this.Player.Vanity[slot - 3].SetItem(item.NetID);
if (item.NetID != 0)
this.Player.Vanity[slot - 3].Prefix = (byte)((ItemPrefix)this.cboEquipmentPrefix.SelectedItem).Id;
item = this.Player.Vanity[slot - 3];
}
// Dye..
else if (slot >= 6 && slot <= 13)
{
this.Player.Dye[slot - 6].SetItem(item.NetID);
if (item.NetID != 0)
this.Player.Dye[slot - 6].Prefix = (byte)((ItemPrefix)this.cboEquipmentPrefix.SelectedItem).Id;
item = this.Player.Dye[slot - 6];
}
// Accessories..
else if (slot >= 14 && slot <= 18)
{
this.Player.Accessories[slot - 14].SetItem(item.NetID);
if (item.NetID != 0)
this.Player.Accessories[slot - 14].Prefix = (byte)((ItemPrefix)this.cboEquipmentPrefix.SelectedItem).Id;
item = this.Player.Accessories[slot - 14];
}
// Social Accessories
else
{
this.Player.SocialAccessories[slot - 19].SetItem(item.NetID);
if (item.NetID != 0)
this.Player.SocialAccessories[slot - 19].Prefix = (byte)((ItemPrefix)this.cboEquipmentPrefix.SelectedItem).Id;
item = this.Player.SocialAccessories[slot - 19];
}
// Update the inventory label..
this.m_SelectedEquipmentItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedEquipmentItem.Text = item.MaxStack.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, item.ToString());
}
/// <summary>
/// Filters the equipment prefix list based on the selected category.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboEquipmentPrefixCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.cboEquipmentPrefixCategory.SelectedItem == null)
{
return;
}
this.cboEquipmentPrefix.SelectedIndexChanged -= this.cboEquipmentPrefix_SelectedIndexChanged;
var item = CreateFilteredPrefixList(this.cboEquipmentPrefixCategory.SelectedIndex);
this.cboEquipmentPrefix.DataSource = item.ToList();
this.cboEquipmentPrefix.SelectedIndexChanged += this.cboEquipmentPrefix_SelectedIndexChanged;
}
/// <summary>
/// Sets the equipment item prefix.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboEquipmentPrefix_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedEquipmentItem == null)
return;
if (this.cboEquipmentPrefix.SelectedItem == null)
{
return;
}
var prefix = (ItemPrefix)this.cboEquipmentPrefix.SelectedItem;
var slot = (int)this.m_SelectedEquipmentItem.Tag;
// Equipment..
if (slot == 0 || slot == 1 || slot == 2)
{
if (this.Player.Armor[slot].NetID == 0)
return;
this.Player.Armor[slot].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, this.Player.Armor[slot].ToString());
}
// Vanity..
else if (slot == 3 || slot == 4 || slot == 5)
{
if (this.Player.Vanity[slot - 3].NetID == 0)
return;
this.Player.Vanity[slot - 3].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, this.Player.Vanity[slot - 3].ToString());
}
// Dye..
else if (slot >= 6 && slot <= 13)
{
if (this.Player.Dye[slot - 6].NetID == 0)
return;
this.Player.Dye[slot - 6].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, this.Player.Dye[slot - 6].ToString());
}
// Accessories..
else if (slot >= 14 && slot <= 18)
{
if (this.Player.Accessories[slot - 14].NetID == 0)
return;
this.Player.Accessories[slot - 14].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, this.Player.Accessories[slot - 14].ToString());
}
// Social Accessories..
else
{
if (this.Player.SocialAccessories[slot - 19].NetID == 0)
return;
this.Player.SocialAccessories[slot - 19].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, this.Player.SocialAccessories[slot - 19].ToString());
}
}
/// <summary>
/// Updates the equipment item list based on the selected slot and filter.
/// </summary>
private void SetEquipmentListContext()
{
// Do not set a source if no item is selected..
if (this.m_SelectedEquipmentItem == null)
{
this.lstEquipmentItems.DataSource = null;
return;
}
// Remove the selection changed event while we update..
this.lstEquipmentItems.SelectedIndexChanged -= this.lstEquipmentItems_SelectedIndexChanged;
this.lstEquipmentItems.SuspendLayout();
// Determine the slot type..
var slot = (int)this.m_SelectedEquipmentItem.Tag;
switch (slot)
{
case 0: // Armor (Head)
case 3: // Vanity (Head)
{
var items = CreateFilteredItemList(this.txtEquipmentFilter.Text, 1);
this.lstEquipmentItems.DataSource = items.Where(i => i.HeadSlot > -1 || i.NetID == 0).ToList();
break;
}
case 1: // Armor (Body)
case 4: // Vanity (Body)
{
var items = CreateFilteredItemList(this.txtEquipmentFilter.Text, 1);
this.lstEquipmentItems.DataSource = items.Where(i => i.BodySlot > -1 || i.NetID == 0).ToList();
break;
}
case 2: // Armor (Legs)
case 5: // Vanity (Legs)
{
var items = CreateFilteredItemList(this.txtEquipmentFilter.Text, 1);
this.lstEquipmentItems.DataSource = items.Where(i => i.LegSlot > -1 || i.NetID == 0).ToList();
break;
}
case 6: // Dye
case 7: // Dye
case 8: // Dye
case 9: // Dye
case 10: // Dye
case 11: // Dye
case 12: // Dye
case 13: // Dye
{
var items = CreateFilteredItemList(this.txtEquipmentFilter.Text, 0);
this.lstEquipmentItems.DataSource = items.Where(i => i.Dye > 0 || i.NetID == 0).ToList();
break;
}
case 14: // Accessory
case 15: // Accessory
case 16: // Accessory
case 17: // Accessory
case 18: // Accessory
case 19: // Accessory
case 20: // Accessory
case 21: // Accessory
case 22: // Accessory
case 23: // Accessory
{
var items = CreateFilteredItemList(this.txtEquipmentFilter.Text, 2);
this.lstEquipmentItems.DataSource = items.ToList();
break;
}
}
// Restore the listbox..
this.lstEquipmentItems.SelectedIndex = -1;
this.lstEquipmentItems.ResumeLayout();
this.lstEquipmentItems.SelectedIndexChanged += this.lstEquipmentItems_SelectedIndexChanged;
}
/// <summary>
/// Saves the current players gear to an xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveEquipmentSet_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Equipment Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to save equipment!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("Equipment"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save equipment!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Loop each armor piece..
foreach (var i in this.Player.Armor)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("armor", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("prefix", i.Prefix)
}));
}
// Loop each accessory piece..
foreach (var i in this.Player.Accessories)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("accessory", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("prefix", i.Prefix)
}));
}
// Loop each vanity piece..
foreach (var i in this.Player.Vanity)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("vanity", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("prefix", i.Prefix)
}));
}
// Loop each social accessory piece..
foreach (var i in this.Player.SocialAccessories)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("socialaccessory", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("prefix", i.Prefix)
}));
}
// Loop each dye piece..
foreach (var i in this.Player.Dye)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("dye", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("prefix", i.Prefix)
}));
}
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a saved equipment set.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadEquipmentSet_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Equipment Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
if (ofd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to open equipment save!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the equipment dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("Equipment");
if (root == null)
throw new InvalidDataException("File data is not valid.");
// Obtain each categories items..
var armorElements = root.Elements("armor");
var accessoryElements = root.Elements("accessory");
var vanityElements = root.Elements("vanity");
var socialAccessoryElements = root.Elements("socialaccessory");
var dyeElements = root.Elements("dye");
// Convert the items to lists..
var armor = armorElements as IList<XElement> ?? armorElements.ToList();
var accessory = accessoryElements as IList<XElement> ?? accessoryElements.ToList();
var vanity = vanityElements as IList<XElement> ?? vanityElements.ToList();
var socialAccessory = socialAccessoryElements as IList<XElement> ?? socialAccessoryElements.ToList();
var dye = dyeElements as IList<XElement> ?? dyeElements.ToList();
// Validate the data..
if (armor.Count != 3 || accessory.Count != 5 || vanity.Count != 3 || socialAccessory.Count != 5 || dye.Count != 8)
throw new InvalidDataException("File data is not valid.");
// Update the armor..
this.Player.Armor[0].SetItem(int.Parse(armor[0].Attribute("id").Value));
this.Player.Armor[0].Prefix = (byte)int.Parse(armor[0].Attribute("prefix").Value);
this.Player.Armor[1].SetItem(int.Parse(armor[1].Attribute("id").Value));
this.Player.Armor[1].Prefix = (byte)int.Parse(armor[1].Attribute("prefix").Value);
this.Player.Armor[2].SetItem(int.Parse(armor[2].Attribute("id").Value));
this.Player.Armor[2].Prefix = (byte)int.Parse(armor[2].Attribute("prefix").Value);
// Update the accessories..
this.Player.Accessories[0].SetItem(int.Parse(accessory[0].Attribute("id").Value));
this.Player.Accessories[0].Prefix = (byte)int.Parse(accessory[0].Attribute("prefix").Value);
this.Player.Accessories[1].SetItem(int.Parse(accessory[1].Attribute("id").Value));
this.Player.Accessories[1].Prefix = (byte)int.Parse(accessory[1].Attribute("prefix").Value);
this.Player.Accessories[2].SetItem(int.Parse(accessory[2].Attribute("id").Value));
this.Player.Accessories[2].Prefix = (byte)int.Parse(accessory[2].Attribute("prefix").Value);
this.Player.Accessories[3].SetItem(int.Parse(accessory[3].Attribute("id").Value));
this.Player.Accessories[3].Prefix = (byte)int.Parse(accessory[3].Attribute("prefix").Value);
this.Player.Accessories[4].SetItem(int.Parse(accessory[4].Attribute("id").Value));
this.Player.Accessories[4].Prefix = (byte)int.Parse(accessory[4].Attribute("prefix").Value);
// Update the vanity..
this.Player.Vanity[0].SetItem(int.Parse(vanity[0].Attribute("id").Value));
this.Player.Vanity[0].Prefix = (byte)int.Parse(vanity[0].Attribute("prefix").Value);
this.Player.Vanity[1].SetItem(int.Parse(vanity[1].Attribute("id").Value));
this.Player.Vanity[1].Prefix = (byte)int.Parse(vanity[1].Attribute("prefix").Value);
this.Player.Vanity[2].SetItem(int.Parse(vanity[2].Attribute("id").Value));
this.Player.Vanity[2].Prefix = (byte)int.Parse(vanity[2].Attribute("prefix").Value);
// Update the accessories..
this.Player.SocialAccessories[0].SetItem(int.Parse(socialAccessory[0].Attribute("id").Value));
this.Player.SocialAccessories[0].Prefix = (byte)int.Parse(socialAccessory[0].Attribute("prefix").Value);
this.Player.SocialAccessories[1].SetItem(int.Parse(socialAccessory[1].Attribute("id").Value));
this.Player.SocialAccessories[1].Prefix = (byte)int.Parse(socialAccessory[1].Attribute("prefix").Value);
this.Player.SocialAccessories[2].SetItem(int.Parse(socialAccessory[2].Attribute("id").Value));
this.Player.SocialAccessories[2].Prefix = (byte)int.Parse(socialAccessory[2].Attribute("prefix").Value);
this.Player.SocialAccessories[3].SetItem(int.Parse(socialAccessory[3].Attribute("id").Value));
this.Player.SocialAccessories[3].Prefix = (byte)int.Parse(socialAccessory[3].Attribute("prefix").Value);
this.Player.SocialAccessories[4].SetItem(int.Parse(socialAccessory[4].Attribute("id").Value));
this.Player.SocialAccessories[4].Prefix = (byte)int.Parse(socialAccessory[4].Attribute("prefix").Value);
// Update the dye..
for (var x = 0; x < dye.Count; x++)
{
this.Player.Dye[x].SetItem(int.Parse(dye[x].Attribute("id").Value));
this.Player.Dye[x].Prefix = (byte)int.Parse(dye[x].Attribute("prefix").Value);
}
// Refresh the player..
this.RefreshLoadedPlayer();
}
catch
{
MessageBox.Show("Failed to open equipment file!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
#endregion
#region "==> Bank / Safe Tab"
/// <summary>
/// Filters the bank/safe items list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtBankSafeFilter_TextChanged(object sender, EventArgs e)
{
this.lstBankSafeItems.SelectedIndexChanged -= this.lstBankSafeItems_SelectedIndexChanged;
var items = CreateFilteredItemList(this.txtBankSafeFilter.Text, this.cboBankSafeItemFilter.SelectedIndex);
this.lstBankSafeItems.DataSource = items.ToList();
this.lstBankSafeItems.SelectedIndexChanged += this.lstBankSafeItems_SelectedIndexChanged;
}
/// <summary>
/// Filters the bank/safe items list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboBankSafeItemFilter_SelectedIndexChanged(object sender, EventArgs e)
{
this.lstBankSafeItems.SelectedIndexChanged -= this.lstBankSafeItems_SelectedIndexChanged;
var items = CreateFilteredItemList(this.txtBankSafeFilter.Text, this.cboBankSafeItemFilter.SelectedIndex);
this.lstBankSafeItems.DataSource = items.ToList();
this.lstBankSafeItems.SelectedIndexChanged += this.lstBankSafeItems_SelectedIndexChanged;
}
/// <summary>
/// Filters the bank/safe prefix list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboBankSafePrefixCategory_SelectedIndexChanged(object sender, EventArgs e)
{
this.cboBankSafePrefix.SelectedIndexChanged -= this.cboBankSafePrefix_SelectedIndexChanged;
var item = CreateFilteredPrefixList(this.cboBankSafePrefixCategory.SelectedIndex);
this.cboBankSafePrefix.DataSource = item.ToList();
this.cboBankSafePrefix.SelectedIndexChanged += this.cboBankSafePrefix_SelectedIndexChanged;
}
/// <summary>
/// Selects the hovered bank/safe label.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bankSafeItem_Click(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.FromArgb(64, 127, 255, 0);
this.m_SelectedBankSafeItem = lbl;
lbl.Focus();
foreach (var label in this.m_BankSafeLabels.Where(label => label != this.m_SelectedBankSafeItem))
label.BackColor = Color.Transparent;
var slot = (int)this.m_SelectedBankSafeItem.Tag;
var item = (slot <= 39) ? this.Player.Bank1[slot] : this.Player.Bank2[slot - 40];
if (item != null && item.NetID != 0)
{
this.cboBankSafePrefixCategory.SelectedIndex = 0;
if (item.Prefix != 0)
{
for (var x = 0; x < this.cboBankSafePrefix.Items.Count; x++)
{
if (((ItemPrefix)this.cboBankSafePrefix.Items[x]).Id == item.Prefix)
{
this.cboBankSafePrefix.SelectedIndex = x;
return;
}
}
}
else
{
var none = (from ItemPrefix i in this.cboBankSafePrefix.Items
where i.Prefix == "None"
select i).SingleOrDefault();
if (none != null)
this.cboBankSafePrefix.SelectedItem = none;
}
}
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bankSafeItem_MouseEnter(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = Color.LightSkyBlue;
}
/// <summary>
/// Adjusts the hovered items background color.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bankSafeItem_MouseLeave(object sender, EventArgs e)
{
var lbl = (Label)sender;
lbl.BackColor = lbl != this.m_SelectedBankSafeItem ? Color.Transparent : Color.FromArgb(64, 127, 255, 0);
}
/// <summary>
/// Updates the current item.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstBankSafeItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedBankSafeItem == null)
return;
// Set the inventory item..
var item = (Item)this.lstBankSafeItems.SelectedItem;
var slot = (int)this.m_SelectedBankSafeItem.Tag;
int count;
if (slot <= 39)
{
this.Player.Bank1[slot].SetItem(item.NetID);
this.Player.Bank1[slot].Count = this.Player.Bank1[slot].Stack = this.Player.Bank1[slot].MaxStack;
if (item.NetID == 0)
this.Player.Bank1[slot].Count = this.Player.Bank1[slot].Stack = 0;
else
{
// Add the selected prefix to the item..
this.Player.Bank1[slot].Prefix = (byte)((ItemPrefix)this.cboBankSafePrefix.SelectedItem).Id;
}
count = this.Player.Bank1[slot].Count;
}
else
{
this.Player.Bank2[slot - 40].SetItem(item.NetID);
this.Player.Bank2[slot - 40].Count = this.Player.Bank2[slot - 40].Stack = this.Player.Bank2[slot - 40].MaxStack;
if (item.NetID == 0)
this.Player.Bank2[slot - 40].Count = this.Player.Bank2[slot - 40].Stack = 0;
else
{
// Add the selected prefix to the item..
this.Player.Bank2[slot - 40].Prefix = (byte)((ItemPrefix)this.cboBankSafePrefix.SelectedItem).Id;
}
count = this.Player.Bank2[slot - 40].Count;
}
// Update the item label..
this.m_SelectedBankSafeItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedBankSafeItem.Text = count.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedBankSafeItem, (slot <= 39) ? this.Player.Bank1[slot].ToString() : this.Player.Bank2[slot - 40].ToString());
}
/// <summary>
/// Updates the current items prefix.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboBankSafePrefix_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_SelectedBankSafeItem == null)
return;
// Set the bank/safe item..
var prefix = (ItemPrefix)this.cboBankSafePrefix.SelectedItem;
var slot = (int)this.m_SelectedBankSafeItem.Tag;
if (slot <= 39)
{
if (this.Player.Bank1[slot].NetID == 0)
return;
this.Player.Bank1[slot].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedBankSafeItem, this.Player.Bank1[slot].ToString());
}
else
{
if (this.Player.Bank2[slot - 40].NetID == 0)
return;
this.Player.Bank2[slot - 40].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedBankSafeItem, this.Player.Bank2[slot - 40].ToString());
}
}
/// <summary>
/// Prevents the stack count from having non-numeric characters typed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtBankSafeStackCount_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
/// <summary>
/// Updates the current items stack count with the entered amount.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtBankSafeStackCount_TextChanged(object sender, EventArgs e)
{
if (this.m_SelectedBankSafeItem == null)
return;
// Attempt to parse the new count..
int count;
if (!int.TryParse(this.txtBankSafeStackCount.Text, out count))
return;
// Ensure the slot has an item..
var slot = (int)this.m_SelectedBankSafeItem.Tag;
if (slot <= 39)
{
if (this.Player.Bank1[slot].NetID == 0)
return;
// Update the item and label..
this.Player.Bank1[slot].Count = this.Player.Bank1[slot].Stack = count;
this.m_SelectedBankSafeItem.Text = count.ToString();
}
else
{
if (this.Player.Bank2[slot - 40].NetID == 0)
return;
// Update the item and label..
this.Player.Bank2[slot - 40].Count = this.Player.Bank2[slot - 40].Stack = count;
this.m_SelectedBankSafeItem.Text = count.ToString();
}
}
/// <summary>
/// Deletes all items in the players bank.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteAllBankItems_Click(object sender, EventArgs e)
{
for (var x = 0; x < 40; x++)
{
// Update the item..
var item = this.Player.Bank1[x];
item.SetItem(0);
item.Count = 0;
// Update the item label..
this.m_BankSafeLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_BankSafeLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_BankSafeLabels[x], item.ToString());
}
}
/// <summary>
/// Deletes all the items in the players safe.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteAllSafeItems_Click(object sender, EventArgs e)
{
for (var x = 0; x < 40; x++)
{
// Update the item..
var item = this.Player.Bank2[x];
item.SetItem(0);
item.Count = 0;
// Update the item label..
this.m_BankSafeLabels[x + 40].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_BankSafeLabels[x + 40].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_BankSafeLabels[x + 40], item.ToString());
}
}
/// <summary>
/// Maxes all bank and safe stack counts.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMaxAllBankSafeStacks_Click(object sender, EventArgs e)
{
for (var x = 0; x < this.m_BankSafeLabels.Count; x++)
{
// Update the item..
var item = (x < 40) ? this.Player.Bank1[x] : this.Player.Bank2[x - 40];
if (item.Id != 0 && item.MaxStack > 1)
item.Count = item.Stack = item.MaxStack;
// Update the item label..
this.m_BankSafeLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_BankSafeLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_BankSafeLabels[x], item.ToString());
}
}
/// <summary>
/// Hacks all the bank and safe item stack counts.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnHackAllBankSafeStacks_Click(object sender, EventArgs e)
{
for (var x = 0; x < this.m_BankSafeLabels.Count; x++)
{
// Update the item..
var item = (x < 40) ? this.Player.Bank1[x] : this.Player.Bank2[x - 40];
if (item.Id != 0 && item.MaxStack > 1)
item.Count = item.Stack = int.MaxValue;
// Update the item label..
this.m_BankSafeLabels[x].Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_BankSafeLabels[x].Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_BankSafeLabels[x], item.ToString());
}
}
/// <summary>
/// Saves the players current bank items to an xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveBankItems_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Bank Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to save bank!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("BankSafe"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save bank!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Loop each item in the players bank..
foreach (var i in this.Player.Bank1)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("item", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("count", i.Count),
new XAttribute("prefix", i.Prefix)
}));
}
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a bank save file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadBankItems_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Bank Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
if (ofd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to open bank!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the bank dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("BankSafe");
if (root == null)
throw new InvalidDataException("File data is not valid.");
// Obtain the item entries..
var itemElements = root.Elements("item");
var items = itemElements as IList<XElement> ?? itemElements.ToList();
if (items.Count != 40)
throw new InvalidDataException("File data is not valid.");
// Update each item..
for (var x = 0; x < items.Count; x++)
{
int itemId;
int itemCount;
int itemPrefix;
int.TryParse(items[x].Attribute("id").Value, out itemId);
int.TryParse(items[x].Attribute("count").Value, out itemCount);
int.TryParse(items[x].Attribute("prefix").Value, out itemPrefix);
this.Player.Bank1[x].SetItem(itemId);
this.Player.Bank1[x].Count = itemCount;
this.Player.Bank1[x].Prefix = (byte)itemPrefix;
}
this.RefreshLoadedPlayer();
}
catch
{
MessageBox.Show("Failed to open bank!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
/// <summary>
/// Saves the players current safe items into an xml file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveSafeItems_Click(object sender, EventArgs e)
{
// Ask where to save to..
var sfd = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Safe Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to save safe!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Create the new xml document..
var xml = new XDocument(new XElement("BankSafe"));
if (xml.Root == null)
{
sfd.Dispose();
MessageBox.Show("Failed to save safe!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Loop each item in the players safe..
foreach (var i in this.Player.Bank2)
{
// Add each item to the xml document..
xml.Root.Add(new XElement("item", new object[]
{
new XAttribute("id", i.NetID),
new XAttribute("count", i.Count),
new XAttribute("prefix", i.Prefix)
}));
}
// Attempt to save the document..
xml.Save(sfd.FileName);
sfd.Dispose();
}
/// <summary>
/// Imports a safe save file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadSafeItems_Click(object sender, EventArgs e)
{
// Ask what to open..
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xml",
Filter = "TSGE Safe Files (*.xml)|*.xml|All files (*.*)|*.*",
InitialDirectory = Application.StartupPath,
ValidateNames = true
};
if (ofd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("Failed to open safe!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Load the safe dump..
var xml = XDocument.Load(ofd.FileName);
// Ensure the root element exists..
var root = xml.Element("BankSafe");
if (root == null)
throw new InvalidDataException("File data is not valid.");
// Obtain the item entries..
var itemElements = root.Elements("item");
var items = itemElements as IList<XElement> ?? itemElements.ToList();
if (items.Count != 40)
throw new InvalidDataException("File data is not valid.");
// Update each item..
for (var x = 0; x < items.Count; x++)
{
int itemId;
int itemCount;
int itemPrefix;
int.TryParse(items[x].Attribute("id").Value, out itemId);
int.TryParse(items[x].Attribute("count").Value, out itemCount);
int.TryParse(items[x].Attribute("prefix").Value, out itemPrefix);
this.Player.Bank2[x].SetItem(itemId);
this.Player.Bank2[x].Count = itemCount;
this.Player.Bank2[x].Prefix = (byte)itemPrefix;
}
this.RefreshLoadedPlayer();
}
catch
{
MessageBox.Show("Failed to open safe!\r\nThe selected file is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ofd.Dispose();
}
#endregion
#region "==> Hotkey Handlers"
/// <summary>
/// PreviewKeyDown event for inventory items to allow usage of hotkeys.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void inventoryItem_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Ensure we have a selected item..
if (this.m_SelectedInventoryItem == null)
return;
// Ensure the slot has a valid item..
var slot = (int)this.m_SelectedInventoryItem.Tag;
if (this.Player.Inventory[slot].NetID == 0)
return;
// Handle the key accordingly..
switch (e.KeyCode)
{
case Keys.D: // Delete current item..
{
// Delete the item..
this.Player.Inventory[slot].SetItem(0);
this.Player.Inventory[slot].Count = 0;
// Update the inventory label..
this.m_SelectedInventoryItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, this.Player.Inventory[slot].NetID));
this.m_SelectedInventoryItem.Text = "0";
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, this.Player.Inventory[slot].ToString());
break;
}
case Keys.P: // Set prefix..
{
// Update the prefix and tooltip..
var prefix = (ItemPrefix)this.cboInventoryPrefix.SelectedItem;
this.Player.Inventory[slot].Prefix = (byte)prefix.Id;
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, this.Player.Inventory[slot].ToString());
break;
}
case Keys.M: // Set max stack..
{
// Update the stack count..
var item = this.Player.Inventory[slot];
item.Count = item.Stack = item.MaxStack;
// Update the item label..
this.m_SelectedInventoryItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedInventoryItem.Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, item.ToString());
break;
}
case Keys.H: // Set hacked stack..
{
// Update the stack count..
var item = this.Player.Inventory[slot];
if (item.MaxStack > 1)
item.Count = item.Stack = 999;
// Update the item label..
this.m_SelectedInventoryItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedInventoryItem.Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedInventoryItem, item.ToString());
break;
}
case Keys.I: // Set item..
{
// Ensure we have a selected item..
var item = (Item)this.lstInventoryItems.SelectedItem;
if (item == null)
return;
// Set the item..
this.Player.Inventory[slot].SetItem(item.Id);
this.Player.Inventory[slot].Count = this.Player.Inventory[slot].Stack = this.Player.Inventory[slot].MaxStack;
break;
}
}
}
/// <summary>
/// PreviewKeyDown event for equipment items to allow usage of hotkeys.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void equipmentItem_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Ensure we have a selected item..
if (this.m_SelectedEquipmentItem == null)
return;
// Ensure the slot has a valid item..
var slot = (int)this.m_SelectedEquipmentItem.Tag;
if ((slot == 0 || slot == 1 || slot == 2) && this.Player.Armor[slot].NetID == 0)
return;
if ((slot == 3 || slot == 4 || slot == 5) && this.Player.Vanity[slot - 3].NetID == 0)
return;
if ((slot == 6 || slot == 7 || slot == 8) && this.Player.Dye[slot - 6].NetID == 0)
return;
if (slot >= 9 && this.Player.Accessories[slot - 9].NetID == 0)
return;
// Obtain the editing item.
Item item = null;
if (slot == 0 || slot == 1 || slot == 2)
item = this.Player.Armor[slot];
if (slot == 3 || slot == 4 || slot == 5)
item = this.Player.Vanity[slot - 3];
if (slot == 6 || slot == 7 || slot == 8)
item = this.Player.Dye[slot - 6];
if (slot >= 9)
item = this.Player.Accessories[slot - 9];
if (item == null)
return;
// Handle the key accordingly..
switch (e.KeyCode)
{
case Keys.D: // Delete current item..
{
item.SetItem(0);
item.Count = 0;
break;
}
case Keys.P: // Set prefix..
{
var prefix = (ItemPrefix)this.cboEquipmentPrefix.SelectedItem;
item.Prefix = (byte)prefix.Id;
break;
}
}
// Update the equipment label..
this.m_SelectedEquipmentItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedEquipmentItem.Text = item.MaxStack.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedEquipmentItem, item.ToString());
}
/// <summary>
/// PreviewKeyDown event for bank and safe items to allow usage of hotkeys.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bankSafeItem_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Ensure we have a selected item..
if (this.m_SelectedBankSafeItem == null)
return;
// Ensure the slot has a valid item..
var slot = (int)this.m_SelectedBankSafeItem.Tag;
if (((slot <= 39 && this.Player.Bank1[slot].NetID == 0) ||
(slot > 39 && this.Player.Bank2[slot - 40].NetID == 0)) &&
e.KeyCode != Keys.I)
return;
// Obtain the editing item..
var item = slot <= 39 ? this.Player.Bank1[slot] : this.Player.Bank2[slot - 40];
// Handle the key accordingly..
switch (e.KeyCode)
{
case Keys.D: // Delete current item..
{
item.SetItem(0);
item.Count = 0;
break;
}
case Keys.P: // Set prefix..
{
var prefix = (ItemPrefix)this.cboBankSafePrefix.SelectedItem;
item.Prefix = (byte)prefix.Id;
break;
}
case Keys.M: // Set max stack..
{
item.Count = item.Stack = item.MaxStack;
break;
}
case Keys.H: // Set hacked stack..
{
if (item.MaxStack > 1)
item.Count = item.Stack = 999;
break;
}
case Keys.I: // Set item..
{
// Ensure we have a selected item..
var selItem = (Item)this.lstBankSafeItems.SelectedItem;
if (selItem == null)
return;
// Set the item..
item.SetItem(selItem.Id);
item.Count = item.Stack = item.MaxStack;
break;
}
}
// Update the item label..
this.m_SelectedBankSafeItem.Image = new Bitmap(string.Format("{0}\\Data\\Items\\item_{1}.png", Application.StartupPath, item.NetID));
this.m_SelectedBankSafeItem.Text = item.Count.ToString();
this.m_Tooltip.SetToolTip(this.m_SelectedBankSafeItem, item.ToString());
}
#endregion
/// <summary>
/// Adjusts the form size for each tab.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tcMainTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.tcMainTabControl.SelectedIndex)
{
case 0: // Main Player
case 1: // Buffs
case 3: // Equipment
{
this.Width = DpiHelper.ScaleAsDpi(628);
this.Height = DpiHelper.ScaleAsDpi(493);
break;
}
case 2: // Inventory
{
this.Width = DpiHelper.ScaleAsDpi(810);
this.Height = DpiHelper.ScaleAsDpi(493);
break;
}
case 4: // Bank / Safe
{
this.Width = DpiHelper.ScaleAsDpi(705);
this.Height = DpiHelper.ScaleAsDpi(560);
break;
}
}
}
}
}
|
gpl-3.0
|
OpenJEVis/JEAPI-WS
|
src/main/java/org/jevis/jeapi/ws/REQUEST.java
|
3954
|
/**
* Copyright (C) 2016 Envidatec GmbH <info@envidatec.com>
*
* This file is part of JEAPI-WS.
*
* JEAPI-WS 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 in version 3.
*
* JEAPI-WS 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
* JEAPI-WS. If not, see <http://www.gnu.org/licenses/>.
*
* JEAPI-WS is part of the OpenJEVis project, further project information are
* published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.jeapi.ws;
/**
* Simple JEWebService URL building constats interfaces
*
* @TODO Add an URL building function
* @author fs
*/
public interface REQUEST {
public static String API_PATH_V1 = "JEWebService/v1/";
public interface OBJECTS {
public static String PATH = "objects/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=";
public static String ONLY_ROOT = "root=";
}
public interface ATTRIBUTES {
public static String PATH = "attributes/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
}
public interface SAMPLES {
public static String PATH = "samples/";
public interface OPTIONS {
public static String FROM = "from=";
public static String UNTIL = "until=";
public static String LASTEST = "onlyLatest=";
}
public interface FILES {
public static String PATH = "files/";
public interface OPTIONS {
public static String FILENAME = "filename=";
public static String TIMESTAMP = "timestamp=";
}
}
}
}
}
public interface CLASS_ICONS {
public static String PATH = "classicons/";
}
public interface CLASSES {
public static String PATH = "classes/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
}
public interface ICON {
public static String PATH = "icon/";
}
public interface TYPES {
public static String PATH = "types/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
}
}
}
public interface TYPES {
public static String PATH = "types/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
}
}
public interface RELATIONSHIPS {
public static String PATH = "relationships/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
public static String FROM = "from=";
public static String TO = "to=";
public static String TYPE = "type=";
}
}
public interface CLASS_RELATIONSHIPS {
public static String PATH = "classrelationships/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
public static String FROM = "from=";
public static String TO = "to=";
public static String TYPE = "type=";
}
}
public interface JEVISUSER {
public static String PATH = "user/";
public interface OPTIONS {
public static String INCLUDE_RELATIONSHIPS = "rel=true";
}
}
}
|
gpl-3.0
|
mdlenslyon/moodle
|
lib/yui/build/moodle-core-lockscroll/moodle-core-lockscroll-debug.js
|
4675
|
YUI.add('moodle-core-lockscroll', function (Y, NAME) {
/**
* Provides the ability to lock the scroll for a page, allowing nested
* locking.
*
* @module moodle-core-lockscroll
*/
/**
* Provides the ability to lock the scroll for a page.
*
* This is achieved by applying the class 'lockscroll' to the body Node.
*
* Nested widgets are also supported and the scroll lock is only removed
* when the final plugin instance is disabled.
*
* @class M.core.LockScroll
* @extends Plugin.Base
*/
Y.namespace('M.core').LockScroll = Y.Base.create('lockScroll', Y.Plugin.Base, [], {
/**
* Whether the LockScroll has been activated.
*
* @property _enabled
* @type Boolean
* @protected
*/
_enabled: false,
/**
* Handle destruction of the lockScroll instance, including disabling
* of the current instance.
*
* @method destructor
*/
destructor: function() {
this.disableScrollLock();
},
/**
* Start locking the page scroll.
*
* This is achieved by applying the lockscroll class to the body Node.
*
* A count of the total number of active, and enabled, lockscroll instances is also kept on
* the body to ensure that premature disabling does not occur.
*
* @method enableScrollLock
* @param {Boolean} forceOnSmallWindow Whether to enable the scroll lock, even for small window sizes.
* @chainable
*/
enableScrollLock: function(forceOnSmallWindow) {
if (this.isActive()) {
Y.log('LockScroll already active. Ignoring enable request', 'warn', 'moodle-core-lockscroll');
return;
}
var dialogueHeight = this.get('host').get('boundingBox').get('region').height,
// Most modern browsers use win.innerHeight, but some older versions of IE use documentElement.clientHeight.
// We fall back to 0 if neither can be found which has the effect of disabling scroll locking.
windowHeight = Y.config.win.innerHeight || Y.config.doc.documentElement.clientHeight || 0;
if (!forceOnSmallWindow && dialogueHeight > (windowHeight - 10)) {
Y.log('Dialogue height greater than window height. Ignoring enable request.', 'warn', 'moodle-core-lockscroll');
return;
}
Y.log('Enabling LockScroll.', 'debug', 'moodle-core-lockscroll');
this._enabled = true;
var body = Y.one(Y.config.doc.body);
// We use a CSS class on the body to handle the actual locking.
body.addClass('lockscroll');
// Increase the count of active instances - this is used to ensure that we do not
// remove the locking when parent windows are still open.
// Note: We cannot use getData here because data attributes are sandboxed to the instance that created them.
var currentCount = parseInt(body.getAttribute('data-activeScrollLocks'), 10) || 0,
newCount = currentCount + 1;
body.setAttribute('data-activeScrollLocks', newCount);
Y.log("Setting the activeScrollLocks count from " + currentCount + " to " + newCount,
'debug', 'moodle-core-lockscroll');
return this;
},
/**
* Stop locking the page scroll.
*
* The instance may be disabled but the scroll lock not removed if other instances of the
* plugin are also active.
*
* @method disableScrollLock
* @chainable
*/
disableScrollLock: function() {
if (this.isActive()) {
Y.log('Disabling LockScroll.', 'debug', 'moodle-core-lockscroll');
this._enabled = false;
var body = Y.one(Y.config.doc.body);
// Decrease the count of active instances.
// Note: We cannot use getData here because data attributes are sandboxed to the instance that created them.
var currentCount = parseInt(body.getAttribute('data-activeScrollLocks'), 10) || 1,
newCount = currentCount - 1;
if (currentCount === 1) {
body.removeClass('lockscroll');
}
body.setAttribute('data-activeScrollLocks', currentCount - 1);
Y.log("Setting the activeScrollLocks count from " + currentCount + " to " + newCount,
'debug', 'moodle-core-lockscroll');
}
return this;
},
/**
* Return whether scroll locking is active.
*
* @method isActive
* @return Boolean
*/
isActive: function() {
return this._enabled;
}
}, {
NS: 'lockScroll',
ATTRS: {
}
});
}, '@VERSION@', {"requires": ["plugin", "base-build"]});
|
gpl-3.0
|
fernandomv3/Molecule-Viewer
|
src/render/GLProgram.cpp
|
4471
|
#include "render/GLProgram.h"
#include <cstdio>
#include <string.h>
GLProgram::GLProgram(){
this->vertexShader =0;
this->fragmentShader=0;
this->program=0;
this->uniforms = new struct uniforms;
this->uniforms->unifModelMatrix = 0;
this->uniforms->unifBlockMatrices =0;
this->uniforms->unifBlockDirectionalLights=0;
this->uniforms->unifBlockAmbientLight =0;
}
GLuint GLProgram::getVertexShader(){
return this->vertexShader;
}
GLuint GLProgram::getFragmentShader(){
return this->fragmentShader;
}
GLuint GLProgram::getProgram(){
return this->program;
}
void GLProgram::setVertexShader(GLuint vertexShader){
this->vertexShader = vertexShader;
}
void GLProgram::setFragmentShader(GLuint fragmentShader){
this->fragmentShader = fragmentShader;
}
void GLProgram::setProgram(GLuint program){
this->program = program;
}
char* GLProgram::getSourceFromFile(char* filename){//rewrite not using fopen()
FILE *f = fopen(filename, "r");
void *buffer;
if (!f) {
fprintf(stderr, "Unable to open %s for reading\n", filename);
return NULL;
}
fseek(f, 0, SEEK_END);
int *length=0;
*length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = new char[*length+1];
*length = fread(buffer, 1, *length, f);
fclose(f);
((char*)buffer)[*length] = '\0';
return (char*)buffer;
}
GLuint GLProgram::compileShader(GLenum type, char* source){
GLint length = strlen(source);
GLuint shader;
GLint shaderOk;
if (!source)
return 0;
shader = glCreateShader(type);
glShaderSource(shader, 1, (const GLchar**)&source, &length);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &shaderOk);
if (!shaderOk) {
fprintf(stderr, "Failed to compile:\n");
show_info_log(shader, glGetShaderiv, glGetShaderInfoLog);
glDeleteShader(shader);
return 0;
}
return shader;
}
GLuint GLProgram::linkProgram(GLuint vertexShader, GLuint fragmentShader){
GLint programOk;
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &programOk);
if (!programOk) {
fprintf(stderr, "Failed to link shader program:\n");
show_info_log(program, glGetProgramiv, glGetProgramInfoLog);
glDeleteProgram(program);
return 0;
}
return program;
}
void GLProgram::show_info_log(GLuint object,PFNGLGETSHADERIVPROC glGet__iv,PFNGLGETSHADERINFOLOGPROC glGet__InfoLog){
GLint log_length;
char *log;
glGet__iv(object, GL_INFO_LOG_LENGTH, &log_length);
log = new char[log_length];
glGet__InfoLog(object, log_length, NULL, log);
fprintf(stderr, "%s", log);
delete[] log;
}
GLuint GLProgram::getAttrPosition(){
return this->attrPosition;
}
void GLProgram::setAttrPosition(GLuint attrPosition){
this->attrPosition = attrPosition;
}
GLuint GLProgram::getAttrNormal(){
return this->attrNormal;
}
void GLProgram::setAttrNormal(GLuint attrNormal){
this->attrNormal = attrNormal;
}
Uniforms GLProgram::getUniforms(){
return this->uniforms;
}
void GLProgram::setUniforms(Uniforms uniforms){
this->uniforms = uniforms;
}
GLProgram::~GLProgram(){
if(this->uniforms != NULL) delete uniforms;
}
GLuint GLProgram::getTessControlShader(){
return this->tessControlShader;
}
GLuint GLProgram::getTessEvaluationShader(){
return this->tessEvaluationShader;
}
void GLProgram::setTessEvaluationShader(GLuint tessEvaluationShader){
this->tessEvaluationShader = tessEvaluationShader;
}
void GLProgram::setTessControlShader(GLuint tessControlShader){
this->tessControlShader = tessControlShader;
}
GLuint GLProgram::linkProgramTessellation(GLuint vertexShader, GLuint fragmentShader, GLuint tessControlShader, GLuint tessEvaluationShader){
GLint programOk;
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, tessControlShader);
glAttachShader(program, tessEvaluationShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &programOk);
if (!programOk) {
fprintf(stderr, "Failed to link shader program:\n");
show_info_log(program, glGetProgramiv, glGetProgramInfoLog);
glDeleteProgram(program);
return 0;
}
return program;
}
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.