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 |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ECCentral.QueryFilter.IM;
using ECCentral.BizEntity.IM;
namespace ECCentral.Service.IM.IDataAccess
{
public interface IProductRelatedDA
{
/// <summary>
/// 根据query得到相关商品信息
/// </summary>
/// <param name="query"></param>
/// <param name="totalCount"></param>
/// <returns></returns>
DataTable GetProductRelatedByQuery(ProductRelatedQueryFilter query, out int totalCount);
/// <summary>
/// 创建ItemRelated
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
int CreateProductRelate(ProductRelatedInfo info);
/// <summary>
/// Delete
/// </summary>
/// <param name="sysNo"></param>
void DeleteProductRelate(string sysNo);
/// <summary>
/// 更新优先级
/// </summary>
/// <param name="info"></param>
void UpdateProductRelatePriority(ProductRelatedInfo info);
}
}
| ZeroOne71/ql | 02_ECCentral/03_Service/02_IM/ECCentral.Service.IM.IDataAccess/IProductRelatedDA.cs | C# | gpl-3.0 | 1,096 |
console.log('Hello world!')
require('./src')
| VevoxDigital/Iota | index.js | JavaScript | gpl-3.0 | 45 |
# Copyright 2008-2010, Red Hat, Inc
# Dan Radez <dradez@redhat.com>
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
__author__ = 'Dan Radez'
__version__ = '0.7.1'
__license__ = 'GPLv3'
| oppianmatt/django-loki | src/loki/__init__.py | Python | gpl-3.0 | 429 |
/*
* Created by: Anastassios Martakos
*
* Copyright 2016 Anastassios Martakos
*
* 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.
*/
#include <string>
#include <vector>
#include "huffman.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <unordered_map>
#include <stdlib.h>
#include <math.h>
#ifndef NULL
#define NULL 0
#endif
Node::Node(char* c, const unsigned int& freq) {
right = NULL;
left = NULL;
character = c;
this->freq = freq;
parent = NULL;
}
Node::~Node(void) {
if(character != NULL)
delete character;
if(left != NULL)
delete left;
if(right != NULL)
delete right;
}
LL::LL(Node* item) {
next = NULL;
if(item != NULL)
tree = item;
else
tree = NULL;
}
LL::~LL(void) {
if(next != NULL)
delete next;
next = NULL;
}
// huffman tree implemented as a binary tree filled in bottom up
BinaryTree::BinaryTree(LL* linkedlist, const unsigned int& size) {
first = NULL;
std::vector<Node* > tmp_ll;
for(unsigned int i = 0; i < size; i++)
tmp_ll.push_back(linkedlist->get(i)->tree);
while(true) {
Node* tmp = new Node();
tmp->freq = tmp_ll[0]->freq + tmp_ll[1]->freq;
tmp->left = tmp_ll[0];
tmp->right = tmp_ll[1];
tmp_ll[0]->parent = tmp;
tmp_ll[1]->parent = tmp;
tmp_ll.erase(tmp_ll.begin(), tmp_ll.begin() + 2);
std::vector<Node* >::iterator i = tmp_ll.begin();
if(tmp_ll.size() == 0) {
tmp_ll.push_back(tmp);
break;
}
while(i != tmp_ll.end()) {
if((*i)->freq == tmp->freq || (*i)->freq > tmp->freq || i == tmp_ll.end() - 1) {
tmp_ll.insert(i, tmp);
break;
}
i++;
}
if(tmp_ll.size() == 1)
break;
}
first = tmp_ll[0];
}
BinaryTree::~BinaryTree(void) {
if(first != NULL)
delete first;
}
void BinaryTree::print(Node const * next, unsigned int intent, std::string curr_map) {
Node const * curr_node = next;
if(curr_node == NULL)
curr_node = first;
if(curr_node->left != NULL)
print(curr_node->left, ++intent, curr_map + '0');
if(curr_node->right != NULL)
print(curr_node->right, ++intent, curr_map + '1');
if(curr_node->character != NULL) {
const char tmp[] = { *(curr_node->character), '\0' };
std::cout << std::setw(intent) << ' ' << tmp << " : " << curr_map << std::endl;
}
}
void BinaryTree::generateMapping(std::unordered_map<char, std::vector<bool> >* map, Node* curr_node, std::vector<bool> curr_map) {
if(map == NULL)
map = new std::unordered_map<char, std::vector<bool> >();
if(curr_node == NULL)
curr_node = first;
// well then lol..
if(curr_node == NULL)
return void();
if(curr_node->left != NULL) {
std::vector<bool> new_map = curr_map;
new_map.push_back(false);
generateMapping(map, curr_node->left, new_map);
}
if(curr_node->right != NULL) {
std::vector<bool> new_map = curr_map;
new_map.push_back(true);
generateMapping(map, curr_node->right, new_map);
}
// left and right Nodes are NULL which means we are
// at a leaf Node, now assign the mapping to the it
if(curr_node->character != NULL) {
map->emplace(*(curr_node->character), curr_map);
}
}
Node* BinaryTree::getFirst(void) {
return first;
}
void LL::insert(Node* item) {
if(tree == NULL && next == NULL)
tree = item;
else if(next == NULL)
next = new LL(item);
else
next->insert(item);
}
int* LL::getFreq(const char& c) {
if(tree == NULL)
return 0;
if(*(tree->character) == c) {
return &(tree->freq);
}else{
if(next == NULL)
return NULL;
else
return next->getFreq(c);
}
}
LL* LL::get(const int& i, const int curr) {
if(i == curr) {
return this;
}else{
if(next == NULL)
return NULL;
else
return next->get(i, curr + 1);
}
}
std::vector<bool>* Huffman::compress(const char* input, const size_t& size) {
encode = true;
LL* linkedlist = new LL();
unsigned int ll_size = 0;
for(unsigned int i = 0; i < size; i++) {
int* freq = linkedlist->getFreq(input[i]);
if(freq == NULL) {
linkedlist->insert(new Node(new char(input[i])));
ll_size++;
}else{
(*freq)++;
}
}
// sort linked list
// I will use bubblesort, because we will have not so many
Node* t0;
for(int j = ll_size - 1; j > 0; j--) {
for(int i = 0; i < j; i++) {
LL* ll_f = linkedlist->get(i);
LL* ll_s = linkedlist->get(i+1);
if(ll_f->tree->freq > ll_s->tree->freq) {
t0 = ll_f->tree;
ll_f->tree = ll_s->tree;
ll_s->tree = t0;
}
}
}
BinaryTree* bst = new BinaryTree(linkedlist, ll_size);
std::unordered_map<char, std::vector<bool> >* map = new std::unordered_map<char, std::vector<bool> >();
bst->generateMapping(map);
encoded = (void*)(new std::vector<bool>());
for(unsigned int i = 0; i < size; i++) {
std::vector<bool>::iterator iter = map->at(input[i]).begin();
while(iter != map->at(input[i]).end()) {
((std::vector<bool>*)encoded)->push_back(*iter);
iter++;
}
}
delete map;
this->encoding = new Huffman::Encoding();
this->encoding->data = new std::vector<char>();
this->encoding->freqs = new std::vector<int>();
for(int i = ll_size - 1; i >= 0 ; i--) {
this->encoding->data->push_back(*(linkedlist->get(i)->tree->character));
this->encoding->freqs->push_back(linkedlist->get(i)->tree->freq);
}
delete linkedlist;
delete bst;
return (std::vector<bool>*)encoded;
}
Huffman::~Huffman(void) {
if(encoded != NULL) {
if(encode)
delete (std::vector<bool>*)encoded;
else
delete (std::string*)encoded;
}
if(encoding != NULL)
delete encoding;
}
Huffman::Encoding::~Encoding(void) {
if(data != NULL)
delete data;
delete freqs;
}
std::string* Huffman::decompress(const std::vector<bool>* input) {
encode = false;
if(encoding == NULL || encoding->data == NULL || encoding->freqs == NULL)
throw "no encoding set";
encoded = (void*)(new std::string());
LL* linkedlist = new LL();
unsigned int ll_size = 0;
for(unsigned int i = 0; i < encoding->data->size(); i++) {
linkedlist->insert(new Node(new char(encoding->data->at(i)), encoding->freqs->at(i)));
ll_size++;
}
BinaryTree* bst = new BinaryTree(linkedlist, ll_size);
Node* curr_node = bst->getFirst();
for(unsigned int i = 0; i < input->size() - overflow; i++) {
if(!input->at(i)) {
if(curr_node->left != NULL)
curr_node = curr_node->left;
}else if(input->at(i)) {
if(curr_node->right != NULL)
curr_node = curr_node->right;
}
if(curr_node->left == NULL && curr_node->right == NULL) {
if(curr_node->character != NULL) {
const char tmp[] = {*(curr_node->character), '\0'};
*((std::string*)encoded) += std::string(tmp);
}
curr_node = bst->getFirst();
}
}
delete linkedlist;
delete bst;
return (std::string*)encoded;
}
void Huffman::setEncoding(Huffman::Encoding* encoding) {
if(this->encoding != NULL)
delete this->encoding;
this->encoding = encoding;
}
Huffman::Encoding* Huffman::getEncoding(void) {
return encoding;
}
Huffman::Encoding* Huffman::parseEncoding(std::string& str_enc) {
Huffman::Encoding* enc = new Huffman::Encoding();
enc->data = new std::vector<char>();
enc->freqs = new std::vector<int>();
std::string* tmp = new std::string();
std::string::const_iterator i = str_enc.begin();
while(i != str_enc.end()) {
enc->data->push_back(*i);
i++;
while(true) {
if(*i == ';')
break;
char ttt[] = {*i, '\0'};
*tmp += std::string(ttt);
i++;
}
enc->freqs->push_back(std::stoi(*tmp));
delete tmp;
tmp = new std::string();
i++;
}
if(tmp != NULL)
delete tmp;
return enc;
}
void* Huffman::getEncoded(void) {
return encoded;
}
std::vector<char>* Huffman::generateHeader(void) {
if(encoding == NULL)
return NULL;
std::vector<char>* final = new std::vector<char>();
for(int i = encoding->data->size() - 1; i >= 0; i--) {
final->push_back(encoding->data->at(i));
std::string s = std::to_string(encoding->freqs->at(i));
const char* tmp = s.c_str();
for(unsigned int j = 0; j < s.size(); j++)
final->push_back(tmp[j]);
final->push_back(';');
}
return final;
}
void Huffman::writeToFile(const char* file, const bool write_header) {
std::vector<char>* header = generateHeader();
std::fstream outfile;
outfile.open(file, std::ios::out | std::ios::binary);
unsigned int alloc_bytes = ceil(((std::vector<bool>*)encoded)->size() / 8) + 1;
unsigned char* bin = new unsigned char[alloc_bytes];
// std::cout << "size: " << encoded->size() << std::endl;
// std::cout << "allocating: " << alloc_bytes << " bytes" << std::endl;
unsigned int overflow = 0;
for(unsigned int i = 0; i < alloc_bytes; i++) {
int conv[8];
for(unsigned int j = 0; j < 8; j++) {
if((i * 8) + j < ((std::vector<bool>*)encoded)->size()) {
if(((std::vector<bool>*)encoded)->at((i * 8) + j))
conv[j] = 1;
else
conv[j] = 0;
}else{
conv[j] = 1;
overflow++;
}
}
bin[i] = conv[7] << 7 |
conv[6] << 6 |
conv[5] << 5 |
conv[4] << 4 |
conv[3] << 3 |
conv[2] << 2 |
conv[1] << 1 |
conv[0] << 0;
}
outfile << overflow;
for(unsigned int m = 0; m < header->size(); m++) {
outfile << header->at(m);
}
for(unsigned int n = 0; n < alloc_bytes; n++)
outfile << bin[n];
outfile.close();
if(bin != NULL)
delete bin;
if(header != NULL)
delete header;
}
void Huffman::writeToStringFile(const char* file) {
std::fstream outfile;
outfile.open(file, std::ios::out);
std::string::iterator i = ((std::string*)encoded)->begin();
while(i != ((std::string*)encoded)->end()) {
outfile << *i;
i++;
}
outfile << '\n';
outfile.close();
}
void Huffman::setOverflow(unsigned int& overflow) {
this->overflow = overflow;
}
void Huffman::prepareCompressed(std::string& header, std::vector<bool>* input, unsigned int& overflow, const char* file) {
std::ifstream infile;
infile.open(file, std::ios::in | std::ios::binary | std::ios::ate);
long size = infile.tellg();
infile.seekg(0, std::ios::beg);
char* buff = new char[size];
infile.read(buff, size);
infile.close();
const char tmp[] = {buff[0], '\0'};
overflow = atoi(tmp);
unsigned int counter = 1;
while(true) {
if(buff[counter] == ';') {
if(buff[counter + 2] != '0' &&
buff[counter + 2] != '1' &&
buff[counter + 2] != '2' &&
buff[counter + 2] != '3' &&
buff[counter + 2] != '4' &&
buff[counter + 2] != '5' &&
buff[counter + 2] != '6' &&
buff[counter + 2] != '7' &&
buff[counter + 2] != '8' &&
buff[counter + 2] != '9' &&
buff[counter + 2] != ';')
break;
}
const char tmp[] = {buff[counter], '\0'};
header += std::string(tmp);
counter++;
}
for(int i = ++counter; i < size; i++) {
for(int j = 0; j < 8; j++) {
const bool tmp = (buff[i] & (1 << j)) ? true : false;
input->push_back(tmp);
}
}
header += ";";
delete buff;
infile.close();
}
| realm01/huffman-cpp | src/huffman.cpp | C++ | gpl-3.0 | 11,781 |
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from restorepoint import RestorePoint
import argparse
import logging
import os
import shutil
import sys
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-u',
'--username',
required=True,
help='Username to connect to RestorePoint'
)
parser.add_argument(
'-p',
'--password',
required=True,
help='Password to connect to RestorePoint'
)
parser.add_argument(
'-H',
'--hostname',
help='RestorePoint Hostname',
required=True
)
parser.add_argument(
'-k',
'--insecure',
action='store_true',
help='Skip SSL cert verification',
default=False
)
parser.add_argument(
'-s',
'--sleep',
type=int,
help='Sleep interval between device backups',
default=2
)
parser.add_argument(
'-e',
'--errors-only',
action='store_true',
help='Print errors only',
default=False
)
subparsers = parser.add_subparsers(
dest='action',
help='Available commands'
)
subparsers.add_parser(
'list',
help='List devices'
)
backup_parser = subparsers.add_parser(
'backup',
help='Backup one or more devices'
)
backup_parser.add_argument(
'--exclude',
action='append',
help='Exclude one or more devices from backup'
)
backup_parser.add_argument(
'DEVICE',
default='all',
nargs='*',
help='Optinal device name to backup (Default: all)'
)
export_parser = subparsers.add_parser(
'export',
help='Export the latest backup of one or more devices'
)
export_parser.add_argument(
'-d',
'--destination',
help='Destination directory (Default: PWD)',
default=None,
required=False
)
export_parser.add_argument(
'-i',
'--ignore-disabled',
help='Ignore disabled devices',
action='store_true',
default=True
)
export_parser.add_argument(
'-f',
'--force-backup',
help='Force a backup before exporting it',
action='store_true',
default=False
)
export_parser.add_argument(
'-c',
'--clean',
help='Empty destination dir if set',
action='store_true',
default=False
)
export_parser.add_argument(
'--prune',
help='Prune backups (keep 10 most recent only)',
action='store_true',
default=False
)
export_parser.add_argument(
'--exclude',
action='append',
help='Exclude one or more devices from export'
)
export_parser.add_argument(
'DEVICE',
default='all',
nargs='*',
help='Optinal device name to export (Default: all)'
)
prune_parser = subparsers.add_parser(
'prune',
help='Prune the latest backup of one or more devices'
)
prune_parser.add_argument(
'--exclude',
action='append',
help='Exclude one or more devices from prune'
)
prune_parser.add_argument(
'--keep',
type=int,
default=10,
help='Number of configurations to keep'
)
prune_parser.add_argument(
'DEVICE',
default='all',
nargs='*',
help='Optinal device name to prune (Default: all)'
)
return parser.parse_args()
def empty_dir(directory):
for f in os.listdir(directory):
file_path = os.path.join(directory, f)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
logger.error(e)
def determine_device_ids(rp, device_names):
# Determine the device IDs
device_ids = []
for dev in device_names:
dev_id = rp.get_device_id_from_name(dev)
if not dev_id:
logger.error('Could not determine device ID of device {}'.format(dev))
else:
device_ids.append(dev_id)
return device_ids
def get_device_ids(rp, device_names, excluded=None, ignore_disabled=False):
if device_names == ['all'] or device_names == 'all':
device_ids = rp.get_all_device_ids(ignore_disabled=ignore_disabled)
else:
device_ids = determine_device_ids(rp, device_names)
if excluded:
device_ids = [x for x in device_ids if rp.get_device_name_from_id(x) not in excluded]
return device_ids
def display_backup_results(rp, result, errors_only=False):
for dev_id, backup_result in result.items():
dev_name = rp.get_device(dev_id)['Name']
if errors_only:
if not backup_result:
print('{}: Backup failed!'.format(dev_name))
else:
print(
'{}: {}'.format(
dev_name,
'Backup succeeded' if backup_result else 'Backup failed!'
)
)
def display_export_results(rp, res, errors_only=False):
device_ids = rp.get_all_device_ids()
latest_backups = rp.latest_backups(device_ids)
for backup_id, backup_result in res:
dev_name = None
for b in latest_backups:
if b['ID'] == backup_id:
dev_name = rp.get_device(b['DeviceID'])['Name']
if errors_only:
if backup_result is None:
print('{}: Export failed!'.format(dev_name))
else:
print(
'{}: {}'.format(
dev_name,
'Export succeeded' if backup_result else 'Export failed!'
)
)
def main():
args = parse_args()
rp = RestorePoint(
hostname=args.hostname,
username=args.username,
password=args.password,
verify=not args.insecure
)
exit_code = 0
if args.action == 'list':
device_names = sorted(
[x['Name'] for x in rp.list_devices()],
key=lambda s: s.lower()
)
for dev in device_names:
print(dev)
elif args.action == 'backup':
device_ids = get_device_ids(rp, args.DEVICE, args.exclude)
if not device_ids:
print('No devices selected for backup', file=sys.stderr)
sys.exit(4)
# Backup the devices whose IDs could be determined
res = rp.backup_devices_block(device_ids, sleep_interval=args.sleep)
# Print results
display_backup_results(rp, res, args.errors_only)
# Set the exit code to 1 if at least one backup failed
exit_code = 0 if all(res.values()) else 1
elif args.action == 'export':
# Clean/empty the destination dir if requested
if args.clean and args.destination is None:
print(
'You need to set the destination dir when --clean is set',
file=sys.stderr
)
sys.exit(3)
elif args.clean:
empty_dir(args.destination)
device_ids = get_device_ids(rp, args.DEVICE, args.exclude)
if not device_ids:
print('No devices selected for export', file=sys.stderr)
sys.exit(4)
# Optionally force a new backup
if args.force_backup:
backup_res = rp.backup_devices_block(device_ids,
sleep_interval=args.sleep)
# Export the devices whose IDs could be determined
res = rp.export_latest_backups(device_ids, args.destination)
# Print results
if args.force_backup:
display_backup_results(rp, backup_res, args.errors_only)
exit_code = 0 if all(backup_res.values()) else 1
display_export_results(rp, res, args.errors_only)
if args.prune:
for dev_id in device_ids:
try:
rp.prune_backups(dev_id)
except Exception as exc:
print('Something went wrong while pruning backups of'
' {}: {}'.format(dev_id, exc))
elif args.action == 'prune':
device_ids = get_device_ids(rp, args.DEVICE, args.exclude)
for dev_id in device_ids:
rp.prune_backups(dev_id, keep=args.keep)
sys.exit(exit_code)
if __name__ == '__main__':
main()
| pschmitt/python-restorepoint | restorepoint/rp.py | Python | gpl-3.0 | 8,649 |
class Solution:
def simplifyPath(self, path: str) -> str:
path_components = path.split('/')
starting_path = []
for path_component in path_components:
if not path_component: # '//'
continue
if path_component == '.':
continue
if path_component == '..':
starting_path = starting_path[:-1]
continue
starting_path.append(path_component)
return '/' + '/'.join(starting_path)
| 1337/yesterday-i-learned | leetcode/71m.py | Python | gpl-3.0 | 518 |
package ch.cyberduck.core.dropbox;
/*
* Copyright (c) 2002-2022 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import ch.cyberduck.core.PasswordCallback;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.exception.BackgroundException;
import ch.cyberduck.core.exception.InteroperabilityException;
import ch.cyberduck.core.exception.NotfoundException;
import ch.cyberduck.core.features.Delete;
import ch.cyberduck.core.preferences.HostPreferences;
import ch.cyberduck.core.threading.ScheduledThreadPool;
import ch.cyberduck.core.transfer.TransferStatus;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.files.DbxUserFilesRequests;
import com.dropbox.core.v2.files.DeleteArg;
import com.dropbox.core.v2.files.DeleteBatchJobStatus;
import com.dropbox.core.v2.files.DeleteBatchLaunch;
import com.dropbox.core.v2.files.DeleteBatchResultEntry;
import com.google.common.util.concurrent.Uninterruptibles;
public class DropboxBatchDeleteFeature implements Delete {
private final DropboxSession session;
public DropboxBatchDeleteFeature(final DropboxSession session) {
this.session = session;
}
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final ScheduledThreadPool scheduler = new ScheduledThreadPool();
try {
for(Path f : files.keySet()) {
callback.delete(f);
}
final DbxUserFilesRequests requests = new DbxUserFilesRequests(session.getClient());
final DeleteBatchLaunch job = requests.deleteBatch(files.keySet().stream().map(f -> new DeleteArg(f.getAbsolute())).collect(Collectors.toList()));
final CountDownLatch signal = new CountDownLatch(1);
final AtomicReference<BackgroundException> failure = new AtomicReference<>();
scheduler.repeat(() -> {
try {
// Poll status
final DeleteBatchJobStatus status = requests.deleteBatchCheck(job.getAsyncJobIdValue());
if(status.isComplete()) {
final List<DeleteBatchResultEntry> entries = status.getCompleteValue().getEntries();
for(DeleteBatchResultEntry entry : entries) {
if(entry.isFailure()) {
switch(entry.getFailureValue().tag()) {
case PATH_LOOKUP:
failure.set(new NotfoundException(entry.getFailureValue().toString()));
break;
default:
failure.set(new InteroperabilityException());
}
}
}
signal.countDown();
}
if(status.isFailed()) {
signal.countDown();
}
}
catch(DbxException e) {
failure.set(new DropboxExceptionMappingService().map(e));
signal.countDown();
}
}, new HostPreferences(session.getHost()).getLong("dropbox.delete.poll.interval.ms"), TimeUnit.MILLISECONDS);
Uninterruptibles.awaitUninterruptibly(signal);
if(null != failure.get()) {
throw failure.get();
}
}
catch(DbxException e) {
throw new DropboxExceptionMappingService().map(e);
}
finally {
scheduler.shutdown();
}
}
@Override
public boolean isRecursive() {
return true;
}
}
| iterate-ch/cyberduck | dropbox/src/main/java/ch/cyberduck/core/dropbox/DropboxBatchDeleteFeature.java | Java | gpl-3.0 | 4,514 |
/*
* 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 com.bc.ceres.swing.figure.support;
import com.bc.ceres.swing.figure.FigureStyle;
import org.junit.Test;
import java.awt.BasicStroke;
import java.awt.Color;
import static org.junit.Assert.*;
public class DefaultFigureStyleTest {
@Test
public void testDefaultConstructor() {
// This is the SVG/CSS default
FigureStyle style = new DefaultFigureStyle();
assertEquals("", style.getName());
assertEquals(Color.BLACK, style.getFillColor());
assertEquals(null, style.getStrokeColor());
assertNotNull(style.getStroke());
assertNull(style.getSymbol());
}
@Test
public void testConstructorWithName() {
FigureStyle style = new DefaultFigureStyle("X");
assertEquals("X", style.getName());
assertEquals(Color.BLACK, style.getFillColor());
assertEquals(null, style.getStrokeColor());
assertNotNull(style.getStroke());
assertNull(style.getSymbol());
}
@Test
public void testImageSymbolFromName() {
DefaultFigureStyle style = new DefaultFigureStyle();
assertNull(style.getSymbol());
style.setSymbolName("pin");
assertNotNull(style.getSymbol());
}
@Test
public void testImageSymbolFromResource() {
DefaultFigureStyle style = new DefaultFigureStyle();
assertNull(style.getSymbol());
style.setSymbolImagePath("/com/bc/ceres/swing/figure/support/TestSymbolIcon.png");
assertNotNull(style.getSymbol());
}
@Test
public void testPolygonStyle() {
FigureStyle style = DefaultFigureStyle.createPolygonStyle(Color.RED);
assertEquals(Color.RED, style.getFillColor());
assertEquals(null, style.getStrokeColor());
assertEquals(0.0, style.getStrokeWidth(), 1E-10);
assertNotNull(style.getStroke());
style = DefaultFigureStyle.createPolygonStyle(Color.RED, Color.BLUE);
assertEquals(Color.RED, style.getFillColor());
assertEquals(Color.BLUE, style.getStrokeColor());
assertNotNull(style.getStroke());
}
@Test
public void testCss() {
testToPointCss("symbol-image:TestSymbolIcon.png; symbol-ref-x:2.0; symbol-ref-y:6.0",
DefaultFigureStyle.createPointStyle(ImageSymbol.createIcon("TestSymbolIcon.png", 2.0, 6.0)));
testToPointCss("stroke:#ffc800; stroke-width:2.5; symbol:star",
DefaultFigureStyle.createPointStyle(NamedSymbol.STAR, Color.ORANGE, new BasicStroke(2.5f)));
testToPointCss("fill:#00ff00; stroke:#ffc800; stroke-width:2.5; symbol:pin",
DefaultFigureStyle.createPointStyle(NamedSymbol.PIN, Color.GREEN, Color.ORANGE, new BasicStroke(2.5f)));
testToLineCss("stroke:#0000ff; stroke-width:5.0",
DefaultFigureStyle.createLineStyle(Color.BLUE, new BasicStroke(5.0f)));
testToLineCss("stroke:#0a0b0c; stroke-opacity:0.05; stroke-width:1.0",
DefaultFigureStyle.createLineStyle(new Color(10, 11, 12, 13), new BasicStroke(1.0f)));
testToPolygonCss("fill:#ff0000; stroke:#0000ff; stroke-width:5.0",
DefaultFigureStyle.createPolygonStyle(Color.RED, Color.BLUE, new BasicStroke(5.0f)));
testToPolygonCss("fill:#3f4a0d; stroke:#aabbff",
DefaultFigureStyle.createPolygonStyle(Color.decode("0x3f4a0d"),
Color.decode("0xaabbff")));
testToPolygonCss("fill:#0c1722; fill-opacity:0.5",
DefaultFigureStyle.createPolygonStyle(new Color(12, 23, 34, 128)));
testToPolygonCss("fill:#0c1722; fill-opacity:0.5; stroke:#646464; stroke-opacity:0.38",
DefaultFigureStyle.createPolygonStyle(new Color(12, 23, 34, 127), new Color(100, 100, 100, 98)));
}
private void testToPointCss(String expectedCss, FigureStyle style) {
String css = style.toCssString();
assertEquals(expectedCss, css);
testFromPointCss(style, css);
}
private void testFromPointCss(FigureStyle expectedStyle, String css) {
FigureStyle style = new DefaultFigureStyle();
style.fromCssString(css);
assertEquals(expectedStyle.getSymbolName(), style.getSymbolName());
assertEquals(expectedStyle.getSymbolImagePath(), style.getSymbolImagePath());
assertEquals(expectedStyle.getSymbolRefX(), style.getSymbolRefX(), 1E-10);
assertEquals(expectedStyle.getSymbolRefY(), style.getSymbolRefY(), 1E-10);
}
private void testToLineCss(String expectedCss, FigureStyle style) {
String css = style.toCssString();
assertEquals(expectedCss, css);
testFromLineCss(style, css);
}
private void testFromLineCss(FigureStyle expectedStyle, String css) {
FigureStyle style = new DefaultFigureStyle();
style.fromCssString(css);
assertEquals(expectedStyle.getStrokeOpacity(), style.getStrokeOpacity(), 1E-10);
assertEquals(expectedStyle.getStrokeWidth(), style.getStrokeWidth(), 1E-10);
assertEquals(expectedStyle.getStrokeColor(), style.getStrokeColor());
// FIXME - these sometimes fail due to lossy alpha conversion (nf)
// assertEquals(expectedStyle.getStrokePaint(), style.getStrokePaint());
}
private void testToPolygonCss(String expectedCss, FigureStyle style) {
String css = style.toCssString();
assertEquals(expectedCss, css);
testFromPolygonCss(style, css);
}
private void testFromPolygonCss(FigureStyle expectedStyle, String css) {
FigureStyle style = new DefaultFigureStyle();
style.fromCssString(css);
assertEquals(expectedStyle.getFillColor(), style.getFillColor());
assertEquals(expectedStyle.getFillOpacity(), style.getFillOpacity(), 1E-10);
assertEquals(expectedStyle.getStrokeColor(), style.getStrokeColor());
assertEquals(expectedStyle.getStrokeOpacity(), style.getStrokeOpacity(), 1E-10);
assertEquals(expectedStyle.getStrokeWidth(), style.getStrokeWidth(), 1E-10);
// FIXME - these sometimes fail due to lossy alpha conversion (nf)
//assertEquals(expectedStyle.getFillPaint(), style.getFillPaint());
//assertEquals(expectedStyle.getStrokePaint(), style.getStrokePaint());
}
}
| lveci/nest | beam/ceres-0.x/ceres-ui/src/test/java/com/bc/ceres/swing/figure/support/DefaultFigureStyleTest.java | Java | gpl-3.0 | 7,103 |
package is.idega.idegaweb.campus.webservice.nortek;
import java.util.Date;
public interface NortekService {
public boolean isCardValid(String cardSerialNumber);
public boolean banCard(String cardSerialNumber);
public boolean addAmountToCard(String cardSerialNumber, Date timestamp, double amount, String terminal);
}
| idega/platform2 | src/is/idega/idegaweb/campus/webservice/nortek/NortekService.java | Java | gpl-3.0 | 326 |
/***************************************************************************
* GIntegral.cpp - Integration class *
* ----------------------------------------------------------------------- *
* copyright (C) 2010-2020 by Juergen Knoedlseder *
* ----------------------------------------------------------------------- *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
/**
* @file GIntegral.cpp
* @brief Integration class implementation
* @author Juergen Knoedlseder
*/
/* __ Includes ___________________________________________________________ */
#include <cmath> // std::abs()
#include <vector>
#include <algorithm> // std::sort
#include "GIntegral.hpp"
#include "GException.hpp"
#include "GTools.hpp"
#include "GFunction.hpp"
/* __ Method name definitions ____________________________________________ */
#define G_ROMBERG "GIntegral::romberg(double&, double&, int&)"
#define G_TRAPZD "GIntegral::trapzd(double&, double&, int&, double)"
#define G_POLINT "GIntegral::polint(double*, double*, int, double, double*)"
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
/* __ Debug definitions __________________________________________________ */
/* __ Constants __________________________________________________________ */
namespace gammalib {
// Gauss-Kronrod abscissae, common to the 10-, 21-, 43- and 87-point rule
const double gkx1[5] = {
0.973906528517171720077964012084452,
0.865063366688984510732096688423493,
0.679409568299024406234327365114874,
0.433395394129247190799265943165784,
0.148874338981631210884826001129720
};
// Gauss-Kronrod weights of the 10-point rule
const double gkw10[5] = {
0.066671344308688137593568809893332,
0.149451349150580593145776339657697,
0.219086362515982043995534934228163,
0.269266719309996355091226921569469,
0.295524224714752870173892994651338
};
// Gauss-Kronrod abscissae, common to the 21-, 43- and 87-point rule
const double gkx2[5] = {
0.995657163025808080735527280689003,
0.930157491355708226001207180059508,
0.780817726586416897063717578345042,
0.562757134668604683339000099272694,
0.294392862701460198131126603103866
};
// Gauss-Kronrod weights of the 21-point rule for abscissae gkx1
const double gkw21a[5] = {
0.032558162307964727478818972459390,
0.075039674810919952767043140916190,
0.109387158802297641899210590325805,
0.134709217311473325928054001771707,
0.147739104901338491374841515972068
};
// Gauss-Kronrod weights of the 21-point rule for abscissae gkx2
const double gkw21b[6] = {
0.011694638867371874278064396062192,
0.054755896574351996031381300244580,
0.093125454583697605535065465083366,
0.123491976262065851077958109831074,
0.142775938577060080797094273138717,
0.149445554002916905664936468389821
};
// Gauss-Kronrod abscissae, common to the 43- and 87-point rule
const double gkx3[11] = {
0.999333360901932081394099323919911,
0.987433402908088869795961478381209,
0.954807934814266299257919200290473,
0.900148695748328293625099494069092,
0.825198314983114150847066732588520,
0.732148388989304982612354848755461,
0.622847970537725238641159120344323,
0.499479574071056499952214885499755,
0.364901661346580768043989548502644,
0.222254919776601296498260928066212,
0.074650617461383322043914435796506
};
// Gauss-Kronrod weights of the 43-point rule for abscissae gkx1, gkx3
const double gkw43a[10] = {
0.016296734289666564924281974617663,
0.037522876120869501461613795898115,
0.054694902058255442147212685465005,
0.067355414609478086075553166302174,
0.073870199632393953432140695251367,
0.005768556059769796184184327908655,
0.027371890593248842081276069289151,
0.046560826910428830743339154433824,
0.061744995201442564496240336030883,
0.071387267268693397768559114425516
};
// Gauss-Kronrod weights of the 43-point formula for abscissae gkx3
const double gkw43b[12] = {
0.001844477640212414100389106552965,
0.010798689585891651740465406741293,
0.021895363867795428102523123075149,
0.032597463975345689443882222526137,
0.042163137935191811847627924327955,
0.050741939600184577780189020092084,
0.058379395542619248375475369330206,
0.064746404951445885544689259517511,
0.069566197912356484528633315038405,
0.072824441471833208150939535192842,
0.074507751014175118273571813842889,
0.074722147517403005594425168280423
};
// Gauss-Kronrod abscissae, of the 87-point rule
const double gkx4[22] = {
0.999902977262729234490529830591582,
0.997989895986678745427496322365960,
0.992175497860687222808523352251425,
0.981358163572712773571916941623894,
0.965057623858384619128284110607926,
0.943167613133670596816416634507426,
0.915806414685507209591826430720050,
0.883221657771316501372117548744163,
0.845710748462415666605902011504855,
0.803557658035230982788739474980964,
0.757005730685495558328942793432020,
0.706273209787321819824094274740840,
0.651589466501177922534422205016736,
0.593223374057961088875273770349144,
0.531493605970831932285268948562671,
0.466763623042022844871966781659270,
0.399424847859218804732101665817923,
0.329874877106188288265053371824597,
0.258503559202161551802280975429025,
0.185695396568346652015917141167606,
0.111842213179907468172398359241362,
0.037352123394619870814998165437704
};
// Gauss-Kronrod weights of the 87-point rule for abscissae gkx1, gkx2, gkx3
const double gkw87a[21] = {
0.008148377384149172900002878448190,
0.018761438201562822243935059003794,
0.027347451050052286161582829741283,
0.033677707311637930046581056957588,
0.036935099820427907614589586742499,
0.002884872430211530501334156248695,
0.013685946022712701888950035273128,
0.023280413502888311123409291030404,
0.030872497611713358675466394126442,
0.035693633639418770719351355457044,
0.000915283345202241360843392549948,
0.005399280219300471367738743391053,
0.010947679601118931134327826856808,
0.016298731696787335262665703223280,
0.021081568889203835112433060188190,
0.025370969769253827243467999831710,
0.029189697756475752501446154084920,
0.032373202467202789685788194889595,
0.034783098950365142750781997949596,
0.036412220731351787562801163687577,
0.037253875503047708539592001191226
};
// Gauss-Kronrod weights of the 87-point formula for abscissae gkx4
const double gkw87b[23] = {
0.000274145563762072350016527092881,
0.001807124155057942948341311753254,
0.004096869282759164864458070683480,
0.006758290051847378699816577897424,
0.009549957672201646536053581325377,
0.012329447652244853694626639963780,
0.015010447346388952376697286041943,
0.017548967986243191099665352925900,
0.019938037786440888202278192730714,
0.022194935961012286796332102959499,
0.024339147126000805470360647041454,
0.026374505414839207241503786552615,
0.028286910788771200659968002987960,
0.030052581128092695322521110347341,
0.031646751371439929404586051078883,
0.033050413419978503290785944862689,
0.034255099704226061787082821046821,
0.035262412660156681033782717998428,
0.036076989622888701185500318003895,
0.036698604498456094498018047441094,
0.037120549269832576114119958413599,
0.037334228751935040321235449094698,
0.037361073762679023410321241766599
};
} // end gammalib namespace
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GIntegral::GIntegral(void)
{
// Initialise members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Function kernel constructor
*
* @param[in] kernel Pointer to function kernel.
*
* The function kernel constructor assigns the function kernel pointer in
* constructing the object.
***************************************************************************/
GIntegral::GIntegral(GFunction* kernel)
{
// Initialise members
init_members();
// Set function kernel
m_kernel = kernel;
// Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] integral Integral.
***************************************************************************/
GIntegral::GIntegral(const GIntegral& integral)
{
// Initialise members
init_members();
// Copy members
copy_members(integral);
// Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GIntegral::~GIntegral(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] integral Integral.
* @return Integral.
***************************************************************************/
GIntegral& GIntegral::operator=(const GIntegral& integral)
{
// Execute only if object is not identical
if (this != &integral) {
// Free members
free_members();
// Initialise integral
init_members();
// Copy members
copy_members(integral);
} // endif: object was not identical
// Return
return *this;
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear integral
***************************************************************************/
void GIntegral::clear(void)
{
// Free members
free_members();
// Initialise private members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Clone integral
*
* @return Pointer to deep copy of integral.
***************************************************************************/
GIntegral* GIntegral::clone(void) const
{
return new GIntegral(*this);
}
/***********************************************************************//**
* @brief Perform Romberg integration
*
* @param[in] bounds Integration boundaries.
* @param[in] order Integration order (default: 5)
*
* @exception GException::invalid_argument
* Integration order incompatible with number of iterations.
*
* Returns the integral of the integrand, computed over a number of
* intervals [a0,a1], [a1,a2], ... that are given as an unordered vector
* by the @p bounds argument.
*
* Integration is performed by Romberg's method of order 2*order, where
*
* order=1 is equivalent to the trapezoidal rule,
* order=2 is equivalent to Simpson's rule, and
* order=3 is equivalent to Boole's rule.
*
* The number of iterations is limited by m_max_iter. m_eps specifies the
* requested fractional accuracy. By default it is set to 1e-6.
***************************************************************************/
double GIntegral::romberg(std::vector<double> bounds, const int& order)
{
// Sort integration boundaries in ascending order
std::sort(bounds.begin(), bounds.end());
// Initialise integral
double value = 0.0;
// Initialise integration status information
int calls = 0;
// Add integral of all intervals
for (int i = 0; i < bounds.size()-1; ++i) {
value += romberg(bounds[i], bounds[i+1], order);
calls += m_calls;
}
// Set integration status information
m_calls = calls;
// Return value
return value;
}
/***********************************************************************//**
* @brief Perform Romberg integration
*
* @param[in] a Left integration boundary.
* @param[in] b Right integration boundary.
* @param[in] order Integration order (default: 5)
*
* @exception GException::invalid_argument
* Integration order incompatible with number of iterations.
*
* Returns the integral of the integrand from a to b. Integration is
* performed by Romberg's method of order 2*order, where
*
* order=1 is equivalent to the trapezoidal rule,
* order=2 is equivalent to Simpson's rule, and
* order=3 is equivalent to Boole's rule.
*
* The number of iterations is limited by m_max_iter. m_eps specifies the
* requested fractional accuracy. By default it is set to 1e-6.
***************************************************************************/
double GIntegral::romberg(const double& a, const double& b, const int& order)
{
// Initialise result and status
double result = 0.0;
// Initialise integration status information
m_isvalid = true;
m_calls = 0;
m_has_abserr = false;
m_has_relerr = false;
// Continue only if integration range is valid
if (b > a) {
// Initialise variables
bool converged = false;
double dss = 0.0;
// Determine (maximum) number of iterations
int max_iter = (m_fix_iter > 0) ? m_fix_iter : m_max_iter;
// Check whether maximum number of iterations is compliant with
// order
if (order > max_iter) {
std::string msg = "Requested integration order "+
gammalib::str(order)+" is larger than the "
"maximum number of iterations "+
gammalib::str(max_iter)+". Either reduce the "
"integration order or increase the (maximum) "
"number of iterations.";
throw GException::invalid_argument(G_ROMBERG, msg);
}
// Allocate temporal storage
double* s = new double[max_iter+2];
double* h = new double[max_iter+2];
// Initialise step size
h[1] = 1.0;
s[0] = 0.0;
// Iterative loop
for (m_iter = 1; m_iter <= max_iter; ++m_iter) {
// Integration using Trapezoid rule
s[m_iter] = trapzd(a, b, m_iter, s[m_iter-1]);
// Compile option: Check for NaN/Inf
#if defined(G_NAN_CHECK)
if (is_notanumber(s[m_iter]) || is_infinite(s[m_iter])) {
m_message = "*** ERROR: GIntegral::romberg"
"(a="+gammalib::str(a)+", b="+gammalib::str(b)+""
", k="+gammalib::str(k)+"): NaN/Inf encountered"
" (s["+gammalib::str(m_iter)+"]="
""+gammalib::str(s[m_iter])+")";
std::cout << m_message << std::endl;
m_isvalid = false;
}
#endif
// Starting from iteration order on, use polynomial interpolation
if (m_iter >= order) {
// Compute result using polynom interpolation
result = polint(&h[m_iter-order], &s[m_iter-order],
order, 0.0, &dss);
// If a fixed number of iterations has been requested then
// check whether we reached the final one; otherwise check
// whether we reached the requested precision.
if (m_fix_iter > 0) {
if (m_iter == max_iter) {
converged = true;
}
}
else if (std::abs(dss) <= m_eps * std::abs(result)) {
converged = true;
}
if (converged) {
m_has_abserr = true;
m_abserr = std::abs(dss);
if (std::abs(result) > 0) {
m_has_relerr = true;
m_relerr = m_abserr / std::abs(result);
}
break;
}
} // endif: polynomial interpolation performed
// Reduce step size
h[m_iter+1]= 0.25 * h[m_iter];
} // endfor: iterative loop
// Free temporal storage
delete [] s;
delete [] h;
// Set status and optionally dump warning
if (!converged) {
m_isvalid = false;
m_message = "Integration uncertainty "+
gammalib::str(std::abs(dss))+
" exceeds absolute tolerance of "+
gammalib::str(m_eps * std::abs(result))+
" after "+gammalib::str(m_iter)+
" iterations. Result "+
gammalib::str(result)+
" is inaccurate.";
if (!m_silent) {
std::string origin = "GIntegral::romberg("+
gammalib::str(a)+", "+
gammalib::str(b)+", "+
gammalib::str(order)+")";
gammalib::warning(origin, m_message);
}
}
} // endif: integration range was valid
// Return result
return result;
}
/***********************************************************************//**
* @brief Perform Trapezoidal integration
*
* @param[in] a Left integration boundary.
* @param[in] b Right integration boundary.
* @param[in] n Number of steps.
* @param[in] result Result from a previous trapezoidal integration step.
* @return Integration results.
*
* @exception GException::invalid_value
* Function kernel not set.
*
* The method performs a trapezoidal integration of the function kernel for
* the integration interval [a,b].
*
* If @p n = 1 the integral is computed using
*
* \f[
* \int_a^b f(x) \, dx = \frac{1}{2} (b-a) (f(a) + f(b))
* \f]
*
* For @p n > 1 the integral is computed using
*
* \f[
* \int_a^b f(x) \, dx = \frac{1}{2} \left[{\tt result} +
* \frac{b-a}{2^{n-1}}
* \sum_{i=0}^{2^{n-1}-1} f \left( a + (0.5+i) \frac{b-a}{2^{n-1}} \right) \right]
*
* \f]
*
* where \f${\tt result}\f$ is the integration result from a previous call
* to the method with @p n = @p n - 1.
***************************************************************************/
double GIntegral::trapzd(const double& a, const double& b, const int& n,
double result)
{
// Throw an exception if the instance has no kernel
if (m_kernel == NULL) {
std::string msg = "Function kernel not set. Please set a function "
"kernel before calling the method.";
throw GException::invalid_value(G_TRAPZD, msg);
}
// Handle case of identical boundaries
if (a == b) {
result = 0.0;
}
// ... otherwise use trapeziodal rule
else {
// Case A: Only a single step is requested
if (n == 1) {
// Evaluate integrand at boundaries
double y_a = m_kernel->eval(a);
double y_b = m_kernel->eval(b);
m_calls += 2;
// Compute result
result = 0.5*(b-a)*(y_a + y_b);
} // endif: only a single step was requested
// Case B: More than a single step is requested
else {
// Compute step level 2^(n-1)
int it = 1;
for (int j = 1; j < n-1; ++j) {
it <<= 1;
}
// Verify that step level is valid
if (it == 0) {
m_isvalid = false;
m_message = "Invalid step level "+gammalib::str(it)+
" encountered for"
" a="+gammalib::str(a)+
", b="+gammalib::str(b)+
", n="+gammalib::str(n)+
", result="+gammalib::str(result)+
". Looks like n is too large.";
if (!m_silent) {
gammalib::warning(G_TRAPZD, m_message);
}
}
// Set step size
double tnm = double(it);
double del = (b-a)/tnm;
// Verify that step is >0
if (del == 0) {
m_isvalid = false;
m_message = "Invalid step size "+gammalib::str(del)+
" encountered for"
" a="+gammalib::str(a)+
", b="+gammalib::str(b)+
", n="+gammalib::str(n)+
", result="+gammalib::str(result)+
". Step is too small to make sense.";
if (!m_silent) {
gammalib::warning(G_TRAPZD, m_message);
}
}
// Sum up values
double x = a + 0.5*del;
double sum = 0.0;
for (int j = 0; j < it; ++j, x+=del) {
// Evaluate integrand
double y = m_kernel->eval(x);
m_calls++;
// Add integrand
sum += y;
} // endfor: looped over steps
// Set result
result = 0.5*(result + (b-a)*sum/tnm);
}
} // endelse: trapeziodal rule was applied
// Return result
return result;
}
/***********************************************************************//**
* @brief Adaptive Simpson's integration
*
* @param[in] a Left integration boundary.
* @param[in] b Right integration boundary.
*
* Integrates the function using an adaptive Simpson's rule. The initial
* interval [a,b] is split into two sub-intervals [a,c] and [c,b] for which
* the integral is computed using
*
* \f[
* \frac{b-a}{6} f(a) + 4f(c) + f(b)
* \f]
*
* where \f$c=(a+b)/2\f$ is the mid-point of interval [a,b]. Each
* sub-interval is then recursively divided into sub-interval and the process
* is repeated. Dividing of sub-intervals is stopped when the difference
* between subsequent intervals falls below the relative tolerance specified
* by eps(). The maximum recursion depth is set by the max_iter() method.
*
* I almost do not dare to confess, but the code has been taken from
* http://en.wikipedia.org/wiki/Adaptive_Simpson%27s_method
* It's really pretty simple ...
***************************************************************************/
double GIntegral::adaptive_simpson(const double& a, const double& b) const
{
// Initialise integration status information
m_isvalid = true;
m_calls = 0;
m_iter = m_max_iter;
m_has_abserr = false;
m_has_relerr = false;
// Compute mid-point c
double c = 0.5*(a + b); //!< Mid-point of interval [a,b]
double h = b - a; //!< Length of interval [a,b]
// Evaluate function at boundaries and mid-point c
double fa = m_kernel->eval(a);
double fb = m_kernel->eval(b);
double fc = m_kernel->eval(c);
m_calls += 3;
// Compute integral using Simpson's rule
double S = (h/6.0) * (fa + 4.0*fc + fb);
// Initialise absolute precision
double epsilon = (std::abs(S) > 0) ? m_eps * S : m_eps;
// Call recursive auxiliary function
double value = adaptive_simpson_aux(a, b, epsilon, S, fa, fb, fc, m_max_iter);
// Deduce the number of iterations from the iteration counter
m_iter = m_max_iter - m_iter;
// If result is not valid, set and output status message
if (!m_isvalid) {
m_message = "Integration uncertainty exceeds relative tolerance "
"of "+gammalib::str(m_eps)+" and absolute tolerance of "
""+gammalib::str(epsilon)+" after "+gammalib::str(m_iter)+
" iterations and "+gammalib::str(m_calls)+" function "
"calls. Result "+gammalib::str(value)+" inaccurate.";
if (!m_silent) {
std::string origin = "GIntegral::adaptive_simpson("+
gammalib::str(a)+", "+
gammalib::str(b)+")";
gammalib::warning(origin, m_message);
}
}
// Return result
return value;
}
/***********************************************************************//**
* @brief Gauss-Kronrod integration
*
* @param[in] a Left integration boundary.
* @param[in] b Right integration boundary.
*
***************************************************************************/
double GIntegral::gauss_kronrod(const double& a, const double& b) const
{
// Initialise integration status information
m_isvalid = true;
m_iter = 0;
m_calls = 0;
m_has_abserr = false;
m_has_relerr = false;
// Initialise integration result
double result = 0.0;
// Allocate some arrays
double fv1[5];
double fv2[5];
double fv3[5];
double fv4[5];
double savfun[21];
// Main code loop (so that we can exit using break)
do {
// Tolerance check
if (m_eps < 1.12e-14) {
m_isvalid = false;
m_message = "Requested relative tolerance of "+gammalib::str(m_eps)+
" cannot be acheived. Please relax the integration "
"precision.";
if (!m_silent) {
std::string origin = "GIntegral::gauss_kronrod("+
gammalib::str(a)+", "+
gammalib::str(b)+")";
gammalib::warning(origin, m_message);
}
}
// Compute function at mid-point
double h = 0.5 * (b - a);
double abs_h = std::abs(h);
double c = 0.5 * (b + a);
double f_c = m_kernel->eval(c);
m_calls++;
// Compute the integral using the 10- and 21-point formulae
m_iter++;
double res10 = 0;
double res21 = gammalib::gkw21b[5] * f_c;
double resabs = gammalib::gkw21b[5] * std::abs(f_c);
for (int k = 0; k < 5; ++k) {
double x = h * gammalib::gkx1[k];
double fval1 = m_kernel->eval(c+x);
double fval2 = m_kernel->eval(c-x);
double fval = fval1 + fval2;
m_calls += 2;
res10 += gammalib::gkw10[k] * fval;
res21 += gammalib::gkw21a[k] * fval;
resabs += gammalib::gkw21a[k] * (std::abs(fval1) + std::abs(fval2));
savfun[k] = fval;
fv1[k] = fval1;
fv2[k] = fval2;
}
for (int k = 0; k < 5; ++k) {
double x = h * gammalib::gkx2[k];
double fval1 = m_kernel->eval(c+x);
double fval2 = m_kernel->eval(c-x);
double fval = fval1 + fval2;
m_calls += 2;
res21 += gammalib::gkw21b[k] * fval;
resabs += gammalib::gkw21b[k] * (std::abs(fval1) + std::abs(fval2));
savfun[k+5] = fval;
fv3[k] = fval1;
fv4[k] = fval2;
}
resabs *= abs_h;
double mean = 0.5 * res21;
double resasc = gammalib::gkw21b[5] * std::abs(f_c - mean);
for (int k = 0; k < 5; ++k) {
resasc += (gammalib::gkw21a[k] *
(std::abs(fv1[k] - mean) + std::abs(fv2[k] - mean)) +
gammalib::gkw21b[k] *
(std::abs(fv3[k] - mean) + std::abs(fv4[k] - mean)));
}
resasc *= abs_h ;
result = res21 * h;
double error = rescale_error((res21 - res10) * h, resabs, resasc);
// Test for convergence */
if (error < m_eps * std::abs(result)) {
m_has_abserr = true;
m_abserr = error;
if (std::abs(result) > 0) {
m_has_relerr = true;
m_relerr = error / std::abs(result);
}
break;
}
// Compute the integral using the 43-point formula
m_iter++;
double res43 = gammalib::gkw43b[11] * f_c;
for (int k = 0; k < 10; ++k) {
res43 += savfun[k] * gammalib::gkw43a[k];
}
for (int k = 0; k < 11; ++k) {
double x = h * gammalib::gkx3[k];
double fval = (m_kernel->eval(c+x) +
m_kernel->eval(c-x));
m_calls += 2;
res43 += fval * gammalib::gkw43b[k];
savfun[k+10] = fval;
}
result = res43 * h;
// Test for convergence */
error = rescale_error((res43 - res21) * h, resabs, resasc);
if (error < m_eps * std::abs(result)) {
m_has_abserr = true;
m_abserr = error;
if (std::abs(result) > 0) {
m_has_relerr = true;
m_relerr = error / std::abs(result);
}
break;
}
// Compute the integral using the 87-point formula
m_iter++;
double res87 = gammalib::gkw87b[22] * f_c;
for (int k = 0; k < 21; ++k) {
res87 += savfun[k] * gammalib::gkw87a[k];
}
for (int k = 0; k < 22; ++k) {
double x = h * gammalib::gkx4[k];
res87 += gammalib::gkw87b[k] *
(m_kernel->eval(c+x) +
m_kernel->eval(c-x));
m_calls += 2;
}
result = res87 * h ;
// Test for convergence */
error = rescale_error ((res87 - res43) * h, resabs, resasc);
if (error < m_eps * std::abs(result)) {
m_has_abserr = true;
m_abserr = error;
if (std::abs(result) > 0) {
m_has_relerr = true;
m_relerr = error / std::abs(result);
}
break;
}
// Failed to converge
m_isvalid = false;
m_message = "Integration uncertainty "+gammalib::str(error)+" exceeds "
"absolute tolerance of "+
gammalib::str(m_eps * std::abs(result))+" after "+
gammalib::str(m_iter)+" iterations and "+
gammalib::str(m_calls)+" function calls. Result "+
gammalib::str(result)+" inaccurate.";
if (!m_silent) {
std::string origin = "GIntegral::gauss_kronrod("+
gammalib::str(a)+", "+
gammalib::str(b)+")";
gammalib::warning(origin, m_message);
}
} while (false); // end of main loop
// Return result
return result;
}
/***********************************************************************//**
* @brief Print integral information
*
* @param[in] chatter Chattiness.
* @return String containing integral information.
***************************************************************************/
std::string GIntegral::print(const GChatter& chatter) const
{
// Initialise result string
std::string result;
// Continue only if chatter is not silent
if (chatter != SILENT) {
// Append header
result.append("=== GIntegral ===");
// Append information
result.append("\n"+gammalib::parformat("Relative precision"));
result.append(gammalib::str(eps()));
if (m_has_abserr) {
result.append("\n"+gammalib::parformat("Absolute error"));
result.append(gammalib::str(m_abserr));
}
if (m_has_relerr) {
result.append("\n"+gammalib::parformat("Relative error"));
result.append(gammalib::str(m_relerr));
}
result.append("\n"+gammalib::parformat("Function calls"));
result.append(gammalib::str(calls()));
result.append("\n"+gammalib::parformat("Iterations"));
result.append(gammalib::str(iter()));
if (m_fix_iter > 0) {
result.append(" (fixed: ");
result.append(gammalib::str(fixed_iter()));
result.append(")");
}
else {
result.append(" (maximum: ");
result.append(gammalib::str(max_iter()));
result.append(")");
}
// Append status information
result.append("\n"+gammalib::parformat("Status"));
if (is_valid()) {
result.append("Result accurate.");
}
else {
result.append(message());
}
if (silent()) {
result.append("\n"+gammalib::parformat("Warnings")+"suppressed");
}
else {
result.append("\n"+gammalib::parformat("Warnings"));
result.append("in standard output");
}
} // endif: chatter was not silent
// Return result
return result;
}
/*==========================================================================
= =
= Protected methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
***************************************************************************/
void GIntegral::init_members(void)
{
// Initialise members
m_kernel = NULL;
m_eps = 1.0e-6;
m_max_iter = 20;
m_fix_iter = 0;
m_message.clear();
m_silent = false;
// Initialise results
m_iter = 0;
m_calls = 0;
m_isvalid = true;
m_has_abserr = false;
m_has_relerr = false;
m_abserr = 0.0;
m_relerr = 0.0;
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] integral Integral.
***************************************************************************/
void GIntegral::copy_members(const GIntegral& integral)
{
// Copy attributes
m_kernel = integral.m_kernel;
m_eps = integral.m_eps;
m_max_iter = integral.m_max_iter;
m_fix_iter = integral.m_fix_iter;
m_message = integral.m_message;
m_silent = integral.m_silent;
// Copy results
m_iter = integral.m_iter;
m_calls = integral.m_calls;
m_isvalid = integral.m_isvalid;
m_has_abserr = integral.m_has_abserr;
m_has_relerr = integral.m_has_relerr;
m_abserr = integral.m_abserr;
m_relerr = integral.m_relerr;
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
***************************************************************************/
void GIntegral::free_members(void)
{
// Return
return;
}
/***********************************************************************//**
* @brief Perform Polynomial interpolation
*
* @param[in] xa Pointer to array of X values.
* @param[in] ya Pointer to array of Y values.
* @param[in] n Number of elements in arrays.
* @param[in] x X value at which interpolations should be performed.
* @param[out] dy Error estimate for interpolated values.
*
* Given arrays xa[1,..,n] and ya[1,..,n], and given a value x, this
* method returns a value y, and an error estimate dy. If P(x) is the
* polynomial of degree n-1, then the returned value y=P(x).
*
* @todo Implement exceptions instead of screen dump.
* @todo Use std::vector for xa and ya and start at 0
***************************************************************************/
double GIntegral::polint(double* xa, double* ya, int n, double x, double* dy)
{
// Initialise result
double y = 0.0;
// Allocate temporary memory
std::vector<double> c(n, 0.0);
std::vector<double> d(n, 0.0);
// Compute initial distance to first node
double dif = std::abs(x-xa[1]);
// Find index ns of the closest table entry
int ns = 0;
for (int i = 0; i < n; ++i) {
double dift = std::abs(x-xa[i+1]);
if (dift < dif) {
ns = i;
dif = dift;
}
c[i] = ya[i+1];
d[i] = ya[i+1];
}
// Get initial approximation to y
y = ya[ns+1];
ns--;
// Loop over each column of the tableau
for (int m = 1; m < n; ++m) {
// Update current c's and d's
for (int i = 0; i < n-m; ++i) {
double ho = xa[i+1] - x;
double hp = xa[i+m+1] - x;
double w = c[i+1] - d[i];
double den = ho - hp;
if (den == 0.0) {
m_isvalid = false;
m_message = "Invalid step size "+gammalib::str(den)+
" encountered. Two values in xa array are"
" identical.";
if (!m_silent) {
gammalib::warning(G_POLINT, m_message);
}
}
den = w/den;
d[i] = hp*den;
c[i] = ho*den;
}
// Compute y correction
*dy = (2*(ns+1) < (n-m)) ? c[ns+1] : d[ns--];
// Update y
y += *dy;
} // endfor: looped over columns of tableau
// Return
return y;
}
/***********************************************************************//**
* @brief Auxiliary function for adaptive Simpson's method
*
* @param[in] a Left integration boundary.
* @param[in] b Right integration boundary.
* @param[in] eps Precision.
* @param[in] S Integral of last computation.
* @param[in] fa Function value at left integration boundary.
* @param[in] fb Function value at right integration boundary.
* @param[in] fc Function value at mid-point of interval [a,b]
* @param[in] bottom Iteration counter (stop when 0)
*
* Implements a recursive auxiliary method for the adative_simpson()
* integrator.
***************************************************************************/
double GIntegral::adaptive_simpson_aux(const double& a, const double& b,
const double& eps, const double& S,
const double& fa, const double& fb,
const double& fc,
const int& bottom) const
{
// Store the iteration counter
if (bottom < m_iter) {
m_iter = bottom;
}
// Compute mid-point c bet
double c = 0.5*(a + b); //!< Mid-point of interval [a,b]
double h = b - a; //!< Length of interval [a,b]
double d = 0.5*(a + c); //!< Mid-point of interval [a,c]
double e = 0.5*(c + b); //!< Mid-point of interval [c,b]
// Evaluate function at mid-points d and e
double fd = m_kernel->eval(d);
double fe = m_kernel->eval(e);
m_calls += 2;
// Compute integral using Simpson's rule for the left and right interval
double h12 = h / 12.0;
double Sleft = h12 * (fa + 4.0*fd + fc);
double Sright = h12 * (fc + 4.0*fe + fb);
double S2 = Sleft + Sright;
// Allocate result
double value;
// If converged then compute the result ...
if (std::abs(S2 - S) <= 15.0 * eps) {
// if (std::abs(S2 - S) <= 15.0 * m_eps * std::abs(S2)) {
value = S2 + (S2 - S)/15.0;
}
// ... else if the maximum recursion depth was reached then compute the
// result and signal result invalidity
else if (bottom <= 0) {
value = S2 + (S2 - S)/15.0;
m_isvalid = false;
}
// ... otherwise call this method recursively
else {
value = adaptive_simpson_aux(a, c, 0.5*eps, Sleft, fa, fc, fd, bottom-1) +
adaptive_simpson_aux(c, b, 0.5*eps, Sright, fc, fb, fe, bottom-1);
}
// Return result
return value;
}
/***********************************************************************//**
* @brief Rescale errors for Gauss-Kronrod integration
*
* @param[in] err Error estimate.
* @param[in] result_abs ???.
* @param[in] result_asc ???.
* @return Rescaled error estimate.
***************************************************************************/
double GIntegral::rescale_error(double err,
const double& result_abs,
const double& result_asc) const
{
// Take absolute value of error
err = std::abs(err);
// ...
if (result_asc != 0.0 && err != 0.0) {
double scale = std::pow((200.0 * err / result_asc), 1.5);
if (scale < 1.0) {
err = result_asc * scale ;
}
else {
err = result_asc ;
}
}
if (result_abs > 2.2250738585072014e-308 / (50.0 * 2.2204460492503131e-16)) {
double min_err = 50.0 * 2.2204460492503131e-16 * result_abs;
if (min_err > err) {
err = min_err ;
}
}
// Return error
return err;
}
| gammalib/gammalib | src/numerics/GIntegral.cpp | C++ | gpl-3.0 | 44,144 |
/**
* team-popup-links.js
* Foxtrick show Team Popup
* @author bummerland, convinced, ryanli
*/
'use strict';
Foxtrick.modules['TeamPopupLinks'] = {
MODULE_CATEGORY: Foxtrick.moduleCategories.SHORTCUTS_AND_TWEAKS,
OUTSIDE_MAINBODY: true,
PAGES: ['all'],
NICE: 10, // after anythings that works on team/manager links
// but before staff-marker
CSS: Foxtrick.InternalPath + 'resources/css/popup-links.css',
OPTIONS: ['TeamHighlight', 'TeamLinks', 'UserLinks', 'CustomLink'],
OPTION_TEXTS: true,
OPTION_TEXTS_DISABLED_LIST: [true, true, true, false],
LINKS: {
Team: {
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_team=true',
},
Manager: {
linkByTeam: '/Club/Manager/?teamId=[teamid]',
},
Matches: {
ownLink: '/Club/Matches/',
linkByTeam: '/Club/Matches/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_matches=true',
},
Players: {
ownLink: '/Club/Players/',
linkByTeam: '/Club/Players/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_players=true',
},
Series: {
linkByTeam: '/Club/Manager/?teamId=[teamid]&redir_to_series=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_series=true',
},
last_5_ips: {
linkByTeam: '/Club/Manager/?teamId=[teamid]&ShowOldConnections=true',
linkByUser: '/Club/Manager/?userId=[userid]&ShowOldConnections=true',
},
Guestbook: {
linkByTeam: '/Club/Manager/Guestbook.aspx?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_guestbook=true',
},
SendMessage: {
linkByTeam: '/Club/?teamId=[teamid]&redir_to_mail=true',
linkByUser: '/MyHattrick/Inbox/?actionType=newMail&userId=[userid]',
},
Challenge: {
linkByTeam: '/Club/?teamId=[teamid]&make_challenge',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_challenge=true',
},
Achievements: {
linkByTeam: '/Club/Manager/?teamId=[teamid]&redir_to_achievements=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_achievements=true',
},
Coach: {
ownLink: '/Club/Training/?redir_to_coach=true',
linkByTeam: '/Club/Players/?teamId=[teamid]&redir_to_coach=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_coach=true',
},
TeamAnalysis: {
ownLink: '/Club/TacticsRoom/',
linkByTeam: '/Club/TacticsRoom/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_analysis=true',
},
TransferHistory: {
linkByTeam: '/Club/Transfers/transfersTeam.aspx?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_transferhistory=true',
},
TeamHistory: {
linkByTeam: '/Club/History/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_teamhistory=true',
},
FlagCollection: {
linkByTeam: '/Club/Flags/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_flags=true',
},
LastLineup: {
linkByTeam: '/Club/Matches/MatchLineup.aspx?teamId=[teamid]' +
'&useArchive=True&redir_to_newlineup=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_lastlineup=true',
},
NextMatch: {
linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_nextmatch=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_nextmatch=true',
},
AddNextMatch: {
linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_addnextmatch=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_addnextmatch=true',
},
YouthMatches: {
linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_youthmatches=true',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_youthmatches=true',
},
Tournaments: {
linkByTeam: '/Community/Tournaments/?teamId=[teamid]',
linkByUser: '/Club/Manager/?userId=[userid]&redir_to_tournaments=true',
},
},
OPTION_FUNC: function(doc) {
var table = doc.createElement('table');
table.className = 'bordered center';
var caption = doc.createElement('caption');
caption.setAttribute('data-text', 'TeamPopupLinks.prefsCaption');
table.appendChild(caption);
var headerRow = doc.createElement('tr');
table.appendChild(headerRow);
var placeHolder = doc.createElement('th');
headerRow.appendChild(placeHolder);
var enableDefault = doc.createElement('th');
enableDefault.setAttribute('data-text', 'TeamPopupLinks.ShowByDefault');
headerRow.appendChild(enableDefault);
var enableMore = doc.createElement('th');
enableMore.setAttribute('data-text', 'TeamPopupLinks.ShowOnMore');
headerRow.appendChild(enableMore);
var enableNewTab = doc.createElement('th');
enableNewTab.setAttribute('data-text', 'TeamPopupLinks.OpenNewTab');
headerRow.appendChild(enableNewTab);
var i;
for (i in this.LINKS) {
var row = doc.createElement('tr');
table.appendChild(row);
var title = doc.createElement('th');
title.textContent = Foxtrick.Prefs.getModuleElementDescription('TeamPopupLinks', i);
row.appendChild(title);
var defaultCell = doc.createElement('td');
row.appendChild(defaultCell);
var defaultCheck = doc.createElement('input');
defaultCheck.type = 'checkbox';
defaultCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.default');
defaultCell.appendChild(defaultCheck);
var moreCell = doc.createElement('td');
row.appendChild(moreCell);
var moreCheck = doc.createElement('input');
moreCheck.type = 'checkbox';
moreCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.more');
moreCell.appendChild(moreCheck);
var newTab = doc.createElement('td');
row.appendChild(newTab);
var newTabCheck = doc.createElement('input');
newTabCheck.type = 'checkbox';
newTabCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.newTab');
newTab.appendChild(newTabCheck);
}
return table;
},
run: function(doc) {
const module = this;
// show last 5 logins
if (/ShowOldConnections=true/i.test(doc.URL)) {
let a = Foxtrick.getMBElement(doc, 'lnkShowLogins');
a && a.click();
}
module.addPopupLinks(doc);
},
/* eslint-disable complexity */
addPopupLinks: function(doc) {
const module = this;
const MODULE_NAME = module.MODULE_NAME;
const TEAM_RE = /Club\/(Default\.aspx)?\?TeamID=/i;
const MANAGER_RE = /Club\/Manager\/(Default\.aspx)?\?UserID=/i;
const FORUM_RE = /Forum\/(Default\.aspx)?\?/i;
const TEAM_ID_TAG = /\[teamid\]/i;
const USER_ID_TAG = /\[userid\]/i;
const USER_NAME_TAG = /\[username\]/i;
const REDIR_RE = /redir_to/i;
var teamEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'TeamLinks');
var userEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'UserLinks');
var highlightEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'TeamHighlight');
var customEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'CustomLink');
var mainBody = doc.getElementById('mainBody');
var sUrl = doc.URL;
var ownTeamId = Foxtrick.util.id.getOwnTeamId();
var curTeamId = Foxtrick.Pages.All.getTeamId(doc);
var hasScroll = Foxtrick.util.layout.mainBodyHasScroll(doc);
var links = this.LINKS;
var addSpan = function(aLink) {
if (Foxtrick.hasClass(aLink, 'ft-tpl') ||
Foxtrick.hasClass(aLink, 'ft-popup-list-link'))
return;
var url = aLink.href;
var parent = aLink.parentNode;
var grandParent = parent.parentNode;
if (TEAM_RE.test(url) && !REDIR_RE.test(url) && teamEnabled ||
MANAGER_RE.test(url) && userEnabled) {
var span = Foxtrick.createFeaturedElement(doc, module, 'span');
span.className = 'ft-popup-span';
if (highlightEnabled && TEAM_RE.test(url) &&
curTeamId == parseInt(Foxtrick.getUrlParam(url, 'TeamID'), 10)) {
if (parent.nodeName == 'TD')
Foxtrick.addClass(grandParent, 'ftTeamHighlight');
else if (grandParent.nodeName == 'TD')
Foxtrick.addClass(grandParent.parentNode, 'ftTeamHighlight');
}
const pages = ['forumViewThread', 'forumWritePost', 'forumModWritePost', 'region'];
if (!Foxtrick.isPage(doc, pages) &&
(Foxtrick.util.layout.isStandard(doc) || parent.nodeName != 'TD')) {
// Foxtrick.addClass(aLink, 'ft-nowrap');
Foxtrick.addClass(aLink, 'ft-tpl');
}
else {
Foxtrick.addClass(aLink, 'ft-tpl');
}
parent.insertBefore(span, aLink);
// to show a pop-up!
var showPopup = function(ev) {
var findLink = function(node) {
if (node.nodeName == 'A' && !Foxtrick.hasClass(node, 'ft-no-popup'))
return node;
if (!node.parentNode)
return null;
return findLink(node.parentNode);
};
// need to find <a> recursively as <a> may have children
// like <bdo>
var orgLink = findLink(ev.target);
if (orgLink == null)
return; // no link found
var showMore = false;
if (orgLink.getAttribute('more')) {
if (orgLink.getAttribute('more') == 'true')
showMore = true;
orgLink = orgLink.parentNode.parentNode.previousSibling;
}
var teamId = Foxtrick.util.id.getTeamIdFromUrl(orgLink.href);
if (teamId) {
// eslint-disable-next-line no-unused-vars
let teamName = orgLink.textContent; // lgtm[js/unused-local-variable]
}
var userName;
var userId = Foxtrick.util.id.getUserIdFromUrl(orgLink.href);
if (userId) {
let linkName = orgLink.textContent.trim();
let titleName = orgLink.title.trim();
if (titleName.slice(0, linkName.length) === linkName) {
// link name seems to be shortened for long user names
// using titleName instead if it's a superstring
userName = titleName;
}
else {
userName = linkName;
}
}
var ownTopTeamLinks = orgLink.parentNode.parentNode.nodeName == 'DIV' &&
orgLink.parentNode.parentNode.id == 'teamLinks';
var list = Foxtrick.createFeaturedElement(doc, module, 'ul');
list.className = 'ft-popup-list';
var addItem = function(key, isOwnTeam, teamId, userId, userName, ownLink,
linkByTeam, linkByUser, linkByUserName) {
var item = doc.createElement('li');
var link = doc.createElement('a');
link.className = 'ft-popup-list-link';
var user = userName;
if (user && userId && userId == user.match(/\d+/))
user = '';
if (isOwnTeam && ownLink)
link.href = ownLink;
else if (teamId && linkByTeam)
link.href = linkByTeam.replace(TEAM_ID_TAG, teamId);
else if (user && linkByUserName)
link.href = linkByUserName.replace(USER_NAME_TAG, user);
else if (userId && linkByUser)
link.href = linkByUser.replace(USER_ID_TAG, userId);
else
return;
var openInNewTab = function(option) {
let key = `module.${MODULE_NAME}.${option}.newTab`;
return Foxtrick.Prefs.getBool(key);
};
if (openInNewTab(key))
link.target = '_blank';
link.textContent = Foxtrick.L10n.getString(key);
item.appendChild(link);
list.appendChild(item);
};
var isEnabledWithinContext = function(option, more) {
let key = `module.${MODULE_NAME}.${option}.${more ? 'more' : 'default'}`;
return Foxtrick.Prefs.getBool(key);
};
var showLessMore = false;
if (ownTopTeamLinks) {
// own team's link at the top of the page
for (let link of ['Matches', 'Players']) {
let def = links[link];
if (!def)
continue;
let ownLink = def.ownLink;
addItem(link, true, null, null, null, ownLink, null, null, null);
}
}
else {
for (let link in links) {
if (isEnabledWithinContext(link, showMore)) {
let def = links[link];
let own = teamId == ownTeamId;
addItem(link, own, teamId, userId, userName, def.ownLink,
def.linkByTeam, def.linkByUser, def.linkByUserName);
}
else if (isEnabledWithinContext(link, !showMore)) {
showLessMore = true;
}
}
if (customEnabled) {
let customLinkText =
Foxtrick.Prefs.getString(`module.${MODULE_NAME}.CustomLink_text`);
if (typeof customLinkText === 'string') {
let ownLinks = customLinkText.split(/\n/);
for (let ownLink of ownLinks.map(l => l.trim()).filter(Boolean)) {
try {
let redirToCustom = false;
let json = JSON.parse(ownLink);
if (showMore != json.more) {
showLessMore = true;
continue;
}
let item = doc.createElement('li');
let link = doc.createElement('a');
link.href = Foxtrick.util.sanitize.parseUrl(json.link);
link.title = json.title;
link.textContent = json.title;
if (TEAM_ID_TAG.test(link.href)) {
if (teamId)
link.href = link.href.replace(TEAM_ID_TAG, teamId);
else
redirToCustom = true;
}
if (USER_ID_TAG.test(link.href)) {
if (userId)
link.href = link.href.replace(USER_ID_TAG, userId);
else
redirToCustom = true;
}
if (redirToCustom) {
if (teamId == null) {
link.href = '/Club/Manager/?userId=' + userId +
'&redir_to_custom=true&redir_to=' + link.href;
}
else {
link.href = '/Club/Manager/?teamId=' + teamId +
'&redir_to_custom=true&redir_to=' + link.href;
}
}
if (json.newTab)
link.target = '_blank';
item.appendChild(link);
list.appendChild(item);
}
catch (e) {
Foxtrick.log('custom teampopup error:', e);
}
}
}
}
if (showLessMore) {
let item = doc.createElement('li');
let link = doc.createElement('a');
if (showMore) {
link.setAttribute('more', 'false');
link.textContent = Foxtrick.L10n.getString('less');
}
else {
link.setAttribute('more', 'true');
link.textContent = Foxtrick.L10n.getString('more');
}
Foxtrick.onClick(link, showPopup);
item.appendChild(link);
list.appendChild(item);
}
}
var down = false;
let pos = Foxtrick.getElementPosition(orgLink, mainBody);
var pT = pos.top;
if (hasScroll && pT - mainBody.scrollTop < mainBody.offsetHeight / 2 ||
pT - doc.body.scrollTop < 300 || !mainBody) { // = popdown
if (list.lastChild) {
let more = list.removeChild(list.lastChild);
list.insertBefore(more, list.firstChild);
}
down = true;
}
Foxtrick.addClass(list, 'ft-popup-list-' + (down ? 'down' : 'up'));
let parentTPL = orgLink.parentNode.querySelector('.ft-popup-list');
if (parentTPL)
parentTPL.remove();
Foxtrick.insertAfter(list, orgLink);
};
Foxtrick.listen(aLink, 'mouseover', showPopup, false);
span.appendChild(aLink);
}
};
// team links
var link = doc.querySelector('#teamLinks a');
if (link)
addSpan(link);
// all in mainWrapper (ie. not left boxes)
if (FORUM_RE.test(sUrl))
return; // not in forum overview
if (mainBody) {
let aLinks = mainBody.querySelectorAll('a');
for (let aLink of aLinks) {
if (!aLink.hasAttribute('href') ||
Foxtrick.hasClass(aLink, 'ft-no-popup') ||
aLink.parentNode.className == 'liveTabText' ||
aLink.querySelector('img:not(.ft-staff-icon)') !== null)
continue; // don't add to buttons, and htlive tabs
addSpan(aLink);
}
}
var sidebar = doc.getElementById('sidebar');
if (sidebar) {
let aLinks = sidebar.querySelectorAll('a');
for (let aLink of aLinks) {
if (!aLink.hasAttribute('href') ||
aLink.querySelector('img:not(.ft-staff-icon)') !== null)
continue; // don't add to buttons
addSpan(aLink);
}
}
},
change: function(doc) {
this.addPopupLinks(doc);
},
};
| minj/foxtrick | content/shortcuts-and-tweaks/team-popup-links.js | JavaScript | gpl-3.0 | 15,863 |
"""
A binary gap within a positive integer N is any maximal sequence of
consecutive zeros that is surrounded by ones at both ends in the binary
representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap
of length 2. The number 529 has binary representation 1000010001 and contains
two binary gaps: one of length 4 and one of length 3. The number 20 has binary
representation 10100 and contains one binary gap of length 1.
The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
def solution(N)
that, given a positive integer N, returns the length of its longest binary gap.
The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary
representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
N is an integer within the range [1..2,147,483,647].
Complexity:
expected worst-case time complexity is O(log(N));
expected worst-case space complexity is O(1).
"""
def solution(N):
cnt = 0
result = 0
found_one = False
i = N
while i:
if i & 1 == 1:
if (found_one is False):
found_one = True
else:
result = max(result, cnt)
cnt = 0
else:
cnt += 1
i >>= 1
return result
| Dineshkarthik/codility_training | Lesson 01 - Iterations/binary_gap.py | Python | gpl-3.0 | 1,391 |
package com.weaverplatform.database.virtuoso.profiles;
import com.google.gson.*;
import com.hp.hpl.jena.datatypes.DatatypeFormatException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.weaverplatform.commons.WeaverDatatype;
import com.weaverplatform.commons.WeaverError;
import com.weaverplatform.commons.WriteOperation;
import com.weaverplatform.commons.writeops.CreateAttribute;
import com.weaverplatform.commons.writeops.CreateNode;
import com.weaverplatform.commons.writeops.CreateRelation;
import com.weaverplatform.database.model.node.*;
import com.weaverplatform.database.model.query.WeaverNode;
import com.weaverplatform.database.model.query.WeaverQuery;
import com.weaverplatform.database.virtuoso.Operation;
import com.weaverplatform.database.virtuoso.TransactionRoll;
import com.weaverplatform.database.virtuoso.VirtuosoJDBC;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class NamedGraphsV1Profile implements Profile {
static Logger log = LoggerFactory.getLogger(NamedGraphsV1Profile.class);
public static final String PROFILE_NAME = "DefaultNamedGraphs-1";
private VirtuosoJDBC virtuoso;
@Override
public void setVirtuoso(VirtuosoJDBC virtuoso) {
this.virtuoso = virtuoso;
}
@Override
public synchronized int incrementAttribute(WriteOperation payload) {
int incrementWith = payload.getIntField("value");
int currentValue;
URI id = new URI(payload.getStringField("id"));
URI predicate = new URI(payload.getStringField("key"));
String query = "SELECT * WHERE { GRAPH "+id.toQuery()+
" { "+id.toQuery()+" "+predicate.toQuery()+" ?value }}";
ResultSet resultSet = virtuoso.jdbcSelect(query);
if(!resultSet.hasNext()) {
throw new WeaverError(WeaverError.INCREMENT_ERROR, "No previous value found");
}
RDFNode value = resultSet.next().get("value");
if(value == null) {
throw new WeaverError(WeaverError.INCREMENT_ERROR, "No previous value found");
}
try {
currentValue = value.asLiteral().getInt();
} catch (DatatypeFormatException e) {
throw new WeaverError(WeaverError.INCREMENT_ERROR, "Previous value is not an int, cannot increment");
}
int newValue = currentValue + incrementWith;
TransactionRoll roll = new TransactionRoll();
Operation removeOperation = new Operation(
" WITH "+id.toQuery()+
" DELETE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }" +
" WHERE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }");
removeOperation.requireOneResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(removeOperation);
Operation operation = new Operation(new Quad(id, predicate, new IntegerNode(newValue), id));
operation.requireOneResult(nodeExists(payload.getStringField("id")));
operation.requireNoResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(operation);
virtuoso.insertPayload(roll, true);
return newValue;
}
@Override
public TransactionRoll write(ArrayList<WriteOperation> operations) {
TransactionRoll roll = new TransactionRoll();
int elementIndex = 0;
for(WriteOperation operation : operations) {
try {
switch (operation.getAction()) {
case WriteOperation.CREATE_NODE :
createNode(operation, roll);
break;
case WriteOperation.REMOVE_NODE :
removeNode(operation, roll);
break;
case WriteOperation.CREATE_ATTRIBUTE :
if(operation.hasKey("datatype") && operation.getStringField("datatype").equals(WeaverDatatype.STRING_ARRAY)) {
// createArrayAttribute(operation, roll);
} else {
createAttribute(operation, roll);
}
break;
case WriteOperation.UPDATE_ATTRIBUTE :
if(operation.hasKey("datatype") && operation.getStringField("datatype").equals(WeaverDatatype.STRING_ARRAY)) {
// updateArrayAttribute(operation, roll);
} else {
updateAttribute(operation, roll);
}
break;
case WriteOperation.REMOVE_ATTRIBUTE :
if(operation.hasKey("datatype") && operation.getStringField("datatype").equals(WeaverDatatype.STRING_ARRAY)) {
// removeArrayAttribute(operation, roll);
} else {
removeAttribute(operation, roll);
}
break;
// case WriteOperation.ADD_TO_ATTRIBUTE_ARRAY :
// addToAttributeArray(operation, roll);
// break;
//
// case WriteOperation.SPLICE_ATTRIBUTE_ARRAY :
// spliceAttributeArray(operation, roll);
// break;
case WriteOperation.CREATE_RELATION :
createRelation(operation, roll);
break;
case WriteOperation.UPDATE_RELATION :
updateRelation(operation, roll);
break;
case WriteOperation.REMOVE_RELATION :
// if(!virtuoso.oneResult(relationObjectified(operation.getStringField("from"), operation.getStringField("key"), operation.getStringField("to")))) {
removeRelation(operation, roll);
// } else {
// removeObjectifiedRelation(operation, roll);
// }
break;
case WriteOperation.MERGE_NODES :
mergeNodes(operation, roll);
break;
default:
throw new WeaverError(WeaverError.WRITE_OPERATION_NOT_EXISTS, "This operation is not supported: "+operation.getAction());
}
} catch(WeaverError e) {
e.setElementIndex(elementIndex);
throw e;
}
elementIndex++;
}
return roll;
}
// Checking methods
private String nodeExists(String id) {
URI idUri = new URI(id);
return "SELECT * WHERE { GRAPH "+idUri.toQuery()+" { "+idUri.toQuery()+" "+URI.CREATED_ON.toQuery()+" ?o }}";
}
private String attributeExists(String id, String key) {
URI idUri = new URI(id);
URI predicateUri = new URI(key);
return "SELECT * WHERE { GRAPH "+idUri.toQuery()+" { "+idUri.toQuery()+" "+predicateUri.toQuery()+" ?o }}";
}
// private String isArrayAttribute(String id, String key) {
//
// URI idUri = new URI(id);
// URI predicateUri = new URI(key);
//
// return "SELECT * WHERE { GRAPH "+idUri.toQuery()+" { "+idUri.toQuery()+" "+predicateUri.toQuery()+" ?list . ?list <"+ RDF.type.getURI()+"> <"+ RDF.List.getURI()+"> }}";
// }
// Answers true in both case of anonymous and objectified relation
private String relationExists(URI from, String key, URI to) {
return "SELECT * WHERE { GRAPH ?g { "+from.toQuery()+" "+new URI(key).toQuery()+" "+ to.toQuery()+" . }}";
}
private String relationExists(URI from, String key, URI to, URI id) {
return "SELECT * WHERE { GRAPH "+id.toQuery()+" { "+from.toQuery()+" "+new URI(key).toQuery()+" "+ to.toQuery()+" . }}";
}
private String relationObjectified(String from, String key, String to) {
URI fromUri = new URI(from);
URI predicateUri = new URI(key);
URI toUri = new URI(to);
return "SELECT * WHERE { GRAPH ?g { "+fromUri.toQuery()+" "+predicateUri.toQuery()+" "+ toUri.toQuery()+" . FILTER (?g != "+fromUri.toQuery()+") }}";
}
// Create methods
private void createNode(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
Operation operation = new Operation(new Quad(id, URI.CREATED_ON, new DateTimeNode(payload.getTimestamp()), id));
operation.requireNoResult(nodeExists(payload.getStringField("id")));
roll.add(operation);
}
private void removeNode(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
Operation operation = new Operation(
" DELETE { graph ?g { ?s ?p ?o }}" +
" WHERE { graph ?g { ?s ?p ?o } . graph ?g { ?s1 ?p1 ?o1 } . FILTER (?s1 = "+id.toQuery()+" || ?o1 = "+id.toQuery()+" )}");
operation.requireOneResult(nodeExists(payload.getStringField("id")));
roll.add(operation);
}
private void createAttribute(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
URI predicate = new URI(payload.getStringField("key"));
Node value = NodeFactory.parse(payload);
Operation operation = new Operation(new Quad(id, predicate, value, id));
operation.requireOneResult(nodeExists(payload.getStringField("id")));
operation.requireNoResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(operation);
}
private void updateAttribute(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
URI predicate = new URI(payload.getStringField("key"));
Node value = NodeFactory.parse(payload);
Operation removeOperation = new Operation(
" WITH "+id.toQuery()+
" DELETE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }" +
" WHERE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }");
removeOperation.requireOneResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(removeOperation);
Operation addOperation = new Operation(new Quad(id, predicate, value, id));
addOperation.requireOneResult(nodeExists(payload.getStringField("id")));
addOperation.requireNoResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(addOperation);
}
// private void createArrayAttribute(WriteOperation payload, TransactionRoll roll) {
//
// URI id = new URI(payload.getStringField("id"));
// URI predicate = new URI(payload.getStringField("key"));
// Operation operation;
//
// AnonNode a = new AnonNode();
//
// operation = new Operation(new Quad(id, predicate, a, id));
// operation.requireOneResult(nodeExists(payload.getStringField("id")));
// operation.requireNoResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
// roll.add(operation);
//
// operation = new Operation(new Quad(a, new URI(RDF.type), new URI(RDF.List), id));
// roll.add(operation);
//
// ArrayList<String> list = payload.getStringArrayField("value");
// Iterator<String> iterator = list.iterator();
// while(iterator.hasNext()) {
// String value = iterator.next();
// operation = new Operation(new Quad(a, new URI(RDF.first), new LiteralNode(value), id));
// roll.add(operation);
// if(iterator.hasNext()) {
// AnonNode b = new AnonNode();
// operation = new Operation(new Quad(a, new URI(RDF.rest), b, id));
// roll.add(operation);
// a = b;
// }
// }
// }
// private void removeArrayAttribute(WriteOperation payload, TransactionRoll roll) {
//
// URI id = new URI(payload.getStringField("id"));
// URI predicate = new URI(payload.getStringField("key"));
//
// Operation operation = new Operation(" WITH "+id.toQuery()+
// " DELETE { " + id.toQuery() + " " + predicate.toQuery() + " ?old . ?old ?rel* ?any }" + // todo: second opinion
// " WHERE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }");
// operation.requireOneResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
// operation.requireOneResult(isArrayAttribute(payload.getStringField("id"), payload.getStringField("key")));
// roll.add(operation);
// }
private void removeAttribute(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
URI predicate = new URI(payload.getStringField("key"));
Operation operation = new Operation(
" WITH "+id.toQuery()+
" DELETE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }" +
" WHERE { "+id.toQuery()+" "+predicate.toQuery()+" ?old }");
operation.requireOneResult(attributeExists(payload.getStringField("id"), payload.getStringField("key")));
roll.add(operation);
}
private void createRelation(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
URI from = new URI(payload.getStringField("from"));
URI predicate = new URI(payload.getStringField("key"));
URI to = new URI(payload.getStringField("to"));
Operation operation;
operation = new Operation(new Quad(id, URI.CREATED_ON, new DateTimeNode(payload.getTimestamp()), id));
operation.requireNoResult(nodeExists(payload.getStringField("id")));
roll.add(operation);
operation = new Operation(new Quad(from, predicate, to, id));
operation.requireOneResult(nodeExists(payload.getStringField("from")));
operation.requireOneResult(nodeExists(payload.getStringField("to")));
operation.requireNoResult(relationExists(from, payload.getStringField("key"), to, id));
roll.add(operation);
}
private void updateRelation(WriteOperation payload, TransactionRoll roll) {
URI id = new URI(payload.getStringField("id"));
URI from = new URI(payload.getStringField("from"));
URI predicate = new URI(payload.getStringField("key"));
URI oldTo = new URI(payload.getStringField("oldTo"));
URI newTo = new URI(payload.getStringField("newTo"));
Operation removeOperation = new Operation(
" DELETE { GRAPH ?g { "+from.toQuery()+" "+predicate.toQuery()+" "+oldTo.toQuery()+" }}" +
" WHERE { GRAPH ?g { "+from.toQuery()+" "+predicate.toQuery()+" ?old }}");
removeOperation.requireOneResult(relationExists(from, payload.getStringField("key"), oldTo, id));
roll.add(removeOperation);
Operation createOperation = new Operation(new Quad(from, predicate, newTo, id));
createOperation.requireOneResult(nodeExists(payload.getStringField("from")));
createOperation.requireOneResult(nodeExists(payload.getStringField("newTo")));
createOperation.requireNoResult(relationExists(from, payload.getStringField("key"), newTo, id));
roll.add(createOperation);
}
private void removeRelation(WriteOperation payload, TransactionRoll roll) {
URI from = new URI(payload.getStringField("from"));
URI predicate = new URI(payload.getStringField("key"));
URI to = new URI(payload.getStringField("to"));
Operation operation;
if(payload.hasKey("id")) {
URI id = new URI(payload.getStringField("id"));
operation = new Operation(
" DELETE { GRAPH ?g { ?s ?p ?o }}" +
" WHERE { GRAPH ?g { ?s ?p ?o } FILTER(?g = "+id.toQuery()+" )}");
} else {
operation = new Operation(
" DELETE { GRAPH ?g { ?s ?p ?o }}" +
" WHERE { GRAPH ?g { ?s ?p ?o } GRAPH ?g { " + from.toQuery() + " " + predicate.toQuery() + " " + to.toQuery() + " }}");
}
operation.requireOneResult(relationExists(from, payload.getStringField("key"), to));
roll.add(operation);
}
private void mergeNodes(WriteOperation payload, TransactionRoll roll) {
URI idInto = new URI(payload.getStringField("idInto"));
URI idMerge = new URI(payload.getStringField("idMerge"));
// Move all attributes from id_merge to id_into and
// all (non objectified) relations from id_merge to id_into
Operation operation;
operation = new Operation(
" DELETE { GRAPH "+idMerge.toQuery()+" { "+idMerge.toQuery()+" ?predicate ?object }}" +
" INSERT { GRAPH "+idInto.toQuery()+" { "+idInto.toQuery()+" ?predicate ?object }}" +
" WHERE { GRAPH "+idMerge.toQuery()+" { "+idMerge.toQuery()+" ?predicate ?object }}");
operation.requireOneResult(nodeExists(payload.getStringField("idInto")));
operation.requireOneResult(nodeExists(payload.getStringField("idMerge")));
roll.add(operation);
// Move all objectified relations from id_merge to id_into
operation = new Operation(
" DELETE { GRAPH ?graph { "+idMerge.toQuery()+" ?predicate ?object }}" +
" INSERT { GRAPH ?graph { "+idInto.toQuery()+" ?predicate ?object }}" +
" WHERE { GRAPH ?graph { "+idMerge.toQuery()+" ?predicate ?object } FILTER ( ?graph != "+idMerge.toQuery()+") }");
roll.add(operation);
// Make all the relations that pointed to id_merge point to id_into
operation = new Operation(
" DELETE { GRAPH ?graph { ?subject ?predicate "+idMerge.toQuery()+" }}" +
" INSERT { GRAPH ?graph { ?subject ?predicate "+idInto.toQuery()+" }}" +
" WHERE { GRAPH ?graph { ?subject ?predicate "+idMerge.toQuery()+" }}");
roll.add(operation);
}
// private void addToAttributeArray(WriteOperation payload, TransactionRoll roll) {
//
// Operation operation = new Operation(""); // todo
// operation.requireOneResult(nodeExists(payload.getStringField("id")));
// operation.requireOneResult(isArrayAttribute(payload.getStringField("id"), payload.getStringField("key")));
// roll.add(operation);
// }
//
// private void spliceAttributeArray(WriteOperation payload, TransactionRoll roll) {
// Operation operation = new Operation(""); // todo
// operation.requireOneResult(nodeExists(payload.getStringField("id")));
// operation.requireOneResult(isArrayAttribute(payload.getStringField("id"), payload.getStringField("key")));
// roll.add(operation);
// }
// Read methods
@Override
public String read(String id) {
URI idUri = new URI(id);
String queryString = "SELECT * WHERE { GRAPH ?g { "+idUri.toQuery()+" ?p ?o }}";
ResultSet resultSet = virtuoso.jdbcSelect(queryString);
if(!resultSet.hasNext()) {
throw new WeaverError(WeaverError.NODE_NOT_FOUND, "Node with id " + id + " not found in virtuoso");
}
JsonObject jsonObject = new JsonObject();
// try {
jsonObject.addProperty("id", id);
while (resultSet.hasNext()) {
QuerySolution row = resultSet.next();
RDFNode p = row.get("p");
RDFNode o = row.get("o");
if (o.isLiteral()) {
String key = new URI(p.asResource().getURI()).getId();
JsonPrimitive value = NodeFactory.parse(o.asLiteral()).toJson();
jsonObject.add(key, value);
}
if (o.isURIResource()) {
String key = new URI(p.asResource().getURI()).getId();
JsonArray jsonArray;
if (!jsonObject.has(key)) {
jsonArray = new JsonArray();
jsonObject.add(key, jsonArray);
} else {
jsonArray = (JsonArray) jsonObject.get(key);
}
JsonObject object = new JsonObject();
object.addProperty("id", new URI(o.asResource().getURI()).getId());
jsonArray.add(object);
}
}
// } catch(RuntimeException e) {
// log.warn("Unexpected runtime exception.", e);
// }
return jsonObject.toString();
}
@Override
public String snapshot() {
GsonBuilder builder = new GsonBuilder();
List<com.weaverplatform.commons.writeops.Operation> ops = new ArrayList<>();
ResultSet nodes = virtuoso.jdbcSelect("SELECT DISTINCT ?id ?date WHERE { GRAPH ?id { ?id "+URI.CREATED_ON.toQuery()+" ?date MINUS {?s2 ?p2 ?o2 FILTER(?s2 != ?id)} }}");
while(nodes.hasNext()) {
if(nodes.getRowNumber() % 1000 == 0)
log.trace("Snapshotting nodes at node " + nodes.getRowNumber());
QuerySolution row = nodes.next();
String id = new URI(row.get("id").asResource()).getId();
ops.add(new CreateNode(id));
}
ResultSet relations = virtuoso.jdbcSelect("SELECT DISTINCT ?id ?date ?from ?key ?to WHERE { GRAPH ?id { ?id "+URI.CREATED_ON.toQuery()+" ?date . ?from ?key ?to . FILTER(isUri(?from)) . FILTER(isUri(?to)) . FILTER(?from != ?id) }}");
while(relations.hasNext()) {
QuerySolution row = relations.next();
String from = new URI(row.get("from").asResource()).getId();
String key = new URI(row.get("key").asResource()).getId();
String to = new URI(row.get("to").asResource()).getId();
String id = new URI(row.get("id").asResource()).getId();
ops.add(new CreateRelation(id, key, from, to));
}
ResultSet attributes = virtuoso.jdbcSelect("SELECT DISTINCT ?id ?date ?key ?value WHERE { GRAPH ?id { ?id "+URI.CREATED_ON.toQuery()+" ?date . ?id ?key ?value . FILTER(isLiteral(?value)) }}");
while(attributes.hasNext()) {
QuerySolution row = attributes.next();
String id = new URI(row.get("id").asResource()).getId();
String key = new URI(row.get("key").asResource()).getId();
JsonPrimitive value = NodeFactory.parse(row.get("value").asLiteral()).toJson();
if(URI.CREATED_ON.equals(new URI(row.get("key").asResource()))) {
continue;
}
ops.add(new CreateAttribute(id, key, value));
}
return new Gson().toJson(ops);
}
@Override
public ResultSet dump(ArrayList<URI> uris) {
String selector = "";
Iterator<URI> iterator = uris.iterator();
while(iterator.hasNext()) {
selector += iterator.next().toQuery();
if(iterator.hasNext()) {
selector += ",";
}
}
return virtuoso.jdbcSelect("SELECT DISTINCT ?s ?p ?o WHERE { GRAPH ?g { ?s ?p ?o . FILTER(?s IN ("+selector+"))}}");
}
@Override
public String listRelationKeys() {
JsonArray jsonArray = new JsonArray();
String queryString = "SELECT DISTINCT ?p WHERE { GRAPH ?g { ?s ?p ?o }}";
ResultSet resultSet = virtuoso.jdbcSelect(queryString);
while (resultSet.hasNext()) {
QuerySolution row = resultSet.next();
RDFNode p = row.get("p");
jsonArray.add(new URI(p.asResource().getURI()).getId());
}
return jsonArray.toString();
}
@Override
public String listNodes(List<String> attributes) {
HashMap<String, JsonObject> elements = new HashMap();
String queryString = "SELECT DISTINCT ?s ?p ?o WHERE { GRAPH ?g { ?s ?p ?o }}";
ResultSet resultSet = virtuoso.jdbcSelect(queryString);
while (resultSet.hasNext()) {
QuerySolution row = resultSet.next();
RDFNode s = row.get("s");
RDFNode p = row.get("p");
RDFNode o = row.get("o");
String predicate = new URI(p.asResource().getURI()).getId();
if(s.isURIResource()) {
JsonObject object;
URI id = new URI(s.asResource().getURI());
if(elements.containsKey(id.getId())) {
object = elements.get(id.getId());
} else {
object = new JsonObject();
object.addProperty("id", id.getId());
elements.put(id.getId(), object);
}
if(attributes.contains(predicate)) {
if(o.isLiteral()) {
object.add(predicate, NodeFactory.parse(o.asLiteral()).toJson());
}
}
}
}
JsonArray jsonArray = new JsonArray();
for(JsonObject element : elements.values()) {
jsonArray.add(element);
}
return jsonArray.toString();
}
@Override
public Collection<WeaverNode> executeQuery(WeaverQuery query) {
return new DefaultQueryExecutor(query, virtuoso).execute();
}
@Override
public int countQuery(WeaverQuery query) {
return new DefaultQueryExecutor(query, virtuoso).executeCount();
}
}
| weaverplatform/weaver-database-virtuoso | src/main/java/com/weaverplatform/database/virtuoso/profiles/NamedGraphsV1Profile.java | Java | gpl-3.0 | 23,172 |
using System;
namespace Server.Items
{
public class DragonTurtleHideArms : BaseArmor
{
[Constructable]
public DragonTurtleHideArms()
: base(0x782E)
{
Weight = 5.0;
}
public DragonTurtleHideArms(Serial serial)
: base(serial)
{
}
public override int BasePhysicalResistance
{
get
{
return 5;
}
}
public override int BaseFireResistance
{
get
{
return 3;
}
}
public override int BaseColdResistance
{
get
{
return 2;
}
}
public override int BasePoisonResistance
{
get
{
return 3;
}
}
public override int BaseEnergyResistance
{
get
{
return 2;
}
}
public override int InitMinHits
{
get
{
return 50;
}
}
public override int InitMaxHits
{
get
{
return 65;
}
}
public override int AosStrReq
{
get
{
return 80;
}
}
public override int OldStrReq
{
get
{
return 40;
}
}
public override int OldDexBonus
{
get
{
return -2;
}
}
public override int ArmorBase
{
get
{
return 40;
}
}
public override ArmorMaterialType MaterialType
{
get
{
return ArmorMaterialType.Plate;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
if (this.Weight == 1.0)
this.Weight = 5.0;
}
}
} | GenerationOfWorlds/GOW | Scripts/Core/Time Of Legends/Items/Equipment/Armor/Turtle/DragonTurtleHideArms.cs | C# | gpl-3.0 | 2,367 |
/*
* This file is part of the continuous space language and translation model toolkit
* for statistical machine translation and large vocabulary speech recognition.
*
* Copyright 2015, Holger Schwenk, LIUM, University of Le Mans, France
*
* The CSLM toolkit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3 as
* published by the Free Software Foundation
*
* 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 namespace std;
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <time.h>
#include "Tools.h"
#include "Mach.h"
#include "MachTab.h"
#include "MachPar.h"
#include "MachSeq.h"
#include "MachSplit1.h"
#include "TrainerPhraseSlist1.h"
#include "NBest.h"
#include "sort.cpp"
void TrainerPhraseSlist1::DoConstructorWork()
{
char msg[1024];
idim=mach->GetIdim(); odim=mach->GetOdim(); bsize=mach->GetBsize();
#ifdef BLAS_CUDA
Gpu::SetConfig(mach->GetGpuConfig());
gpu_input = Gpu::Alloc(idim*bsize, "inputs in Trainer");
gpu_target = Gpu::Alloc(odim*bsize, "targets in Trainer");
host_output = new REAL[odim*bsize];
#endif
buf_target_wid = new WordID[odim*bsize];
buf_target_ext = new WordID[odim*bsize];
// set up vector to outputs of the target phrases
if (mach->GetMType() != file_header_mtype_mseq)
Error("CSTM: sequential machine needed\n");
MachSeq *mseq=(MachSeq*) mach;
if (mseq->MachGetNb()<2)
Error("CSTM: the number of machines is suspeciously small");
// check input layer
if (mseq->MachGet(0)->GetMType() != file_header_mtype_mpar)
Error("TrainerPhraseSlist1::DoConstructorWork: CSTM: the input layer has the wrong architecture\n");
MachPar *mpar = (MachPar*) mseq->MachGet(0);
if (mpar->MachGet(0)->GetMType() != file_header_mtype_tab)
Error("TrainerPhraseSlist1::DoConstructorWork: CSTM: the input layer has the wrong architecture\n");
MachTab *mtab = (MachTab*) mpar->MachGet(0);
max_inp_idx = mtab->GetMaxInpVal();
// check output layer
if (mseq->MachGet(mseq->MachGetNb()-1)->GetMType() != file_header_mtype_msplit1)
Error("CSTM: the output layer has the wrong architecture\n");
MachSplit1 *msp = (MachSplit1*) mseq->MachGet(mseq->MachGetNb()-1);
tg_nbphr=msp->MachGetNb();
if (data_train && (data_train->GetOdim() != tg_nbphr)) {
sprintf(msg,"CSTM: output dimension of the training data should be %d, found %d\n", tg_nbphr, data_train->GetOdim());
Error(msg);
}
phrase_mach.clear();
for (int m=0; m<tg_nbphr; m++) {
phrase_mach.push_back(msp->MachGet(m));
if (m>0 && phrase_mach[m-1]->GetOdim() != phrase_mach[m]->GetOdim())
Error("CSTM: the output layer dimension must be identical for all phrases\n");
}
dim_per_phrase = phrase_mach[0]->GetOdim();
cout << " - this machine can predict up to " << phrase_mach.size() << " phrases, each with an output layer of dimension " << dim_per_phrase << endl;
tg_slist_len = dim_per_phrase-1;
// get source word list
if (sr_wlist == NULL) {
vector<WordList> *vect_wlist = NULL;
if (data_dev != NULL)
vect_wlist = data_dev->GetSrcWList();
else if (data_train != NULL)
vect_wlist = data_train->GetSrcWList();
if ((vect_wlist != NULL) && !vect_wlist->empty())
sr_wlist = &(vect_wlist->front());
}
if (sr_wlist == NULL)
Error("no source word list available");
if ((int) sr_wlist->GetSize() > max_inp_idx)
Error("the size of the source word list exceeds the number of input words the machine was trained for");
// get target word list
if (tg_wlist == NULL) {
vector<WordList> *vect_wlist = NULL;
if (data_dev != NULL)
vect_wlist = data_dev->GetTgtWList();
else if (data_train != NULL)
vect_wlist = data_train->GetTgtWList();
if ((vect_wlist != NULL) && !vect_wlist->empty())
tg_wlist = &(vect_wlist->front());
}
if (tg_wlist == NULL)
Error("no target word list available");
if (!tg_wlist->FrequSort())
Error("the target word list don't contain word count");
if (tg_wlist->GetSize() <= tg_slist_len)
Error("TrainerPhraseSlist1: the output layer is larger than the target word list");
ulong sum_sl=0, sum=0;
tg_wlist->SetShortListLength(tg_slist_len);
tg_wlist->CountWords(sum_sl, sum);
printf (" - setting up target short list of %d words, coverage of %5.2f%%\n", tg_slist_len, 100.0*sum_sl/sum);
#ifdef DEBUG2
cout << "Words in slist:" << endl;
WordID ci=tg_slist_len;
WordList::const_iterator iter, end = tg_wlist->End();
for (iter=tg_wlist->Begin(); (iter!=end) && (ci > 0); iter++, ci--)
printf (" %s cnt=%d idx=%d\n", iter->word, iter->n, iter->id);
#endif
#ifdef DEBUG2
cout << "Words not in slist:" << endl;
for (; iter!=end; iter++)
printf (" %s cnt=%d idx=%d\n", iter->word, iter->n, iter->id);
#endif
#ifdef DEBUG2
// just needed for debugging
words.reserve(tg_wlist->GetSize());
for (iter=tg_wlist->Begin(); iter!=end; iter++) words[iter->id] = strdup(iter->word);
#endif
debug0(" + done init TrainerPhraseSlist1\n");
}
//
// constructor for training
//
TrainerPhraseSlist1::TrainerPhraseSlist1 (Mach *pmach, Lrate *lrate, ErrFct *perrfct,
const char *train_fname, const char *dev_fname, const char *pt_fname, int p_nscores,
REAL p_wd, int p_maxep, int p_ep)
: Trainer(pmach,lrate,perrfct,NULL,NULL,p_wd,p_maxep,p_ep),
tg_nbphr(0), tg_slist_len(0),
sr_wlist(NULL), tg_wlist(NULL),
nb_ex_slist(0), nb_ex_short(0),
nb_forw(0)
{
debug2("*** Constructor TrainerPhraseSlist1 for training idim=%d, odim=%d ***\n",idim,odim);
cout << "Setting up CSTM training with short list" << endl;
char msg[1024];
if (train_fname) {
data_train = new Data(train_fname);
if (idim != data_train->GetIdim()) {
sprintf(msg,"TrainerPhraseSlist1: input dimension of the training data (%d) does not match the one of the machine (%d)\n", data_train->GetIdim(), idim);
Error(msg);
}
if (data_train->GetOdim()<1 || data_train->GetOdim()>10) {
sprintf(msg,"TrainerPhraseSlist1: output dimension of the training data should be 1..10, found %d\n", data_train->GetOdim());
Error(msg);
}
auxdim = data_train->GetAuxdim();
}
else
data_train=NULL;
if (dev_fname) {
data_dev = new Data(dev_fname);
data_dev_alloc=true;
if (idim != data_dev->GetIdim()) {
sprintf(msg,"TrainerPhraseSlist1: input dimension of the validation data (%d) does not match the one of the machine (%d)\n", data_dev->GetIdim(), idim);
Error(msg);
}
if (data_dev->GetOdim()<1 || data_dev->GetOdim()>10) {
sprintf(msg,"TrainerPhraseSlist1: output dimension of the validation data should be 1..10, found %d\n", data_dev->GetOdim());
Error(msg);
}
int auxdim_dev = data_dev->GetAuxdim();
if (0 >= auxdim)
auxdim = auxdim_dev;
else if (auxdim != auxdim_dev)
ErrorN("TrainerPhraseSlist1: auxiliary data dimension of the validation data should be %d, found %d", auxdim, auxdim_dev);
}
else {
data_dev=NULL;
data_dev_alloc=false;
}
iaux = (idim - auxdim);
DoConstructorWork();
if (data_dev) {
if (pt_fname) {
cout << " - loading external phrase table from " << pt_fname << endl;
ptable.Read(pt_fname,5,"1:2");
}
else
cout << " - no external phrase table provided" << endl;
}
}
//
// constructor for testing
//
TrainerPhraseSlist1::TrainerPhraseSlist1 (Mach *pmach, ErrFct *perrfct,
Data *data, char *pt_fname, int p_nscores)
: Trainer(pmach,NULL,perrfct,NULL,NULL),
tg_nbphr(0), tg_slist_len(0),
sr_wlist(NULL), tg_wlist(NULL),
nb_ex_slist(0), nb_ex_short(0),
nb_forw(0)
{
debug0("*** Constructor TrainerPhraseSlist1 for testing ***\n");
cout << "Setting up testing with short list" << endl;
char msg[1024];
data_train=NULL;
data_dev=data;
data_dev_alloc=false; // do not free it by this class !
if (idim != data_dev->GetIdim()) {
sprintf(msg,"TrainerPhraseSlist1: input dimension of the test data (%d) does not match the one of the machine (%d)\n", data_dev->GetIdim(), idim);
Error(msg);
}
auxdim = data_dev->GetAuxdim();
iaux = (idim - auxdim);
DoConstructorWork();
cout << " - loading external phrase table from " << pt_fname << endl;
#ifdef BACKWRAD_TM
ptable.Read(pt_fname,5,"1:0"); // backward TM prob
#else
ptable.Read(pt_fname,5,"1:2"); // forward TM prob
#endif
}
//
// constructor for nbest rescoring
//
TrainerPhraseSlist1::TrainerPhraseSlist1 (Mach *pmach,
WordList *p_sr_wlist, WordList *p_tg_wlist,
char *pt_fname, int nscores, char *scores_specif)
: Trainer(pmach,NULL,NULL,NULL,NULL), // TODO; should I call: TrainerNgram(pmach,NULL,NULL,NULL),
tg_nbphr(0), tg_slist_len(0),
sr_wlist(p_sr_wlist), tg_wlist(p_tg_wlist),
nb_ex_short(0), nb_forw(0)
{
debug0("*** Constructor TrainerPhraseSlist1 for block operations ***\n");
cout << "Setting up CSTM with short list" << endl;
// TODO: init with TrainerNgram before
DoConstructorWork();
cout << " - loading external phrase table from " << pt_fname << endl;
ptable.Read(pt_fname, nscores, scores_specif);
}
//**************************************************************************************
TrainerPhraseSlist1::~TrainerPhraseSlist1 ()
{
debug0("*** Destructor TrainerPhraseSlist1 ***\n");
if (buf_target_wid) delete [] buf_target_wid;
if (buf_target_ext) delete [] buf_target_ext;
// buf_input and buf_target will be deleted by ~Trainer()
phrase_mach.clear();
#ifdef DEBUG2
vector<char*>::const_iterator iter, end = words.end();
for (iter=words.begin(); iter!=end; iter++) delete *iter;
words.clear();
#endif
}
//**************************************************************************************
REAL TrainerPhraseSlist1::Train()
{
if (!data_train) return -1;
#ifdef DEBUG
printf("*****************\n");
printf("TrainerPhraseSlist1::Train():\n");
printf(" - idim=%d, odim=%d, tg_nbphr=%d\n", idim, odim, tg_nbphr);
printf(" - data_in: %p \n", (void*) buf_input);
printf(" - target: %p \n", (void*) buf_target);
printf(" - tgt WID: %p \n", (void*) buf_target_wid);
printf(" - grad_out: %p \n", (void*) errfct->GetGrad());
#endif
Timer ttrain; // total training time
Timer tload;
Timer ttransfer; // total transfer time of data to GPU
Timer tforw; // total forw time
Timer tgrad; // total gradient time
Timer tbackw; // total backw time
ttrain.start();
data_train->Rewind();
REAL log_sum=0;
int i;
nb_ex=nb_ex_slist=nb_ex_short_inp=nb_ex_short=0;
nb_tg_words=nb_tg_words_slist=0;
#ifdef BLAS_CUDA
Gpu::SetConfig(mach->GetGpuConfig());
mach->SetDataIn(gpu_input); // we copy from buf_input to gpu_input
errfct->SetTarget(gpu_target); // we copy from buf_target to gpu_target
debug1(" - gpu_input %p\n", gpu_input);
debug1(" - gpu_target %p\n", gpu_target);
#else
mach->SetDataIn(buf_input);
errfct->SetTarget(buf_target);
debug1(" - buf_input %p\n", buf_input);
debug1(" - buf_target %p\n", buf_target);
#endif
errfct->SetOutput(mach->GetDataOut());
mach->SetGradOut(errfct->GetGrad());
bool data_available;
do {
tload.start();
// get a bunch of data and map all the words
int n=0, nbtgsl=0;
data_available = true;
while (n < mach->GetBsize() && data_available) {
data_available = data_train->Next();
if (!data_available) break;
debug0("TRAIN DATA: input: ");
bool at_least_one_short=false;
for (i=0; i<iaux; i++) { // copy word indexes
WordID inp=(WordID) data_train->input[i];
debug2(" %s[%d]", sr_wlist->GetWordInfo(inp).word,inp);
#if TODO // should we map input data ?
buf_input[n*idim + i] = (REAL) sr_wlist->MapIndex(inp, "TrainerPhraseSlist1::Train(): input"); // map context words IDs
if (inp == NULL_WORD)
at_least_one_short=true;
#else
buf_input[n*idim + i] = inp;
if (inp == NULL_WORD)
at_least_one_short=true;
else if (inp<0 || inp>=(int)sr_wlist->GetSize())
ErrorN("TrainerPhraseSlist1::Train(): input out of bounds (%d), must be in [0,%d[", inp, (int) sr_wlist->GetSize());
#endif
}
for (; i < idim ; i++) // copy auxiliary data
buf_input[n * idim + i] = data_train->input[i];
if (at_least_one_short) nb_ex_short_inp++;
debug0(" - > mapped: ");
bool all_in_slist=true; // ALL to be predicted words are in short list
at_least_one_short=false;
nbtgsl=0;
for (i=0; i<tg_nbphr; i++) {
WordID outp=(WordID) data_train->target[i];
int idx=i+n*tg_nbphr;
buf_target_wid[idx] = tg_wlist->MapIndex(outp, "TrainerPhraseSlist1::Train(): output"); // TODO: not really needed during training, just the current value
if (outp==NULL_WORD) {
buf_target[idx] = (REAL) NULL_WORD;
at_least_one_short=true;
debug1(" -[%d->NULL]",(int) buf_target[idx]);
}
else {
nb_tg_words++;
if (tg_wlist->InShortList(buf_target_wid[idx])) {
buf_target[idx] = (REAL) buf_target_wid[idx];
debug3(" %s[%d->%d]", tg_wlist->GetWordInfo(outp).word,(int) buf_target_wid[idx], outp);
nbtgsl++;
}
else {
buf_target[idx] = (REAL) tg_slist_len; // words that are not in slist are ALL done by the last output neuron
debug3(" %s[%d->%d]*", tg_wlist->GetWordInfo(outp).word,(int) buf_target_wid[idx], outp);
all_in_slist=false;
}
}
}
if (all_in_slist) {
nb_ex_slist++;
nb_tg_words_slist += nbtgsl;
}
if (at_least_one_short) nb_ex_short++;
debug1(" all_slist=%d\n",all_in_slist);
n++;
} // loop to get a bunch of examples
debug4("train bunch of %d words, totl=%d, totl slist=%d [%.2f%%]\n", n, nb_ex+n, nb_ex_slist, 100.0*nb_ex_slist/(nb_ex+n));
tload.stop();
#ifdef DEBUG2
printf("network data:\n");
REAL *iptr=buf_input;
REAL *tptr=buf_target;
for (int nn=0;nn<n;nn++) {
for (i=0;i<idim;i++) printf(" %f", *iptr++); printf(" -> ");
for (i=0;i<tg_nbphr;i++) printf(" %f", *tptr++); printf("\n");
}
#endif
if (n>0) {
#ifdef BLAS_CUDA
ttransfer.start();
Gpu::MemcpyAsync(gpu_input, buf_input , n*idim*sizeof(REAL), cudaMemcpyHostToDevice);
Gpu::MemcpyAsync(gpu_target, buf_target , n*odim*sizeof(REAL), cudaMemcpyHostToDevice);
Gpu::StreamSynchronize();
ttransfer.stop();
#endif
tforw.start();
mach->Forw(n,true);
tforw.stop();
tgrad.start();
log_sum += errfct->CalcGrad(n);
tgrad.stop();
debug1(" log_sum=%e\n",log_sum);
#ifdef DEBUG2
int t=(int) data_train->target[0];
#ifdef BLAS_CUDA
Gpu::SetConfig(mach->GetGpuConfig());
REAL * tmp = Gpu::Alloc(5, "tmp buffer for DEBUG2");
cublasGetVector(odim,CUDA_SIZE,mach->GetDataOut(),1,tmp,1);
printf("OUTPUT:");
for (int i=t-2;i<=t+2; i++) printf(" %f",tmp[i]); printf("\n");
cublasGetVector(3, CUDA_SIZE, data_train->target, 1, tmp, 1);
printf("TARGET:");
for (int i=0;i<1; i++) printf(" %f", tmp[i]); printf("\n");
//TODO check if we need odim or idim!
cublasGetVector(odim*bsize, CUDA_SIZE, errfct->GetGrad(), 1, tmp, 1);
printf(" GRAD:");
for (int i=t-2;i<=t+2; i++) printf(" %f",tmp[i]); printf("\n");
cublasFree(tmp);
#else
printf("OUTPUT:") ; for (int i=t-2;i<=t+2; i++) printf(" %f",mach->GetDataOut()[i]); printf("\n");
printf("TARGET:") ; for (int i=0;i<1; i++) printf(" %f",data_train->target[i]); printf("\n");
printf(" GRAD:") ; for (int i=t-2;i<=t+2; i++) printf(" %f",errfct->GetGrad()[i]); printf("\n");
#endif //BLAS_CUDA
#endif //DEBUG2
lrate->UpdateLrateOnForw(mach->GetNbForw());
tbackw.start();
mach->Backw(lrate->GetLrate(), wdecay, n);
tbackw.stop();
}
nb_ex += n;
} while (data_available);
#ifdef BLAS_CUDA
Gpu::StreamSynchronize();
#endif
ttrain.stop();
ttrain.disp(" - training time: ");
tload.disp(" including load: ");
#ifdef BLAS_CUDA
ttransfer.disp(" transfer: ");
#endif
tforw.disp(" forw: ");
tgrad.disp(" grad: ");
tbackw.disp(" backw: ");
printf("\n");
printf(" = log_sum=%.2f, nb_tg_words=%d, nb_ex_slist=%d, nb_tg_words_slist=%d\n", log_sum, nb_tg_words, nb_ex_slist, nb_tg_words_slist);
if (nb_tg_words>0) return exp(-log_sum / (REAL) nb_tg_words); // when normalizing consider that all examples lead to a forward pass
return -1;
}
//**************************************************************************************
//
void TrainerPhraseSlist1::GetMostLikelyTranslations (ofstream &fspt, REAL *optr, int ni)
{
int Nbest=100;
// get input length
int input_length;
for (input_length=0;input_length<iaux;input_length++) {
if (buf_input[ni*idim+input_length] == NULL_WORD) break;
}
std::vector<std::vector<std::pair<float, std::size_t> > > prepared_scores
= prepare_hypotheses(optr, tg_nbphr, dim_per_phrase, Nbest);
std::vector<std::pair<float, std::vector<std::size_t> > > best
= sort_ngrams(prepared_scores, input_length, Nbest);
for(std::size_t i = 0; i < best.size(); ++i) {
// source
for (int j=0; j<iaux; j++) {
if (buf_input[ni*idim+j] == NULL_WORD) break;
fspt << sr_wlist->GetWordInfo(buf_input[ni*idim+j]).word << " ";
}
// target
fspt << "|||";
for(std::size_t j = 0; j < best[i].second.size(); ++j) {
fspt << " " << tg_wlist->GetWordInfoMapped(best[i].second[j]).word;
}
// score
fspt << " ||| " << exp(best[i].first);
fspt << "\n";
}
}
//**************************************************************************************
//
#if 0
void TrainerPhraseSlist1::GetMostLikelyTranslations (ofstream &fspt, REAL *optr, int ni)
{
int i;
// Find most likely outputs
for (i=0;i<iaux;i++) {
if (buf_input[ni*idim+i] == NULL_WORD) break;
fspt << sr_wlist->GetWordInfo(buf_input[ni*idim+i]).word << " ";
}
fspt << "||| ";
for (i=0; i<tg_nbphr; i++) {
if (buf_target_wid[i+ni*tg_nbphr] == NULL_WORD) break;
tgrad.disp(" including ");
tgrad.disp(" including ");
// find max of current word
REAL *sptr=optr+i*dim_per_phrase, max=*sptr++; int max_idx=0;
for (int s=1; s<dim_per_phrase; s++, sptr++) {
if (*sptr>max) { max=*sptr; max_idx=s; }
}
fspt << tg_wlist->GetWordInfoMapped(max_idx).word << "[" << max << "] ";
}
fspt << endl;
}
#endif
//**************************************************************************************
//
REAL TrainerPhraseSlist1::TestDev(char *fname)
{
if (!data_dev) return -1;
vector<string> src_phrase; // interface with classical phrase tables
vector<string> tgt_phrase;
vector<bool> done_by_cstm;
ofstream fs;
if (fname) {
cout << " - dumping phrase probability stream to file '" << fname << "'" << endl;
fs.open(fname,ios::out);
CHECK_FILE(fs,fname);
}
char *ptfname = (char*) "alltrans.txt";
ofstream fspt;
cout << " - dumping new phrase table to file '" << ptfname << "'" << endl;
fspt.open(ptfname,ios::out);
CHECK_FILE(fspt,ptfname);
nb_ex=nb_ex_slist=nb_ex_short=0;
nb_tg_words=nb_tg_words_slist=0;
int nb_probs=0; // this counts the number of cumulated log probs.
// This increments by only one for external phrase tables, independently of the target phrase length
REAL logP, log_sum=0;
REAL log_sum_cstm=0; // only CSLM, i.e. considering phrases done by CSTM
uint idx;
#ifdef BLAS_CUDA
Gpu::SetConfig(mach->GetGpuConfig());
mach->SetDataIn(gpu_input); // we copy from buf_input to gpu_input
errfct->SetTarget(gpu_target); // we copy from buf_target to gpu_target
debug1(" - gpu_input %p\n", gpu_input);
debug1(" - gpu_target %p\n", gpu_target);
#else
mach->SetDataIn(buf_input);
errfct->SetTarget(buf_target);
#endif
errfct->SetOutput(mach->GetDataOut());
bool data_available;
data_dev->Rewind();
do {
// get a bunch of data
int n=0, i;
data_available = true;
debug0("start bunch\n");
done_by_cstm.clear();
while (n < mach->GetBsize() && data_available) {
data_available = data_dev->Next();
if (!data_available) break;
debug0("DEV DATA: input: ");
bool at_least_one_short=false;
for (i=0; i<iaux; i++) { // copy word indexes
WordID inp=(WordID) data_dev->input[i];
idx=n*idim + i;
debug1(" %d", inp);
#if TODO // should we map input data ?
buf_input[idx] = (REAL) sr_wlist->MapIndex(inp, "TrainerPhraseSlist1::TestDev(): input"); // map context words IDs
if (inp == NULL_WORD)
at_least_one_short=true;
#else
buf_input[idx] = inp;
if (inp == NULL_WORD)
at_least_one_short=true;
else if (inp<0 || inp>=(int)sr_wlist->GetSize())
ErrorN("TrainerPhraseSlist1::TestDev(): input out of bounds (%d), must be in [0,%d[", inp, (int) sr_wlist->GetSize());
#endif
}
for (; i < idim ; i++) // copy auxiliary data
buf_input[n * idim + i] = data_dev->input[i];
if (at_least_one_short) nb_ex_short_inp++;
debug0(" - > mapped: ");
bool all_in_slist=true; // ALL to be predicted words are in short list
int nb_words_not_null=0;
at_least_one_short=false;
for (i=0; i<tg_nbphr; i++) {
WordID outp=(WordID) data_dev->target[i];
idx=n*tg_nbphr + i;
buf_target_wid[idx] = tg_wlist->MapIndex(outp, "TrainerPhraseSlist1::TestDev(): output");
buf_target_ext[idx] = buf_target_wid[idx]; // keep target word ID for Moses phrase-table
if (outp==NULL_WORD) {
buf_target[idx] = (REAL) NULL_WORD;
at_least_one_short=true; // TODO: optimize: we should be able to stop the loop on "i"
debug1(" %d[NULL]",(int) buf_target_wid[idx]);
}
else {
nb_tg_words++;
nb_words_not_null++;
if (tg_wlist->InShortList(buf_target_wid[idx])) {
buf_target[idx] = (REAL) buf_target_wid[idx];
debug3(" %s[%d->%d]", tg_wlist->GetWordInfo(outp).word, (int) buf_target_wid[idx], outp);
//nbtgsl++;
}
else {
// TODO: we actually don't need a forward pass for words in the short lists or short n-grams
// this could be used to save some time (5-10%)
buf_target_wid[idx] = tg_slist_len;
buf_target[idx] = (REAL) tg_slist_len; // words that are not in slist are ALL done by the last output neuron
debug3(" %s[%d->%d]*", tg_wlist->GetWordInfo(outp).word,(int) buf_target_wid[idx], outp);
all_in_slist=false;
}
}
}
done_by_cstm.push_back(all_in_slist);
if (all_in_slist) {
nb_ex_slist++;
nb_tg_words_slist += nb_words_not_null;
//nb_tg_words_slist += nbtgsl;
}
if (!at_least_one_short) nb_ex_short++;
debug1(" all_slist=%d\n",all_in_slist);
n++;
} // loop to get a bunch ef examples
debug4("dev bunch of %d phrases, totl=%d, totl slist=%d [%.2f%%]\n", n, nb_ex+n, nb_ex_slist, 100.0*nb_ex_slist/(nb_ex+n));
#ifdef DEBUG2
printf("network data:\n");
REAL *iptr=buf_input;
REAL *tptr=buf_target;
for (int nn=0;nn<n;nn++) {
for (i=0;i<idim;i++) printf(" %f", *iptr++); printf(" -> ");
for (i=0;i<tg_nbphr;i++) printf(" %f", *tptr++); printf("\n");
}
#endif
// process the bunch by the neural network
if (n>0) {
#ifdef BLAS_CUDA
Gpu::MemcpyAsync(gpu_input, buf_input , n*idim*sizeof(REAL), cudaMemcpyHostToDevice);
Gpu::MemcpyAsync(gpu_target, buf_target , n*odim*sizeof(REAL), cudaMemcpyHostToDevice);
#endif
mach->Forw(n,false);
log_sum_cstm += errfct->CalcValue(n);
}
// get probas from CSLM or back-off LM
#ifdef BLAS_CUDA
cudaMemcpy(host_output, mach->GetDataOut(), n*odim*sizeof(REAL), cudaMemcpyDeviceToHost);
REAL *optr=host_output;
Error("TrainerPhraseSlist1::TestDev TODO CUDA");
#else
REAL *optr=mach->GetDataOut(); // n times (tg_nbphr*tg_slen) = odim values
#endif
debug1("Collect n=%d\n", n);
if (n!=(int) done_by_cstm.size())
Error("TrainerPhraseSlist1::TestDev(): internal error, number of phrases done by CSTM does not match");
REAL *ptr_input = buf_input; // n times idim values
for (int ni=0; ni<n; ni++) {
int nb_tg=0; // for normalization
if (done_by_cstm[ni]) {
// get proba from CSTM (removed renorm)
#define DUMP_PHRASE_TABLE
#ifdef DUMP_PHRASE_TABLE
// create output phrase table
for (i=0;i<iaux;i++) {
if (buf_input[ni*idim+i] == NULL_WORD) break;
fspt << sr_wlist->GetWordInfo(buf_input[ni*idim+i]).word << " ";
}
fspt << "||| ";
for (i=0;i<tg_nbphr;i++) {
if (buf_target_wid[i+ni*tg_nbphr] == NULL_WORD) break;
fspt << tg_wlist->GetWordInfoMapped(buf_target_wid[ni*tg_nbphr+i]).word << " ";
}
fspt << "||| ";
#endif
logP=0;
REAL *optr2=optr;
for (i=0; i<tg_nbphr; i++) {
if (buf_target_wid[i+ni*tg_nbphr] == NULL_WORD) break;
logP += safelog(optr2[buf_target_wid[i+ni*tg_nbphr]]); // no error check on indices necessary here
nb_tg++;
#ifdef DUMP_PHRASE_TABLE2
fspt << optr2[buf_target_wid[i+ni*tg_nbphr]] << " ";
#endif
optr2+=dim_per_phrase;
}
#ifdef DUMP_PHRASE_TABLE
fspt << logP/nb_tg << endl;
#endif
#ifdef DUMP_PHRASE_TABLE_NBEST
GetMostLikelyTranslations(fspt,optr,ni);
#endif
nb_probs+=i;
debug1(" CSLM: logP=%e\n", logP);
}
else {
// request proba from Moses phrase-table
#if 1
debug0("create textual phrase pair for external phrase table (word + index)\n");
src_phrase.clear();
debug0(" source:");
for (i=0; i<iaux && ptr_input[i]!=NULL_WORD; i++) {
src_phrase.push_back(sr_wlist->GetWordInfo((uint) ptr_input[i]).word); // TODO: char* to string
debug2(" %s[%d]", src_phrase.back().c_str(), (uint) ptr_input[i]);
}
tgt_phrase.clear();
debug0(" target:");
for (i=0; i<tg_nbphr && buf_target_ext[i+ni*tg_nbphr]!=NULL_WORD; i++) {
tgt_phrase.push_back(tg_wlist->GetWordInfoMapped(buf_target_ext[i+ni*tg_nbphr]).word); // TODO: char* to string
debug2(" %s[%d]", tgt_phrase.back().c_str(), buf_target_ext[i+ni*tg_nbphr]);
}
#ifdef BACKWRAD_TM
logP = safelog(ptable.GetProb(tgt_phrase, src_phrase));
#else
logP = safelog(ptable.GetProb(src_phrase, tgt_phrase));
#endif
nb_probs++;
debug1(" => logP=%e\n",logP);
#else
logP=1;
#endif
}
log_sum += logP;
ptr_input += idim; // next example in bunch at input
optr += odim; // next example in bunch at output
if (fname) {
fs << ((nb_tg>0) ? logP/nb_tg : -1) << endl;
}
}
nb_ex += n;
debug2("%d: %f\n",nb_ex,exp(-log_sum/nb_ex));
} while (data_available);
printf(" %d target words in %d phrases (%d=%.2f%% uncomplete), CSTM: %d target words in %d phrases (%.2f%%)\n",
nb_tg_words, nb_ex,
nb_ex_short, 100.0*nb_ex_short/nb_ex,
nb_tg_words_slist, nb_ex_slist, 100.0*nb_ex_slist/nb_ex);
REAL px = (nb_probs>0) ? exp(-log_sum / (REAL) nb_probs) : -1;
printf(" cstm px=%.2f, ln_sum=%.2f, overall px=%.2f (%d values)\n",
(nb_tg_words_slist>0) ? exp(-log_sum_cstm / (REAL) nb_tg_words_slist) : -1, log_sum_cstm, px, nb_probs);
if (fname) fs.close();
fspt.close();
return px;
}
//**************************************************************************************
// information after finishing an epoch
void TrainerPhraseSlist1::InfoPost ()
{
printf(" - epoch finished, %d target words in %d phrases (%.2f/%.2f%% short source/target)\n",
nb_tg_words, nb_ex,
100.0*nb_ex_short_inp/nb_ex_slist, 100.0*nb_ex_short/nb_ex_slist);
printf(" CSTM: %d target words in %d phrases (%.2f%%), avrg px=%.2f\n",
nb_tg_words_slist, nb_ex_slist, 100.0*nb_ex_slist/nb_ex,
err_train);
}
//**************************************************************************************
// request one n-gram probability, usually the called will be delayed
// and processes later
//**************************************************************************************
// collect all delayed probability requests
void TrainerPhraseSlist1::ForwAndCollect(vector< vector<string> > &src_phrases, AlignReq *areq, int req_beg, int req_end, int bs, int tm_pos)
{
if (bs<=0) return;
debug3("TrainerPhraseSlist1::ForwAndCollect(): collecting outputs %d .. %d from bunch of size %d\n", req_beg, req_end, bs);
debug3("\ttarget machines %d x dim %d = total %d\n", tg_nbphr, dim_per_phrase, odim);
if (bs != (int) src_phrases.size())
ErrorN("TrainerPhraseSlist1::ForwAndCollect(): the number of source phrases (%d) does not match block length (%d)", (int) src_phrases.size(), bs);
#ifdef DEBUG
printf("bunch of %d\n",bs);
for (int b=0; b<bs; b++) {
printf("%3d:", b);
for (int ii=0; ii<idim; ii++) printf(" %.2f", buf_input[b*idim+ii]); printf("\n");
}
#endif
nb_forw++;
#ifdef CUDA
Gpu::SetConfig(mach->GetGpuConfig());
mach->SetDataIn(gpu_input);
Gpu::MemcpyAsync(gpu_input, buf_input , bs*idim*sizeof(REAL), cudaMemcpyHostToDevice);
#else
mach->SetDataIn(buf_input);
#endif
mach->Forw(bs,false);
#ifdef BLAS_CUDA
Gpu::MemcpyAsync(host_output, mach->GetDataOut(), bs*odim*sizeof(REAL), cudaMemcpyDeviceToHost);
Gpu::StreamSynchronize();
#endif
// stats
int cnt_ex_slist=0, cnt_tg_words=0, cnt_tg_words_slist=0;
for (int n=req_beg; n<=req_end; n++) {
REAL logP=0;
int b=areq[n].bs;
if ((int) areq[n].tgph.size() > tg_nbphr)
ErrorN("TrainerPhraseSlist1::ForwAndCollect(): target phrase too long (%d) for machine (%d)", (int) areq[n].tgph.size(), tg_nbphr);
#ifdef DEBUG
printf("collect b=%3d \n input:", b);
for (int ii=0; ii<idim; ii++) printf(" %f",buf_input[b*idim+ii]); printf("\n");
#endif
// map target words
debug0(" output:");
bool all_in_slist=true;
int tw;
for (tw=0; all_in_slist && tw<tg_nbphr; tw++) {
WordID outp = areq[n].tgwid[tw];
debug1(" %d",outp);
if (outp==NULL_WORD) break;
cnt_tg_words++;
buf_target_wid[tw] = tg_wlist->MapIndex(outp, "TrainerPhraseSlist1::ForwAndCollect() output");
debug1("->%d",buf_target_wid[tw]);
all_in_slist=tg_wlist->InShortList(buf_target_wid[tw]);
}
// fill up
for (; tw<tg_nbphr; tw++) {
debug0(" fill");
buf_target_wid[tw]=NULL_WORD;
}
debug1(" slist=%d\n",all_in_slist);
#ifdef BLAS_CUDA
REAL *optr=host_output + b*odim;
#else
REAL *optr=mach->GetDataOut() + b*odim;
#endif
if (!all_in_slist) {
// get proba from external phrase table
logP=ptable.GetProb(src_phrases[areq[n].bs], areq[n].tgph);
debug1(" ptable: logP=%f\n", logP);
}
else {
// get proba from CSLM
debug0(" - in slist CSLM:");
logP=0; int cnt=0;
for (int tw=0; tw<tg_nbphr; tw++) {
if (buf_target_wid[tw] == NULL_WORD) break;
debug1(" %e", optr[buf_target_wid[tw]]);
logP += safelog(optr[buf_target_wid[tw]]);
optr+=dim_per_phrase;
cnt++;
}
if (cnt==0) Error("no target phrases when collecting output");
logP /= cnt; // TODO: is this normalization correct ?
debug1(" -> log avr=%f\n",logP);
cnt_ex_slist++;
cnt_tg_words_slist += cnt;
}
// store LM proba
areq[n].hyp->AddFeature(logP,tm_pos);
} // for (ni=...)
printf(" nb of phrases: %d with %d target words, by CSTM %d (%5.2f%%), avrg length %1.2f words\n",
req_end-req_beg+1, cnt_tg_words, cnt_ex_slist, (float) 100.0* cnt_ex_slist / (req_end-req_beg+1), (float) cnt_tg_words_slist/cnt_ex_slist);
nb_ex += (req_end-req_beg+1);
nb_ex_slist += cnt_ex_slist;
nb_tg_words_slist += cnt_tg_words_slist;
nb_tg_words += cnt_tg_words;
}
void TrainerPhraseSlist1::BlockStats() {
//printf(" - %d phrase probability requests, %d=%5.2f short phrase %d forward passes (avrg of %d probas), %d=%5.2f%% predicted by CSTM\n",
//nb_ngram, nb_ex_short, 100.0*nb_ex_short/nb_ngram, nb_forw, nb_ngram/nb_forw, nb_ex_slist, 100.0*nb_ex_slist/nb_ngram);
printf(" - CSTM: %d forward passes, %d=%5.2f%% phrases were predicted by CSTM\n",
nb_forw, nb_ex_slist, 100.0 * nb_ex_slist/nb_ex);
}
| hschwenk/cslm-toolkit | TrainerPhraseSlist1.cpp | C++ | gpl-3.0 | 33,138 |
var sqlite3 = require('sqlite3').verbose();
/*Live database*/
var db = new sqlite3.Database(__dirname + '/database.db');
/*Testing database*/
module.exports.useTestDatabase = function(){
var path = __dirname + '/testDatabase.db'
db = new sqlite3.Database(__dirname + '/testDatabase.db');
}
/*Test or Live depending on caller*/
module.exports.database = function(){
return db;
};
| TantalizingThyroids/Event.ly | server/db/db.js | JavaScript | gpl-3.0 | 388 |
#!/usr/bin/env python
from __future__ import absolute_import, unicode_literals
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "_3caassurance.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| madicorp/3caassurance | manage.py | Python | gpl-3.0 | 320 |
import json
import random
import string
import logging
import requests
from collections import namedtuple
from os import path
logger = logging.getLogger()
config_file = path.join(path.dirname(path.dirname(__file__)), "config.json")
requests_timeout = 10
titles = [
"dr",
"mr",
"cheeky",
"duchess",
"duke",
"lord",
"fluffy",
"reverend",
"the right reverend",
"the right honorable",
"count",
"blind",
"daddy",
"mamma",
"howlin'",
"",
"professor",
"herr",
"frau",
"scratchy",
"admiral",
"your lord and saviour",
"madam",
"sir",
]
first_names = [
"fluffington",
"meowmeow",
"mittington",
"patrick",
"clawdia",
"paws",
"strange",
"tom",
"old tom",
"beverly",
"socks",
"sybil",
"claws",
"dusty",
"poo-foot",
"litterbox",
"socky",
"teeth",
"fangs",
"yumyums",
"super",
"keith",
"pussington",
"fido",
"alan",
"catty",
"fluffulus",
"hamcat",
]
last_names = [
"of tunatown",
"the fourth",
"the seventh",
"bumfluff",
"the minger",
"the crackhead",
"kibblesocks",
"biscuits",
"cuteington",
"bumtrousers",
"of dustbath",
"esquire",
"the shrew beheader",
"the maimer",
"the nocturnal",
"shitwiskers",
"the bastard",
"the disembowler",
"the mouse botherer",
"the shrew killer",
"the salmon shredder",
"the vomiter",
]
MailgunConfig = namedtuple("MailgunConfig", ["url", "api_key", "from_address"])
CatPicture = namedtuple("CatPicture", ["url", "reddit_url"])
def parse_config(filename):
raw = json.load(open(filename))
recipients = raw["recipients"]
assert type(recipients) == list
raw_mailgun = raw["mailgun"]
mailgun_config = MailgunConfig(
url=raw_mailgun["url"],
api_key=raw_mailgun["api-key"],
from_address=raw_mailgun["from_address"],
)
return recipients, mailgun_config
def generate_random_string(length=6):
return "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(length)
)
def generate_random_user_agent():
return "TheDailyWhiskers" + generate_random_string()
def get_cat_name():
return " ".join(
[random.choice(titles), random.choice(first_names), random.choice(last_names)]
)
def send(mailgun_config, to, html, image_name, image_content, image_content_type):
response = requests.post(
mailgun_config.url,
auth=("api", mailgun_config.api_key),
files=[("inline", (image_name, image_content, image_content_type))],
data={
"from": mailgun_config.from_address,
"to": to,
"subject": "The Daily Whiskers",
"html": html,
},
timeout=requests_timeout,
)
response.raise_for_status()
def get_cat_picture(json_child):
try:
data = json_child["data"]
link_flair_text = data["link_flair_text"]
if link_flair_text != "Cat Picture":
logger.debug("Wrong link_flair_text: %s", link_flair_text)
return None
if "preview" in data:
logger.debug("Found single preview image")
# 1 because 0 is very low res.
url = data["preview"]["images"][0]["resolutions"][1]["url"]
elif "gallery_data" in data:
logger.debug("Found preview image gallery")
first_media_id = data["gallery_data"]["items"][0]["media_id"]
# Number 3 looks like a reasonable resolution? I'm not sure how these resolutions are chosen!
url = data["media_metadata"][first_media_id]["p"][3]["u"]
else:
raise ValueError("Not sure how to extract image from this JSON")
# For a reason known only to the API designer, this is necessary
url = url.replace("&", "&")
reddit_url = "https://www.reddit.com" + data["permalink"]
return CatPicture(url=url, reddit_url=reddit_url)
except (KeyError, IndexError):
logger.exception("Failed to get cat pic from JSON, which was: \n%s", json_child)
return None
def get_cat_pictures(top_cats):
children = top_cats["data"]["children"]
# + 1 because sometimes weird posts are stickied at the top
for json_child in children[1:]:
cat_picture = get_cat_picture(json_child)
if cat_picture is not None:
yield cat_picture
def build_html(cat_name, image_file, reddit_url):
return """
<h1 style="text-align: center;">{cat_name}</h1>
<img style="display: block; margin: auto; width: 100%;" src="cid:{image_file}">
<p><small>Credit: <a href="{reddit_url}">{reddit_url}</a></small></p>
""".format(
cat_name=cat_name, image_file=image_file, reddit_url=reddit_url
).strip()
def main():
logging.basicConfig()
logger.setLevel(logging.DEBUG)
logger.info("Dailywhiskers started")
(recipients, mailgun_config) = parse_config(config_file)
logger.debug("Loaded config")
session = requests.Session()
# Without this reddit gets very throttle-y
session.headers = {"user-agent": generate_random_user_agent()}
top_cats_resp = session.get(
"https://www.reddit.com/r/cats/top.json?t=day", timeout=requests_timeout
)
top_cats_resp.raise_for_status()
for recipient, cat_picture in zip(
recipients, get_cat_pictures(top_cats_resp.json())
):
response = session.get(cat_picture.url, timeout=requests_timeout)
response.raise_for_status()
logger.debug("Processing recipient: %s", recipient)
cat_name = get_cat_name()
# This random string solves Jess's iPhone issue where new pictures clobber old ones.
cat_pic_name = "cat_pic" + generate_random_string()
logger.info(
"Sending cat pic %s with name %s to %s",
cat_picture.reddit_url,
cat_pic_name,
recipient,
)
send(
mailgun_config=mailgun_config,
to=recipient,
html=build_html(cat_name, cat_pic_name, cat_picture.reddit_url),
image_name=cat_pic_name,
image_content=response.content,
image_content_type=response.headers["Content-Type"],
)
if __name__ == "__main__":
main()
def handler(event, context):
try:
main()
except:
logger.exception("DailyWhiskers failed :(")
| SimonStJG/TheDailyWhiskers | thedailywhiskers/dailywhiskers.py | Python | gpl-3.0 | 6,491 |
package com.sample.rest.demo.springbootrest.repositories;
import com.mongodb.WriteResult;
import com.sample.rest.demo.springbootrest.models.Contact;
import com.sample.rest.demo.springbootrest.models.User;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.mongodb.morphia.query.UpdateResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
@Repository
public class ContactRepositoryImpl implements ContactRepository {
@Autowired
private Datastore datastore;
@Override
public String saveOrUpdateContact(Contact contact) {
if(null!= contact && contact.validate())
return extractObjectId(datastore.save(contact));
return null;
}
@Override
public Contact getContactById(ObjectId id){
if(null!=id)
return datastore.createQuery(Contact.class).filter("_id", id).get();
return null;
}
@Override
public Contact getContact(String firstName, String lastName) {
if(null!=firstName && null!=lastName){
Query<Contact> query = datastore.createQuery(Contact.class);
query.and(
query.criteria("details.firstName").equal(firstName),
query.criteria("details.lastName").equal(lastName)
);
return query.get();
}
return null;
}
@Override
public String updateContact(Contact contact) {
if(null!= contact && contact.validate()) {
Contact dbContact = getContactById(contact.getId());
if(null!=dbContact){
if(null!=contact.getDetails() && contact.getDetails().validate())
dbContact.setDetails(contact.getDetails());
if(null!=contact.getContactNumbers() && contact.getContactNumbers().validate())
dbContact.setContactNumbers(contact.getContactNumbers());
dbContact.setLastModifiedDate(new Date());
return extractObjectId(datastore.save(dbContact));
}
}
return null;
}
@Override
public boolean deleteContact(Contact contact) {
if(null!= contact && contact.validate()) {
Contact dbContact = getContactById(contact.getId());
if(null!=dbContact) return null != datastore.delete(dbContact);
}
return false;
}
@Override
public List<Contact> listContact(String owner) {
Query<Contact> query = datastore.createQuery(Contact.class);
if(null!=owner && 0 < owner.trim().length()) query.filter("owner", owner);
query.order("details.firstName, details.lastName");
return query.asList();
}
private String extractObjectId(Key<Contact> keyContact){
if(null!=keyContact)
return keyContact.getId().toString();
else
return null;
}
}
| borgymanotoy/samples | spring-boot/mongodb-odm-morphia-security/src/main/java/com/sample/rest/demo/springbootrest/repositories/ContactRepositoryImpl.java | Java | gpl-3.0 | 3,206 |
#ifdef HAS_PROTOCOL_HTTP
#include "audio/pcmstream.h"
#include "streaming/wsoutnetaudiostream.h"
#include "streaming/streamstypes.h"
#include "protocols/http/websocket/basewssubprotocol.h"
#include "application/baseclientapplication.h"
#include "system/eventdefine.h"
WSOutNetAudioStream::WSOutNetAudioStream (BaseProtocol *pProtocol,
StreamsManager *pStreamsManager,
string streamName)
: BaseOutNetStream(pProtocol, pStreamsManager, ST_OUT_WSNET_AUDIO, streamName),
_dataThreshold(AUDIOTHRE)
{
_soundBuffer.IgnoreAll();
}
WSOutNetAudioStream::~WSOutNetAudioStream() {
}
bool WSOutNetAudioStream::SignalPlay (double &absTimeStamp, double &length)
{
return true;
}
bool WSOutNetAudioStream::SignalPause()
{
return true;
}
bool WSOutNetAudioStream::SignalResume()
{
return true;
}
bool WSOutNetAudioStream::SignalSeek(double &absoluteTimestamp)
{
return true;
}
bool WSOutNetAudioStream::SignalStop()
{
return true;
}
bool WSOutNetAudioStream::IsCompatibleWithType(uint64_t type)
{
return true;
}
void WSOutNetAudioStream::SignalStreamCompleted()
{
}
void WSOutNetAudioStream::SignalAttachedToInStream() {
if (_pInStream) {
_dataThreshold=reinterpret_cast<BaseAudioStream*>(_pInStream)->GetAudioDataTh();
}
uint16_t event=EVT_OUT_AREC_CONNECTED;
if (_pProtocol->GetType()==PT_INBOUND_HTTP_WSCONNECTION) {
event=EVT_IN_AREC_CONNECTED;
}
const_cast<BaseClientApplication*>
(_pProtocol->GetApplication())->OnNotifyEvent(CLOUD_MSG_EVENT,
event,
0);
}
void WSOutNetAudioStream::SignalDetachedFromInStream() {
uint16_t event=EVT_OUT_AREC_DISCONNECTED;
if (_pProtocol->GetType()==PT_INBOUND_HTTP_WSCONNECTION) {
event=EVT_IN_AREC_DISCONNECTED;
}
const_cast<BaseClientApplication*>
(_pProtocol->GetApplication())->OnNotifyEvent(CLOUD_MSG_EVENT,
event,
0);
}
bool WSOutNetAudioStream::FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double absoluteTimestamp, bool isAudio) {
if (IsEnqueueForDelete())
return true;
_soundBuffer.ReadFromBuffer(pData, dataLength);
uint32_t availcount= GETAVAILABLEBYTESCOUNT(_soundBuffer);
if (!_pInStream)
return false;
if (availcount>_dataThreshold ) {
IOBuffer header;
if (_pProtocol) {
BaseWSSubProtocol* pWSProtocol=reinterpret_cast<BaseWSSubProtocol*>(_pProtocol);
BaseAudioStream* pAudioStream = reinterpret_cast<BaseAudioStream*>(_pInStream);
pAudioStream->GetHeader(header, availcount);
pWSProtocol->EnqueueForWSOutbound (GETIBPOINTER(header), GETAVAILABLEBYTESCOUNT(header), false, WS_OPCODE_BINARY_FRAME);
pWSProtocol->EnqueueForWSOutbound (GETIBPOINTER(_soundBuffer), availcount , true, WS_OPCODE_CONTINUATION);
_soundBuffer.Ignore(availcount);
}
}
return true;
}
bool WSOutNetAudioStream::FeedMSGData(uint8_t *pData, uint32_t dataLength)
{
if (IsEnqueueForDelete()) {
DEBUG ("Is EnququeForDelete return");
return false;
}
if (_pProtocol) {
return reinterpret_cast<BaseWSSubProtocol*>
(_pProtocol)->EnqueueForWSOutbound (pData, dataLength, true, WS_OPCODE_TEXT_FRAME);
}
return false;
}
#endif
| OpenQCam/qcam | trunk/sources/thelib/src/streaming/wsoutnetaudiostream.cpp | C++ | gpl-3.0 | 3,366 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include "base/base64.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "net/base/parse_number.h"
#include "net/http/http_security_headers.h"
#include "net/http/http_util.h"
#include "url/gurl.h"
namespace net {
namespace {
enum MaxAgeParsing { REQUIRE_MAX_AGE, DO_NOT_REQUIRE_MAX_AGE };
// MaxAgeToLimitedInt converts a string representation of a "whole number" of
// seconds into a uint32_t. The string may contain an arbitrarily large number,
// which will be clipped to a supplied limit and which is guaranteed to fit
// within a 32-bit unsigned integer. False is returned on any parse error.
bool MaxAgeToLimitedInt(std::string::const_iterator begin,
std::string::const_iterator end,
uint32_t limit,
uint32_t* result) {
const base::StringPiece s(begin, end);
ParseIntError error;
if (!ParseUint32(s, result, &error)) {
if (error == ParseIntError::FAILED_OVERFLOW) {
*result = limit;
} else {
return false;
}
}
if (*result > limit)
*result = limit;
return true;
}
// Returns true iff there is an item in |pins| which is not present in
// |from_cert_chain|. Such an SPKI hash is called a "backup pin".
bool IsBackupPinPresent(const HashValueVector& pins,
const HashValueVector& from_cert_chain) {
for (HashValueVector::const_iterator i = pins.begin(); i != pins.end();
++i) {
HashValueVector::const_iterator j =
std::find_if(from_cert_chain.begin(), from_cert_chain.end(),
HashValuesEqual(*i));
if (j == from_cert_chain.end())
return true;
}
return false;
}
// Returns true if the intersection of |a| and |b| is not empty. If either
// |a| or |b| is empty, returns false.
bool HashesIntersect(const HashValueVector& a,
const HashValueVector& b) {
for (HashValueVector::const_iterator i = a.begin(); i != a.end(); ++i) {
HashValueVector::const_iterator j =
std::find_if(b.begin(), b.end(), HashValuesEqual(*i));
if (j != b.end())
return true;
}
return false;
}
// Returns true iff |pins| contains both a live and a backup pin. A live pin
// is a pin whose SPKI is present in the certificate chain in |ssl_info|. A
// backup pin is a pin intended for disaster recovery, not day-to-day use, and
// thus must be absent from the certificate chain. The Public-Key-Pins header
// specification requires both.
bool IsPinListValid(const HashValueVector& pins,
const HashValueVector& from_cert_chain) {
// Fast fail: 1 live + 1 backup = at least 2 pins. (Check for actual
// liveness and backupness below.)
if (pins.size() < 2)
return false;
if (from_cert_chain.empty())
return false;
return IsBackupPinPresent(pins, from_cert_chain) &&
HashesIntersect(pins, from_cert_chain);
}
bool ParseAndAppendPin(std::string::const_iterator begin,
std::string::const_iterator end,
HashValueTag tag,
HashValueVector* hashes) {
const base::StringPiece value(begin, end);
if (value.empty())
return false;
std::string decoded;
if (!base::Base64Decode(value, &decoded))
return false;
HashValue hash(tag);
if (decoded.size() != hash.size())
return false;
memcpy(hash.data(), decoded.data(), hash.size());
hashes->push_back(hash);
return true;
}
bool ParseHPKPHeaderImpl(const std::string& value,
MaxAgeParsing max_age_status,
base::TimeDelta* max_age,
bool* include_subdomains,
HashValueVector* hashes,
GURL* report_uri) {
bool parsed_max_age = false;
bool include_subdomains_candidate = false;
uint32_t max_age_candidate = 0;
GURL parsed_report_uri;
HashValueVector pins;
bool require_max_age = max_age_status == REQUIRE_MAX_AGE;
HttpUtil::NameValuePairsIterator name_value_pairs(
value.begin(), value.end(), ';',
HttpUtil::NameValuePairsIterator::VALUES_OPTIONAL);
while (name_value_pairs.GetNext()) {
if (base::LowerCaseEqualsASCII(
base::StringPiece(name_value_pairs.name_begin(),
name_value_pairs.name_end()),
"max-age")) {
if (!MaxAgeToLimitedInt(name_value_pairs.value_begin(),
name_value_pairs.value_end(), kMaxHPKPAgeSecs,
&max_age_candidate)) {
return false;
}
parsed_max_age = true;
} else if (base::LowerCaseEqualsASCII(
base::StringPiece(name_value_pairs.name_begin(),
name_value_pairs.name_end()),
"pin-sha256")) {
// Pins are always quoted.
if (!name_value_pairs.value_is_quoted() ||
!ParseAndAppendPin(name_value_pairs.value_begin(),
name_value_pairs.value_end(), HASH_VALUE_SHA256,
&pins)) {
return false;
}
} else if (base::LowerCaseEqualsASCII(
base::StringPiece(name_value_pairs.name_begin(),
name_value_pairs.name_end()),
"includesubdomains")) {
include_subdomains_candidate = true;
} else if (base::LowerCaseEqualsASCII(
base::StringPiece(name_value_pairs.name_begin(),
name_value_pairs.name_end()),
"report-uri")) {
// report-uris are always quoted.
if (!name_value_pairs.value_is_quoted())
return false;
parsed_report_uri = GURL(name_value_pairs.value());
if (parsed_report_uri.is_empty() || !parsed_report_uri.is_valid())
return false;
} else {
// Silently ignore unknown directives for forward compatibility.
}
}
if (!name_value_pairs.valid())
return false;
if (!parsed_max_age && require_max_age)
return false;
*max_age = base::TimeDelta::FromSeconds(max_age_candidate);
*include_subdomains = include_subdomains_candidate;
hashes->swap(pins);
*report_uri = parsed_report_uri;
return true;
}
} // namespace
// Parse the Strict-Transport-Security header, as currently defined in
// http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14:
//
// Strict-Transport-Security = "Strict-Transport-Security" ":"
// [ directive ] *( ";" [ directive ] )
//
// directive = directive-name [ "=" directive-value ]
// directive-name = token
// directive-value = token | quoted-string
//
// 1. The order of appearance of directives is not significant.
//
// 2. All directives MUST appear only once in an STS header field.
// Directives are either optional or required, as stipulated in
// their definitions.
//
// 3. Directive names are case-insensitive.
//
// 4. UAs MUST ignore any STS header fields containing directives, or
// other header field value data, that does not conform to the
// syntax defined in this specification.
//
// 5. If an STS header field contains directive(s) not recognized by
// the UA, the UA MUST ignore the unrecognized directives and if the
// STS header field otherwise satisfies the above requirements (1
// through 4), the UA MUST process the recognized directives.
bool ParseHSTSHeader(const std::string& value,
base::TimeDelta* max_age,
bool* include_subdomains) {
uint32_t max_age_candidate = 0;
bool include_subdomains_candidate = false;
// We must see max-age exactly once.
int max_age_observed = 0;
// We must see includeSubdomains exactly 0 or 1 times.
int include_subdomains_observed = 0;
enum ParserState {
START,
AFTER_MAX_AGE_LABEL,
AFTER_MAX_AGE_EQUALS,
AFTER_MAX_AGE,
AFTER_INCLUDE_SUBDOMAINS,
AFTER_UNKNOWN_LABEL,
DIRECTIVE_END
} state = START;
base::StringTokenizer tokenizer(value, " \t=;");
tokenizer.set_options(base::StringTokenizer::RETURN_DELIMS);
tokenizer.set_quote_chars("\"");
std::string unquoted;
while (tokenizer.GetNext()) {
DCHECK(!tokenizer.token_is_delim() || tokenizer.token().length() == 1);
switch (state) {
case START:
case DIRECTIVE_END:
if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
continue;
if (base::LowerCaseEqualsASCII(tokenizer.token(), "max-age")) {
state = AFTER_MAX_AGE_LABEL;
max_age_observed++;
} else if (base::LowerCaseEqualsASCII(tokenizer.token(),
"includesubdomains")) {
state = AFTER_INCLUDE_SUBDOMAINS;
include_subdomains_observed++;
include_subdomains_candidate = true;
} else {
state = AFTER_UNKNOWN_LABEL;
}
break;
case AFTER_MAX_AGE_LABEL:
if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
continue;
if (*tokenizer.token_begin() != '=')
return false;
DCHECK_EQ(tokenizer.token().length(), 1U);
state = AFTER_MAX_AGE_EQUALS;
break;
case AFTER_MAX_AGE_EQUALS:
if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
continue;
unquoted = HttpUtil::Unquote(tokenizer.token());
if (!MaxAgeToLimitedInt(unquoted.begin(), unquoted.end(),
kMaxHSTSAgeSecs, &max_age_candidate))
return false;
state = AFTER_MAX_AGE;
break;
case AFTER_MAX_AGE:
case AFTER_INCLUDE_SUBDOMAINS:
if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
continue;
else if (*tokenizer.token_begin() == ';')
state = DIRECTIVE_END;
else
return false;
break;
case AFTER_UNKNOWN_LABEL:
// Consume and ignore the post-label contents (if any).
if (*tokenizer.token_begin() != ';')
continue;
state = DIRECTIVE_END;
break;
}
}
// We've consumed all the input. Let's see what state we ended up in.
if (max_age_observed != 1 ||
(include_subdomains_observed != 0 && include_subdomains_observed != 1)) {
return false;
}
switch (state) {
case DIRECTIVE_END:
case AFTER_MAX_AGE:
case AFTER_INCLUDE_SUBDOMAINS:
case AFTER_UNKNOWN_LABEL:
*max_age = base::TimeDelta::FromSeconds(max_age_candidate);
*include_subdomains = include_subdomains_candidate;
return true;
case START:
case AFTER_MAX_AGE_LABEL:
case AFTER_MAX_AGE_EQUALS:
return false;
default:
NOTREACHED();
return false;
}
}
// "Public-Key-Pins" ":"
// "max-age" "=" delta-seconds ";"
// "pin-" algo "=" base64 [ ";" ... ]
// [ ";" "includeSubdomains" ]
// [ ";" "report-uri" "=" uri-reference ]
bool ParseHPKPHeader(const std::string& value,
const HashValueVector& chain_hashes,
base::TimeDelta* max_age,
bool* include_subdomains,
HashValueVector* hashes,
GURL* report_uri) {
base::TimeDelta candidate_max_age;
bool candidate_include_subdomains;
HashValueVector candidate_hashes;
GURL candidate_report_uri;
if (!ParseHPKPHeaderImpl(value, REQUIRE_MAX_AGE, &candidate_max_age,
&candidate_include_subdomains, &candidate_hashes,
&candidate_report_uri)) {
return false;
}
if (!IsPinListValid(candidate_hashes, chain_hashes))
return false;
*max_age = candidate_max_age;
*include_subdomains = candidate_include_subdomains;
hashes->swap(candidate_hashes);
*report_uri = candidate_report_uri;
return true;
}
// "Public-Key-Pins-Report-Only" ":"
// [ "max-age" "=" delta-seconds ";" ]
// "pin-" algo "=" base64 [ ";" ... ]
// [ ";" "includeSubdomains" ]
// [ ";" "report-uri" "=" uri-reference ]
bool ParseHPKPReportOnlyHeader(const std::string& value,
bool* include_subdomains,
HashValueVector* hashes,
GURL* report_uri) {
// max-age is irrelevant for Report-Only headers.
base::TimeDelta unused_max_age;
return ParseHPKPHeaderImpl(value, DO_NOT_REQUIRE_MAX_AGE, &unused_max_age,
include_subdomains, hashes, report_uri);
}
} // namespace net
| golden1232004/webrtc_new | chromium/src/net/http/http_security_headers.cc | C++ | gpl-3.0 | 12,773 |
<?php
/*
OpenTOMS - Open Trade Order Management System
Copyright (C) 2012 JOHN TAM, LPR CONSULTING LLP
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/>.
*/
class Account extends AppModel {
var $name = 'Account';
function getNamed($name) {
$result = $this->find('first', array('fields'=>array('Account.id'),'conditions'=>array('account_name'=>$name)));
if (empty($result)) {
return 0;
}
else {
return $result['Account']['id'];
}
}
//given a posting value to a specific account, this function returns the credit debit journal entry
function debitcredit($id, $value) {
$type = $this->read('account_type', $id);
$type = $type['Account']['account_type'];
if (($type == 'Assets') || ($type == 'Expenses')) {
if ($value >= 0) {
return (array($value, 0));
}
else {
return (array(0, abs($value)));
}
}
else if (($type == 'Owners Equity') || ($type == 'Income')) {
if ($value >= 0) {
return (array(0, $value));
}
else {
return (array(abs($value), 0));
}
}
else {
return null;
}
}
}
?>
| johntam/OpenTOMS | app/models/account.php | PHP | gpl-3.0 | 1,706 |
#include "meta_data.h"
#include <oak/oak.h>
namespace ng
{
void marks_t::replace (buffer_t* buffer, size_t from, size_t to, std::string const& str)
{
for(auto& m : _marks)
{
tree_t::iterator it = m.second.upper_bound(to);
std::string preserveMark = it != m.second.begin() && from < (--it)->first && it->first <= to ? it->second : NULL_STR;
m.second.replace(from, to, str.size(), false);
if(preserveMark != NULL_STR)
m.second.set(from + str.size(), preserveMark);
}
}
void marks_t::set (size_t index, std::string const& markType)
{
_marks[markType].set(index, markType);
}
void marks_t::remove (size_t index, std::string const& markType)
{
_marks[markType].remove(index);
}
void marks_t::remove_all (std::string const& markType)
{
_marks.erase(markType);
}
std::string marks_t::get (size_t index, std::string const& markType) const
{
ASSERT(_marks.find(markType) != _marks.end());
ASSERT(_marks.find(markType)->second.find(index) != _marks.find(markType)->second.end());
return _marks.find(markType)->second.find(index)->second;
}
std::pair<size_t, std::string> marks_t::next (size_t index, std::string const& markType) const
{
std::map<std::string, tree_t>::const_iterator m = _marks.find(markType);
if(m == _marks.end())
return std::pair<size_t, std::string>(0, NULL_STR);
if(m->second.size() == 0)
return std::pair<size_t, std::string>(0, NULL_STR);
else if(m->second.size() == 1)
return *m->second.begin();
tree_t::iterator it = m->second.upper_bound(index);
return *(it == m->second.end() ? m->second.begin() : it);
}
std::pair<size_t, std::string> marks_t::prev (size_t index, std::string const& markType) const
{
std::map< std::string, tree_t>::const_iterator m = _marks.find(markType);
if(m == _marks.end())
return std::pair<size_t, std::string>(0, NULL_STR);
if(m->second.size() == 0)
return std::pair<size_t, std::string>(0, NULL_STR);
else if(m->second.size() == 1)
return *m->second.begin();
tree_t::iterator it = m->second.lower_bound(index);
return *(--(it == m->second.begin() ? m->second.end() : it));
}
std::map<size_t, std::string> marks_t::get_range (size_t from, size_t to, std::string const& markType) const
{
ASSERT_LE(from, to);
std::map<size_t, std::string> res;
if(markType == NULL_STR)
{
for(auto const& m : _marks)
{
foreach(it, m.second.lower_bound(from), m.second.upper_bound(to))
res[it->first - from] = it->second;
}
}
else
{
std::map< std::string, tree_t>::const_iterator m = _marks.find(markType);
if(m != _marks.end())
{
foreach(it, m->second.lower_bound(from), m->second.upper_bound(to))
res[it->first - from] = it->second;
}
}
return res;
}
} /* ng */
| xuvw/textmate | Frameworks/buffer/src/marks.cc | C++ | gpl-3.0 | 2,758 |
import { Component, Directive, ElementRef, EventEmitter, forwardRef, HostListener, Input, NgZone, Renderer, Inject, Optional, Output } from '@angular/core';
import { Content } from '../content/content';
import { CSS, zoneRafFrames } from '../../util/dom';
import { Item } from './item';
import { ItemReorderGesture } from '../item/item-reorder-gesture';
import { isTrueProperty } from '../../util/util';
export class ItemReorder {
constructor(elementRef, _rendered, _zone, _content) {
this._rendered = _rendered;
this._zone = _zone;
this._content = _content;
this._enableReorder = false;
this._visibleReorder = false;
this._lastToIndex = -1;
this.ionItemReorder = new EventEmitter();
this._element = elementRef.nativeElement;
}
ngOnDestroy() {
this._element = null;
this._reorderGesture && this._reorderGesture.destroy();
}
get reorder() {
return this._enableReorder;
}
set reorder(val) {
let enabled = isTrueProperty(val);
if (!enabled && this._reorderGesture) {
this._reorderGesture.destroy();
this._reorderGesture = null;
this._visibleReorder = false;
setTimeout(() => this._enableReorder = false, 400);
}
else if (enabled && !this._reorderGesture) {
// console.debug('enableReorderItems');
this._reorderGesture = new ItemReorderGesture(this);
this._enableReorder = true;
zoneRafFrames(2, () => this._visibleReorder = true);
}
}
reorderPrepare() {
let ele = this._element;
let children = ele.children;
for (let i = 0, ilen = children.length; i < ilen; i++) {
var child = children[i];
child.$ionIndex = i;
child.$ionReorderList = ele;
}
}
reorderStart() {
this.setElementClass('reorder-list-active', true);
}
reorderEmit(fromIndex, toIndex) {
this.reorderReset();
if (fromIndex !== toIndex) {
this._zone.run(() => {
this.ionItemReorder.emit({
from: fromIndex,
to: toIndex,
});
});
}
}
scrollContent(scroll) {
let scrollTop = this._content.getScrollTop() + scroll;
if (scroll !== 0) {
this._content.scrollTo(0, scrollTop, 0);
}
return scrollTop;
}
reorderReset() {
let children = this._element.children;
let len = children.length;
this.setElementClass('reorder-list-active', false);
let transform = CSS.transform;
for (let i = 0; i < len; i++) {
children[i].style[transform] = '';
}
this._lastToIndex = -1;
}
reorderMove(fromIndex, toIndex, itemHeight) {
if (this._lastToIndex === -1) {
this._lastToIndex = fromIndex;
}
let lastToIndex = this._lastToIndex;
this._lastToIndex = toIndex;
let children = this._element.children;
let transform = CSS.transform;
if (toIndex >= lastToIndex) {
for (var i = lastToIndex; i <= toIndex; i++) {
if (i !== fromIndex) {
children[i].style[transform] = (i > fromIndex)
? `translateY(${-itemHeight}px)` : '';
}
}
}
if (toIndex <= lastToIndex) {
for (var i = toIndex; i <= lastToIndex; i++) {
if (i !== fromIndex) {
children[i].style[transform] = (i < fromIndex)
? `translateY(${itemHeight}px)` : '';
}
}
}
}
setElementClass(classname, add) {
this._rendered.setElementClass(this._element, classname, add);
}
getNativeElement() {
return this._element;
}
}
ItemReorder.decorators = [
{ type: Directive, args: [{
selector: 'ion-list[reorder],ion-item-group[reorder]',
host: {
'[class.reorder-enabled]': '_enableReorder',
'[class.reorder-visible]': '_visibleReorder',
}
},] },
];
ItemReorder.ctorParameters = [
{ type: ElementRef, },
{ type: Renderer, },
{ type: NgZone, },
{ type: Content, decorators: [{ type: Optional },] },
];
ItemReorder.propDecorators = {
'ionItemReorder': [{ type: Output },],
'reorder': [{ type: Input },],
};
export class Reorder {
constructor(item, elementRef) {
this.item = item;
this.elementRef = elementRef;
elementRef.nativeElement['$ionComponent'] = this;
}
getReorderNode() {
let node = this.item.getNativeElement();
return findReorderItem(node, null);
}
onClick(ev) {
ev.preventDefault();
ev.stopPropagation();
}
}
Reorder.decorators = [
{ type: Component, args: [{
selector: 'ion-reorder',
template: `<ion-icon name="reorder"></ion-icon>`
},] },
];
Reorder.ctorParameters = [
{ type: ItemReorder, decorators: [{ type: Inject, args: [forwardRef(() => Item),] },] },
{ type: ElementRef, },
];
Reorder.propDecorators = {
'onClick': [{ type: HostListener, args: ['click', ['$event'],] },],
};
export function findReorderItem(node, listNode) {
let nested = 0;
while (node && nested < 4) {
if (indexForItem(node) !== undefined) {
if (listNode && node.parentNode !== listNode) {
return null;
}
return node;
}
node = node.parentNode;
nested++;
}
return null;
}
export function indexForItem(element) {
return element['$ionIndex'];
}
export function reorderListForItem(element) {
return element['$ionReorderList'];
}
| shdevops/JAF-Dice-Roller | node_modules/ionic-angular/es2015/components/item/item-reorder.js | JavaScript | gpl-3.0 | 5,883 |
from unittest import TestCase, main
from requests import HTTPError, Response
from mock import patch
from ntfy.backends.notifico import notify
class TestNotifico(TestCase):
def setUp(self):
self.webhook = 'https://n.tkte.ch/h/1234/testing_webhook'
@patch('requests.get')
def test_basic(self, mock_get):
resp = Response()
resp.status_code = 200
mock_get.return_value = resp
notify('title', 'message', webhook=self.webhook)
mock_get.assert_called_once_with(
self.webhook, params={'payload': 'title\nmessage'})
@patch('requests.get')
def test_none_webhook(self, mock_get):
notify('title', 'message', webhook=None)
mock_get.assert_not_called()
@patch('requests.get')
def test_exception(self, mock_get):
resp = Response()
resp.status_code = 400
mock_get.return_value = resp
with self.assertRaises(HTTPError):
notify('title', 'message', webhook=self.webhook)
mock_get.assert_called_once_with(
self.webhook, params={'payload': 'title\nmessage'})
if __name__ == '__main__':
main()
| dschep/ntfy | tests/test_notifico.py | Python | gpl-3.0 | 1,153 |
/**
* This module removes the need to know which implementation of has we are using.
* @module
* @todo Make a decision and remove this!
*/
define(["lib/dojo/has"], /** @param {Object?} [has] @ignore */function(has) {
"use strict";
var global = window;
return global.has || has;
});
| Joshua-Barclay/wcomponents | wcomponents-theme/src/main/js/wc/has.js | JavaScript | gpl-3.0 | 289 |
cloudStreetMarketApp.factory("indicesGraphFactory", function (httpAuth) {
return {
getGraph: function (index) {
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',"/api/charts/indices/"+index+".png",true);
httpAuth.setHeaders(xmlHTTP);
// Must include this line - specifies the response type we want
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e){
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
if($("#homeChart")[0]){
$("#homeChart")[0].src = "data:image/png;base64,"+btoa(raw);
}
};
xmlHTTP.send();
},
getIndices: function (market) {
return httpAuth.get("/api/indices.json?size=6");
}
}
});
cloudStreetMarketApp.controller('homeFinancialGraphController', function ($scope, indicesGraphFactory){
$scope.init = function () {
var indicesPromise = indicesGraphFactory.getIndices($scope.preferedMarket);
indicesPromise.success(function(dataIndices, status, headers, config) {
$scope.indicesForGraph = dataIndices.content;
if($scope.indicesForGraph){
indicesGraphFactory.getGraph($scope.currentIndex);
}
})
$('.form-control').on('change', function (){
$scope.currentIndex = this.value;
indicesGraphFactory.getGraph($scope.currentIndex);
});
}
$scope.preferedMarket="EUROPE";
$scope.currentIndex="^GDAXI";
$scope.indices = null;
$scope.init();
});
| alex-bretet/cloudstreetmarket.com | cloudstreetmarket-parent/cloudstreetmarket-webapp/src/main/webapp/js/home/home_financial_graph.js | JavaScript | gpl-3.0 | 1,575 |
namespace ValentinesProject
{
partial class MainMenu
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainMenu));
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Gill Sans Ultra Bold", 12F);
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(106, 257);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(123, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Start Story";
this.label1.Click += new System.EventHandler(this.label1_Click);
this.label1.MouseLeave += new System.EventHandler(this.label1_MouseLeave);
this.label1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.label1_MouseMove);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Gill Sans Ultra Bold", 12F);
this.label3.ForeColor = System.Drawing.Color.White;
this.label3.Location = new System.Drawing.Point(138, 290);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(52, 23);
this.label3.TabIndex = 2;
this.label3.Text = "Quit";
this.label3.Click += new System.EventHandler(this.label3_Click);
this.label3.MouseLeave += new System.EventHandler(this.label3_MouseLeave);
this.label3.MouseMove += new System.Windows.Forms.MouseEventHandler(this.label3_MouseMove);
//
// pictureBox2
//
this.pictureBox2.Image = global::ValentinesProject.Properties.Resources.logo;
this.pictureBox2.Location = new System.Drawing.Point(75, 31);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(175, 175);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox2.TabIndex = 4;
this.pictureBox2.TabStop = false;
//
// MainMenu
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.ClientSize = new System.Drawing.Size(336, 356);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainMenu";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Object-Oriented Romancing";
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox pictureBox2;
}
} | RiverOfZabi/OOR | ValentinesProject/MainMenu.Designer.cs | C# | gpl-3.0 | 4,601 |
<?php
/**
* File :: Command.php
*
* Processeur CLI pour le moteur SYSLang.
*
* @author Nicolas DUPRE with the contribution of marvin255
* @release 18/10/2017
* @version 2.0.0-beta1
* @package Index
*
*/
namespace SYSLang;
use Exception;
use InvalidArgumentException;
/**
* Class for cli command.
*/
class Command
{
/**
* Liste des différentes options utilisée dans la classe Command.
*/
const OPTIONS = [
'colors' => [
'color_err' => '196',
'color_in' => '220',
'color_suc' => '76',
'color_war' => '208',
'color_txt' => '221',
'color_kwd' => '39'
],
'separator' => ',',
'shortopt' => "h",
"longopt" => [
"add-languages:",
"complete",
"default",
"deploy",
"directory:",
"dir:",
"export",
"export-dir:",
"finalize",
"from:",
"help",
"import",
"import-dir:",
"install",
"preserve-files",
"remove-languages:",
"remove-langs:",
"set-default-lang:",
"silent",
]
];
/**
* @var string $workdir Dossier de travail
*/
protected $workdir = null;
/**
* @var string $cmdName Nom de la commande
*/
protected $cmdName = null;
/**
* @var array $argv
*/
protected $argv = null;
/**
* @var bool|resource $psdtout Pointeur vers la ressource de sortie standard.
*/
protected $psdtout = STDOUT;
/**
* @var bool|resource $pstderr Pointeur vers la ressource de sortie des erreurs.
*/
protected $pstderr = STDERR;
/**
* @var bool $noDie Flag pour ne pas jouer les evenements die.
*/
protected $noDie = false;
/**
* Constructor function.
*
* @param string $workdir Path to working directory.
* @param array $argv Array of command line arguments.
*
* @throws \InvalidArgumentException
*/
public function __construct($workdir, array $argv, $cmdName)
{
$workdir = trim($workdir);
if (empty($workdir)) {
throw new InvalidArgumentException("workdir parameter in constructor can't be empty.");
}
if (!is_dir($workdir)) {
throw new InvalidArgumentException("workdir `{$workdir}` doesn't exist.");
}
$this->workdir = $workdir;
$this->argv = $argv;
$this->cmdName = $cmdName;
}
/**
* Execution du script.
*/
public function run()
{
$options = $this->argv;
$showHelp = true;
// Création du compilateur
$directory = @($options["dir"]) ?: (@$options["directory"]) ?: $this->workdir;
$compiler = new Core($directory);
// Afficher l'aide si demandé et s'arrêté la$
if (
array_key_exists("h", $options)
|| array_key_exists("help", $options)
) {
$this->help();
return true;
}
// Processus d'installation
if (array_key_exists("install", $options)) {
if (!$compiler->isInstalled()) {
$compiler->install();
$this->stdout('Installation effectuée avec succès dans %s', [ $directory]);
} else {
$this->stderr("Le système de langue est déjà installé dans %s", [$directory], 0);
}
$showHelp = false;
}
// Processus d'enregistrement d'une langue au registre
if (array_key_exists("add-languages", $options)) {
$languages = explode(self::OPTIONS['separator'], $options["add-languages"]);
$languages = array_map(function($el){
return trim($el);
}, $languages);
try {
call_user_func_array(array($compiler, 'addLanguages'), $languages);
// Notification après coup
array_map(function($el){
$this->stdout("Enregistrement de langue %s effectué avec succès.", [$el]);
}, $languages);
if (array_key_exists("default", $options)) {
list($code, $name) = explode(":", $languages[0]);
$compiler->setDefaultLanguage($code);
$this->stdout("La langue par défaut est définie à %s.", [$languages[0]]);
}
} catch (\Exception $e) {
$this->stderr($e->getMessage());
return false;
}
$showHelp = false;
}
// Processus de suppression de langue du registre
if (
array_key_exists("remove-languages", $options)
|| array_key_exists("remove-langs", $options)
) {
// Options à valeur obligatoire, null ne doit jamais se produire.
$languages = @($options["remove-languages"]) ?: @($options["remove-langs"]) ?: null;
$languages = explode(self::OPTIONS['separator'], $languages);
$languages = array_map(function($el) {
return trim($el);
}, $languages);
try {
call_user_func_array([$compiler, "removeLanguages"], array_merge([true], $languages));
// Notification après coup
array_map(function($el){
$this->stdout("Suppression de langue %s effectué avec succès.", [$el]);
}, $languages);
} catch (Exception $e) {
$this->stderr($e->getMessage());
return false;
}
$showHelp = false;
}
// Configuration du pack de langue par défaut
if (array_key_exists("set-default-lang", $options)) {
try {
$compiler->setDefaultLanguage($options["set-default-lang"]);
$this->stdout("La langue par défaut est définie à %s.", [$options["set-default-lang"]]);
} catch (Exception $e) {
$this->stderr($e->getMessage());
return false;
}
$showHelp = false;
}
// Processus de déploiement
if (array_key_exists("deploy", $options)) {
# Si l'option "from" est fournie, alors définir la langue de référence
if (array_key_exists("from", $options)) {
try {
$compiler->setRefLanguage($options["from"]);
} catch (Exception $e) {
$this->stderr($e->getMessage());
return false;
}
}
# Déploiement
try {
$compiler->deploy();
$refLanguage = $compiler->getRefLanguage();
$this->stdout("Le déploiment des clés à bien été effectué avec " .
"succès depuis la langue de référence %s", [$refLanguage]);
} catch (Exception $e) {
$this->stderr($e->getMessage());
return false;
}
$showHelp = false;
}
// Processus d'exportation
if (array_key_exists("export", $options)) {
try {
// Si le dossier cible est défini.
if (array_key_exists("export-dir", $options)) {
$compiler->setExportDirectory($options["export-dir"]);
}
// Si l'option compléte est préssnte, alors faire un export complet.
$complete = (array_key_exists("complete", $options)) ?: false;
// Exportation
$compiler->export($complete);
// Affichage de la bonne exécution.
$args = [];
$scomplete = "";
if ($complete) {
$scomplete = self::OPTIONS["colors"]["color_suc"] . ">%s ";
$args[] = "compléte";
}
//$args[] = $compiler->getExportDirPath;
$message = "Exportation ${scomplete}effectuée avec succès";// dans %s
$this->stdout("$message.", $args);
} catch (Exception $e) {
$this->stderr($e->getMessage());
return false;
}
$showHelp = false;
}
// Processus d'importation
if (array_key_exists("import", $options)) {
try {
// Si le dossier source est défini.
if (array_key_exists("import-dir", $options)) {
$compiler->setImportDirectory($options["import-dir"]);
}
$finalize = (array_key_exists("finalize", $options)) ?: false;
$preserve = (array_key_exists("preserve-files", $options)) ?: false;
// Importation
$compiler->import($finalize, $preserve);
// Affichage de la bonne exécution.
$args = [];
$sfinalize = "";
$spreserve = "";
if ($finalize) {
$sfinalize = "avec " . self::OPTIONS["colors"]["color_suc"] . ">%s ";
$args[] = "finalisation";
}
if ($preserve) {
$spreserve = "avec " . self::OPTIONS["colors"]["color_suc"] . ">%s ";
$args[] = "préservation";
if ($finalize) $spreserve = "et $spreserve";
}
//$args[] = $compiler->getImportDirPath;
$message = "Importation ${sfinalize}${spreserve}effectuée avec succès";// dans %s
$this->stdout("$message.", $args);
} catch (Exception $e) {
$message = preg_replace("/'(.+)'/", "'%s'", $e->getMessage());
preg_match("/'(.+)'/", $e->getMessage(), $matches);
$this->stderr($message, [$matches[1]]);
return false;
}
$showHelp = false;
}
// Si rien ne s'est passé, alors afficher l'aide par défaut
if ($showHelp) {
$this->help();
}
}
/**
* Affiche le manuel d'aide.
*
* @param int $level
*
* @return void
*/
protected function help($level = 0)
{
$separator = self::OPTIONS['separator'];
$name = $this->cmdName;
$man = <<<HELP
Usage : $name [OPTIONS]
Permet la maintenance de l'instalaltion SYSLang en ligne de commande.
0. Options transverses :
--dir, --directory Spécifie l'emplacement de travail.
-h, --help Affiche la présente aide.
--silent Masque les messages d'informations.
--preserve-files Concerver les fichiers dans les cas suivants :
- Suppression d'une langue du registre.
- Importation avec finalisaation.
1. Options d'installation :
--install Installe le fichier de configuration languages.xml
dans le dossier de travail défini.
Defaut : ./
2. Options de configurations :
--add-languages Ajoute la/les langue(s) spécifiée(s) au registre.
Format : xx-XX:Name
Séparateur : virgule ($separator)
--default Fait en sorte que la langue en cours d'ajout
devienne également la langue par defaut.
Si plusieurs valeur, alors c'est la première qui est
retenue.
--remove-languages Supprime la/les langue(s) spécifiée(s) du registre
--remove-langs et supprime les fichiers associés.
Format : xx-XX
Séparateur : virgule ($separator)
--set-default-lang Rend la langue spécifiée par défaut.
Format : xx-XX
3. Options de maintenance :
--deploy Applique les modifications de la langue de référence
(default) a tous les autres langues enregistrées.
--from xx-XX permet d'explicitement dire quelle est
la langue de référence.
--export Procéde à l'exportation des donnés vers des
fichiers .ini .
--export-dir Spécifie le dossier cible de l'exportation.
--complete Extrait l'intégralité des valeur au lieu
de celle ayant besoin d'être traduite.
--import Procéde à l'importation des donnés depuis les
fichiers .ini .
--import-dir Spécifie le dossier source pour l'importation.
--finalize Finalise l'importation qui permettra de faire une
exportation différentielle par la suite.
HELP;
fwrite($this->psdtout, $man . PHP_EOL);
if ($level) die($level);
}
/**
* Met en évidence les valeurs utilisateur dans les messages
*
* @param string $message Message à analyser
*
* @return string $message Message traité
*/
protected function highlight($message)
{
$color_in = self::OPTIONS['colors']['color_in'];
// A tous ceux qui n'ont pas de couleur spécifiée, alors saisir la couleur par défaut
$message = preg_replace("/(?<!>)(%[a-zA-Z0-9])/", "$color_in>$1", $message);
// Remplacer par le code de colorisation Shell
$message = preg_replace("#([0-9]+)>(%[a-zA-Z0-9])#", "\e[38;5;$1m$2\e[0m", $message);
return $message;
}
/**
* Emet des messages dans le flux STDERR de niveau WARNING ou ERROR
*
* @param string $message Message à afficher dans le STDERR
* @param array $args Elements à introduire dans le message
* @param int $level Niveau d'alerte : 0 = warning, 1 = error
*
* @return void
*/
protected function stderr($message, array $args = [], $level = 1)
{
// Connexion aux variables globales
$color_err = self::OPTIONS['colors']['color_err'];
$color_war = self::OPTIONS['colors']['color_war'];
// Traitement en fonction du niveau d'erreur
$level_str = ($level) ? "ERROR" : "WARNING";
$color = ($level) ? $color_err : $color_war;
// Mise en evidence des saisie utilisateur
$message = $this->highlight($message);
$message = "[ \e[38;5;{$color}m$level_str\e[0m ] :: $message" . PHP_EOL;
fwrite($this->pstderr, vsprintf($message, $args));
if ($level && !$this->noDie) die($level);
}
/**
* Emet des messages dans le flux classique STDOUT
*
* @param string $message Message à afficher dans le STDOUT
* @param array $arg Elements à introduire dans le message
*/
protected function stdout($message, $args = [])
{
$options = self::OPTIONS;
if (!isset($options["silent"])) {
$message = $this->highlight($message);
$message = "[ INFO ] :: $message".PHP_EOL;
fwrite($this->psdtout, vsprintf($message, $args));
}
}
/**
* Définie la ressource de sortie standard.
*
* @param bool|resource $stdout Pointeur vers une ressource ayant un accès en écriture.
*/
public function setStdout($stdout = STDOUT)
{
$this->psdtout = $stdout;
}
/**
* Définie la ressource de sortie des erreurs.
*
* @param bool|resource $stderr Pointeur vers une ressource ayant un accès en écriture.
*/
public function setStderr($stderr = STDERR)
{
$this->pstderr = $stderr;
}
/**
* Définie le comportement des fonctions die.
*
* @param bool $nodie
*/
public function setNoDie($nodie = false)
{
$this->noDie = $nodie;
}
}
| neooblaster/SYSLang | src/SYSLang/Command.php | PHP | gpl-3.0 | 16,133 |
/*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.others.BlackJudge;
import com.l2jglobal.gameserver.model.actor.L2Npc;
import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance;
import ai.AbstractNpcAI;
/**
* Black Judge AI.
* @author St3eT
*/
public final class BlackJudge extends AbstractNpcAI
{
// NPC
private static final int BLACK_JUDGE = 30981;
private BlackJudge()
{
addStartNpc(BLACK_JUDGE);
addTalkId(BLACK_JUDGE);
addFirstTalkId(BLACK_JUDGE);
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
String htmltext = null;
if (event.equals("weakenBreath"))
{
if (player.getShilensBreathDebuffLevel() >= 3)
{
player.setShilensBreathDebuffLevel(2);
htmltext = "30981-01.html";
}
else
{
htmltext = "30981-02.html";
}
}
return htmltext;
}
public static void main(String[] args)
{
new BlackJudge();
}
} | rubenswagner/L2J-Global | dist/game/data/scripts/ai/others/BlackJudge/BlackJudge.java | Java | gpl-3.0 | 1,586 |
package org.jcoderz.m3server.renderer;
import java.util.logging.Logger;
import org.jcoderz.m3server.library.Item;
import org.jcoderz.m3server.util.Logging;
/**
* This class represents MPD rendering devices. <ul> <li><a
* href="http://mpd.wikia.com/wiki/Protocol_Reference">Protocol
* Reference</a></li> <li><a
* href="http://mpd.wikia.com/wiki/Built-in_HTTP_streaming_part_2">Built-in HTTP
* streaming part 2</a></li> </ul>
*
* @author mrumpf
*
*/
public class MpdRenderer extends AbstractRenderer {
private static final Logger logger = Logging.getLogger(MpdRenderer.class);
/**
* Constructor.
*
* @param name the name of the renderer
*/
public MpdRenderer(String name) {
super(name, RendererType.MPD);
}
@Override
public Item playpath(String url) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void stop() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void pause() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Info info() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void play() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void volume(long level) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public long volume() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| jCoderZ/m3server | src/main/java/org/jcoderz/m3server/renderer/MpdRenderer.java | Java | gpl-3.0 | 2,066 |
<?php
namespace ApacheSolrForTypo3\Solr\Tests\Unit\System\Cache;
/***************************************************************
* Copyright notice
*
* (c) 2016 <timo.schmidt@dkd.de>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
use ApacheSolrForTypo3\Solr\Tests\Unit\UnitTest;
use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
use TYPO3\CMS\Core\Cache\Backend\BackendInterface;
/**
* Unit testcase to check if the two level cache is working as expected.
*
* @author Timo Schmidt <timo.schmidt@dkd.de>
*/
class TwoLevelCacheTest extends UnitTest
{
/**
* @var TwoLevelCache
*/
protected $twoLevelCache;
/**
* @var FrontendInterface
*/
protected $secondLevelCacheMock;
/**
* Prepare
*
* @see \PHPUnit\Framework\TestCase::setUp()
*/
protected function setUp(): void
{
$this->secondLevelCacheMock = $this->getDumbMock(FrontendInterface::class);
$this->twoLevelCache = new TwoLevelCache('test', $this->secondLevelCacheMock);
}
/**
* Cleanup
* {@inheritDoc}
*/
protected function tearDown(): void
{
$this->twoLevelCache->flush();
parent::tearDown();
}
/**
* @test
*/
public function getOnSecondaryCacheIsNeverCalledWhenValueIsPresentInFirstLevelCache(): void
{
$this->secondLevelCacheMock->expects($this->never())->method('get');
// when we add a value with the identifier to the two level cache, the second level
// cache should not be asked because the value should allready be found in the first
// level cache
$this->twoLevelCache->set('foo', 'bar');
$value = $this->twoLevelCache->get('foo');
$this->assertSame($value, 'bar', 'Did not get expected value from two level cache');
}
/**
* @test
* @throws NoSuchCacheException
*/
public function canHandleInvalidCacheIdentifierOnSet(): void
{
$cacheBackendMock = $this->createMock(BackendInterface::class);
$cacheBackendMock->expects($this->once())->method('set');
$variableFrontend = new VariableFrontend('TwoLevelCacheTest', $cacheBackendMock);
$this->twoLevelCache = new TwoLevelCache('test', $variableFrontend);
$this->twoLevelCache->set('I.Am.An.Invalid.Identifier-#ß%&!', 'dummyValue');
}
/**
* @test
* @throws NoSuchCacheException
*/
public function canHandleInvalidCacheIdentifierOnGet(): void
{
$cacheBackendMock = $this->createMock(BackendInterface::class);
$cacheBackendMock->expects($this->once())->method('get');
$variableFrontend = new VariableFrontend('TwoLevelCacheTest', $cacheBackendMock);
$this->twoLevelCache = new TwoLevelCache('test', $variableFrontend);
$this->assertFalse($this->twoLevelCache->get('I.Am.An.Invalid.Identifier-#ß%&!'));
}
}
| dkd-kaehm/ext-solr | Tests/Unit/System/Cache/TwoLevelCacheTest.php | PHP | gpl-3.0 | 3,835 |
package com.orgzly.android.widgets;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;
import com.orgzly.BuildConfig;
import com.orgzly.R;
import com.orgzly.android.App;
import com.orgzly.android.AppIntent;
import com.orgzly.android.data.DataRepository;
import com.orgzly.android.db.entity.SavedSearch;
import com.orgzly.android.prefs.AppPreferences;
import com.orgzly.android.ui.main.MainActivity;
import com.orgzly.android.ui.share.ShareActivity;
import com.orgzly.android.ui.util.ActivityUtils;
import com.orgzly.android.usecase.NoteUpdateStateToggle;
import com.orgzly.android.usecase.UseCaseRunner;
import com.orgzly.android.util.LogUtils;
import java.util.Calendar;
import java.util.Collections;
import javax.inject.Inject;
/**
* The AppWidgetProvider for the list widget
*/
public class ListWidgetProvider extends AppWidgetProvider {
private static final String TAG = ListWidgetProvider.class.getName();
private static final String PREFERENCES_ID = "list-widget";
public static final int OPEN_CLICK_TYPE = 1;
public static final int DONE_CLICK_TYPE = 2;
@Inject
DataRepository dataRepository;
public static void notifyDataChanged(Context context) {
Intent intent = new Intent(context, ListWidgetProvider.class);
intent.setAction(AppIntent.ACTION_UPDATE_LIST_WIDGET);
context.sendBroadcast(intent);
}
public static void update(Context context) {
Intent intent = new Intent(context, ListWidgetProvider.class);
intent.setAction(AppIntent.ACTION_UPDATE_LAYOUT_LIST_WIDGET);
context.sendBroadcast(intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG);
for (int appWidgetId : appWidgetIds) {
updateAppWidgetLayout(context, appWidgetManager, appWidgetId);
}
}
private void updateAppWidgetLayout(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG);
App.EXECUTORS.diskIO().execute(() -> {
SavedSearch savedSearch = getSavedSearch(context, appWidgetId);
App.EXECUTORS.mainThread().execute(() -> {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.list_widget);
WidgetStyle.updateWidget(remoteViews, context);
Intent serviceIntent = new Intent(context, ListWidgetService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
serviceIntent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.getQuery());
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
// Tell ListView where to get the data from
remoteViews.setRemoteAdapter(R.id.list_widget_list_view, serviceIntent);
remoteViews.setEmptyView(R.id.list_widget_list_view, R.id.list_widget_empty_view);
remoteViews.setTextViewText(R.id.list_widget_empty_view, context.getString(R.string.no_notes_found_after_search));
// Rows - open note
final Intent onClickIntent = new Intent(context, ListWidgetProvider.class);
onClickIntent.setAction(AppIntent.ACTION_CLICK_LIST_WIDGET);
onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0,
onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setPendingIntentTemplate(R.id.list_widget_list_view, onClickPendingIntent);
// Plus icon - new note
remoteViews.setOnClickPendingIntent(R.id.list_widget_header_add, ShareActivity.createNewNoteIntent(context, savedSearch));
// Logo - open query
Intent openIntent = Intent.makeRestartActivityTask(new ComponentName(context, MainActivity.class));
openIntent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.getQuery());
openIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setOnClickPendingIntent(R.id.list_widget_header_icon, PendingIntent.getActivity(context, 0, openIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Intent selectionIntent = new Intent(context, ListWidgetSelectionActivity.class);
selectionIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
selectionIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setOnClickPendingIntent(R.id.list_widget_header_bar, PendingIntent.getActivity(context, 0, selectionIntent, PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setTextViewText(
R.id.list_widget_header_selection,
savedSearch.getName());
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
});
});
}
private void updateAppWidgetLayouts(Context context) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisAppWidgetComponentName = new ComponentName(context.getPackageName(), ListWidgetProvider.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName);
for (int appWidgetId : appWidgetIds) {
updateAppWidgetLayout(context, appWidgetManager, appWidgetId);
}
scheduleUpdate(context);
}
private void updateListContents(Context context) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisAppWidgetComponentName = new ComponentName(context.getPackageName(), ListWidgetProvider.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_widget_list_view);
}
@Override
public void onEnabled(Context context) {
scheduleUpdate(context);
}
@Override
public void onDisabled(Context context) {
clearUpdate(context);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCES_ID, Context.MODE_PRIVATE).edit();
for (int id: appWidgetIds) {
editor.remove(getFilterPreferenceKey(id));
}
editor.apply();
}
private void scheduleUpdate(Context context) {
/*
schedule updates via AlarmManager, because we don't want to wake the device on every update
see https://developer.android.com/guide/topics/appwidgets/index.html#MetaData
*/
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent intent = getAlarmIntent(context);
alarmManager.cancel(intent);
int intervalMin = AppPreferences.widgetUpdateFrequency(context);
long intervalMillis = intervalMin * 60 * 1000;
long now = System.currentTimeMillis();
Calendar triggerAt = Calendar.getInstance();
triggerAt.setTimeInMillis(now);
triggerAt.set(Calendar.MILLISECOND, 1);
triggerAt.set(Calendar.SECOND, 0);
triggerAt.set(Calendar.MINUTE, 0);
do {
triggerAt.add(Calendar.MINUTE, intervalMin);
} while (triggerAt.getTimeInMillis() < now);
alarmManager.setInexactRepeating(
AlarmManager.RTC,
triggerAt.getTimeInMillis(),
intervalMillis,
intent);
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, triggerAt.getTimeInMillis(), intervalMillis);
}
private void clearUpdate(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(getAlarmIntent(context));
}
private PendingIntent getAlarmIntent(Context context) {
Intent intent = new Intent(context, ListWidgetProvider.class);
intent.setAction(AppIntent.ACTION_UPDATE_LIST_WIDGET);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private void setSelectionFromIntent(Context context, Intent intent) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG);
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
long savedSearchId = intent.getLongExtra(AppIntent.EXTRA_SAVED_SEARCH_ID, 0);
setFilter(context, appWidgetId, savedSearchId);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
updateAppWidgetLayout(context, appWidgetManager, appWidgetId);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.list_widget_list_view);
}
private SavedSearch getSavedSearch(Context context, int appWidgetId) {
long filterId = context.getSharedPreferences(PREFERENCES_ID, Context.MODE_PRIVATE)
.getLong(getFilterPreferenceKey(appWidgetId), -1);
SavedSearch savedSearch = null;
if (filterId != -1) {
savedSearch = dataRepository.getSavedSearch(filterId);
}
if (savedSearch == null) {
savedSearch = new SavedSearch(0, context.getString(R.string.list_widget_select_search), "", 0);
}
return savedSearch;
}
private void setFilter(Context context, int appWidgetId, long id) {
SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCES_ID, Context.MODE_PRIVATE).edit();
editor.putLong(getFilterPreferenceKey(appWidgetId), id);
editor.apply();
}
private String getFilterPreferenceKey(int appWidgetId) {
return "widget-filter-" + appWidgetId;
}
private void setNoteDone(Intent intent) {
final long noteId = intent.getLongExtra(AppIntent.EXTRA_NOTE_ID, 0L);
App.EXECUTORS.diskIO().execute(() ->
UseCaseRunner.run(new NoteUpdateStateToggle(Collections.singleton(noteId))));
}
private void openNote(Context context, Intent intent) {
long noteId = intent.getLongExtra(AppIntent.EXTRA_NOTE_ID, 0L);
long bookId = intent.getLongExtra(AppIntent.EXTRA_BOOK_ID, 0L);
PendingIntent pi = ActivityUtils.mainActivityPendingIntent(context, bookId, noteId);
try {
pi.send();
} catch (PendingIntent.CanceledException e) {
Log.e(TAG, "Error opening note: " + e);
}
}
@Override
public void onReceive(Context context, Intent intent) {
App.appComponent.inject(this);
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, intent);
if (AppIntent.ACTION_UPDATE_LIST_WIDGET.equals(intent.getAction())) {
updateListContents(context);
} else if (AppIntent.ACTION_UPDATE_LAYOUT_LIST_WIDGET.equals(intent.getAction())) {
updateAppWidgetLayouts(context);
} else if (AppIntent.ACTION_SET_LIST_WIDGET_SELECTION.equals(intent.getAction())) {
setSelectionFromIntent(context, intent);
} else if (AppIntent.ACTION_CLICK_LIST_WIDGET.equals(intent.getAction())) {
switch (intent.getIntExtra(AppIntent.EXTRA_CLICK_TYPE, -1)) {
case OPEN_CLICK_TYPE:
openNote(context, intent);
break;
case DONE_CLICK_TYPE:
setNoteDone(intent);
break;
}
} else {
super.onReceive(context, intent);
}
}
}
| orgzly/orgzly-android | app/src/main/java/com/orgzly/android/widgets/ListWidgetProvider.java | Java | gpl-3.0 | 12,412 |
package com.yc.tieba.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @Description: 初始化敏感词库,将敏感词加入到HashMap中,构建DFA算法模型
* @Project:test
* @Author : chenming
* @Date : 2014年4月20日 下午2:27:06
* @version 1.0
*/
public class SensitiveWordInit {
private String ENCODING = "GBK"; //字符编码
@SuppressWarnings("rawtypes")
public HashMap sensitiveWordMap;
public SensitiveWordInit(){
super();
}
/**
* @author chenming
* @date 2014年4月20日 下午2:28:32
* @version 1.0
*/
@SuppressWarnings("rawtypes")
public Map initKeyWord(){
try {
//读取敏感词库
Set<String> keyWordSet = readSensitiveWordFile();
//将敏感词库加入到HashMap中
addSensitiveWordToHashMap(keyWordSet);
//spring获取application,然后application.setAttribute("sensitiveWordMap",sensitiveWordMap);
} catch (Exception e) {
e.printStackTrace();
}
return sensitiveWordMap;
}
/**
* 读取敏感词库,将敏感词放入HashSet中,构建一个DFA算法模型:<br>
* 中 = {
* isEnd = 0
* 国 = {<br>
* isEnd = 1
* 人 = {isEnd = 0
* 民 = {isEnd = 1}
* }
* 男 = {
* isEnd = 0
* 人 = {
* isEnd = 1
* }
* }
* }
* }
* 五 = {
* isEnd = 0
* 星 = {
* isEnd = 0
* 红 = {
* isEnd = 0
* 旗 = {
* isEnd = 1
* }
* }
* }
* }
* @author chenming
* @date 2014年4月20日 下午3:04:20
* @param keyWordSet 敏感词库
* @version 1.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addSensitiveWordToHashMap(Set<String> keyWordSet) {//keyWordSet 文档
sensitiveWordMap = new HashMap(keyWordSet.size()); //初始化敏感词容器,减少扩容操作
String key = null;
Map nowMap = null;
Map<String, String> newWorMap = null;
//迭代keyWordSet
Iterator<String> iterator = keyWordSet.iterator();
while(iterator.hasNext()){
key = iterator.next(); //关键字 key 单独的关键字
nowMap = sensitiveWordMap;
for(int i = 0 ; i < key.length() ; i++){
char keyChar = key.charAt(i); //转换成char型
Object wordMap = nowMap.get(keyChar); //获取在nowMap是否有记录
if(wordMap != null){ //如果存在该key,直接赋值
nowMap = (Map) wordMap;
}
else{ //不存在则,则构建一个map,同时将isEnd设置为0,因为他不是最后一个
newWorMap = new HashMap<String,String>();
newWorMap.put("isEnd", "0"); //不是最后一个
nowMap.put(keyChar, newWorMap);
nowMap = newWorMap;
}
if(i == key.length() - 1){
nowMap.put("isEnd", "1"); //最后一个
}
}
}
}
/**
* 读取敏感词库中的内容,将内容添加到set集合中
* @author chenming
* @date 2014年4月20日 下午2:31:18
* @return
* @version 1.0
* @throws Exception
*/
@SuppressWarnings("resource")
private Set<String> readSensitiveWordFile() throws Exception{
Set<String> set = null;
File file = new File("E:\\SensitiveWord.txt"); //读取文件
InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING);
try {
if(file.isFile() && file.exists()){ //文件流是否存在
set = new HashSet<String>();
BufferedReader bufferedReader = new BufferedReader(read);
String txt = null;
while((txt = bufferedReader.readLine()) != null){ //读取文件,将文件内容放入到set中
set.add(txt);
}
}
else{ //不存在抛出异常信息
throw new Exception("敏感词库文件不存在");
}
} catch (Exception e) {
throw e;
}finally{
read.close(); //关闭文件流
}
return set;
}
}
| joyceshenhui/tieba | tieba/src/main/java/com/yc/tieba/util/SensitiveWordInit.java | Java | gpl-3.0 | 4,315 |
from __future__ import unicode_literals
import socket
from django.conf import settings
try:
HOSTNAME = socket.gethostname()
except:
HOSTNAME = 'localhost'
def common_settings(request):
"""Passing custom CONSTANT in Settings into RequestContext."""
from django.contrib.sites.models import get_current_site
COMMON_CONTEXT = {
"DEBUG": settings.DEBUG,
"MAILCHIMP_UUID": settings.MAILCHIMP_UUID,
"MAILCHIMP_ACTION_URL": settings.MAILCHIMP_ACTION_URL,
"HOSTNAME": HOSTNAME,
"CURRENT_DOMAIN": get_current_site(request).domain,
}
try:
# set EXTRA_CONTEXT in local settings
COMMON_CONTEXT.update(settings.EXTRA_CONTEXT)
except:
pass
return COMMON_CONTEXT
| thetoine/eruditorg | erudit/base/context_processors.py | Python | gpl-3.0 | 753 |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <SysUtils.hpp>
#include "Common.h"
#include "Exceptions.h"
#include "TextsCore.h"
#include "Script.h"
#include "Terminal.h"
#include "SessionData.h"
#include "CoreMain.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
static const wchar_t * TransferModeNames[] = { L"binary", L"ascii", L"automatic" };
enum { Off, On };
static const wchar_t * ToggleNames[] = { L"off", L"on" };
//---------------------------------------------------------------------------
__fastcall TScriptProcParams::TScriptProcParams(UnicodeString ParamsStr)
{
int P = FSwitchMarks.Pos(L"/");
assert(P > 0);
if (P > 0)
{
FSwitchMarks.Delete(P, 1);
}
FParamsStr = ParamsStr;
UnicodeString Param;
while (CutToken(ParamsStr, Param))
{
Add(Param);
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TScriptCommands : TStringList
{
public:
typedef void __fastcall (__closure *TCommandProc)(TScriptProcParams * Parameters);
__fastcall TScriptCommands(TScript * Script);
virtual __fastcall ~TScriptCommands();
void __fastcall Execute(const UnicodeString & Command, const UnicodeString & Params);
UnicodeString __fastcall ResolveCommand(const UnicodeString & Command);
void __fastcall Register(const wchar_t * Command,
const UnicodeString Description, const UnicodeString Help, TCommandProc Proc,
int MinParams, int MaxParams, bool Switches);
void __fastcall Register(const wchar_t * Command,
int Description, int Help, TCommandProc Proc,
int MinParams, int MaxParams, bool Switches);
bool __fastcall Info(const UnicodeString Command,
UnicodeString * Description, UnicodeString * Help);
bool __fastcall Enumerate(int Index,
UnicodeString * Command, UnicodeString * Description, UnicodeString * Help);
static int __fastcall FindCommand(TStrings * Commands, const UnicodeString Command,
UnicodeString * Matches = NULL);
static int __fastcall FindCommand(const wchar_t ** Commands, size_t Count,
const UnicodeString Command, UnicodeString * Matches = NULL);
static void __fastcall CheckParams(TOptions * Parameters, bool Switches);
protected:
struct TScriptCommand
{
UnicodeString Description;
UnicodeString Help;
TCommandProc Proc;
int MinParams;
int MaxParams;
bool Switches;
};
TScript * FScript;
};
//---------------------------------------------------------------------------
__fastcall TScriptCommands::TScriptCommands(TScript * Script)
{
FScript = Script;
Sorted = true;
CaseSensitive = false;
}
//---------------------------------------------------------------------------
__fastcall TScriptCommands::~TScriptCommands()
{
for (int Index = 0; Index < Count; Index++)
{
delete reinterpret_cast<TScriptCommand *>(Objects[Index]);
}
}
//---------------------------------------------------------------------------
void __fastcall TScriptCommands::Register(const wchar_t * Command,
const UnicodeString Description, const UnicodeString Help, TCommandProc Proc,
int MinParams, int MaxParams, bool Switches)
{
TScriptCommand * ScriptCommand = new TScriptCommand;
ScriptCommand->Description = Description;
ScriptCommand->Help = Help;
ScriptCommand->Proc = Proc;
ScriptCommand->MinParams = MinParams;
ScriptCommand->MaxParams = MaxParams;
ScriptCommand->Switches = Switches;
AddObject(Command, reinterpret_cast<TObject *>(ScriptCommand));
}
//---------------------------------------------------------------------------
void __fastcall TScriptCommands::Register(const wchar_t * Command,
int Description, int Help, TCommandProc Proc,
int MinParams, int MaxParams, bool Switches)
{
UnicodeString ADescription;
if (Description > 0)
{
ADescription = LoadStr(Description);
}
UnicodeString AHelp;
if (Help > 0)
{
AHelp = LoadStr(Help, 10240);
}
Register(Command, ADescription, AHelp, Proc, MinParams, MaxParams, Switches);
}
//---------------------------------------------------------------------------
bool __fastcall TScriptCommands::Info(const UnicodeString Command,
UnicodeString * Description, UnicodeString * Help)
{
int Index = FindCommand(this, Command);
bool Result = (Index >= 0);
if (Result)
{
TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
if (Description != NULL)
{
*Description = ScriptCommand->Description;
}
if (Help != NULL)
{
*Help = ScriptCommand->Help;
}
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall TScriptCommands::Enumerate(int Index,
UnicodeString * Command, UnicodeString * Description, UnicodeString * Help)
{
bool Result = (Index < Count);
if (Result)
{
TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
if (Command != NULL)
{
*Command = Strings[Index];
}
if (Description != NULL)
{
*Description = ScriptCommand->Description;
}
if (Help != NULL)
{
*Help = ScriptCommand->Help;
}
}
return Result;
}
//---------------------------------------------------------------------------
int __fastcall TScriptCommands::FindCommand(TStrings * Commands,
const UnicodeString Command, UnicodeString * Matches)
{
int Result = Commands->IndexOf(Command);
if (Result < 0)
{
int MatchesCount = 0;
for (int i = 0; i < Commands->Count; i++)
{
if ((Command.Length() <= Commands->Strings[i].Length()) &&
AnsiSameText(Command, Commands->Strings[i].SubString(1, Command.Length())))
{
if (Matches != NULL)
{
if (!Matches->IsEmpty())
{
*Matches += L", ";
}
*Matches += Commands->Strings[i];
}
MatchesCount++;
Result = i;
}
}
if (MatchesCount == 0)
{
Result = -1;
}
else if (MatchesCount > 1)
{
Result = -2;
}
}
return Result;
}
//---------------------------------------------------------------------------
int __fastcall TScriptCommands::FindCommand(const wchar_t ** Commands, size_t Count,
const UnicodeString Command, UnicodeString * Matches)
{
int Result;
TStringList * Strings = new TStringList;
try
{
Strings->CaseSensitive = false;
for (unsigned int i = 0; i < Count; i++)
{
Strings->Add(Commands[i]);
}
Result = FindCommand(Strings, Command, Matches);
}
__finally
{
delete Strings;
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TScriptCommands::CheckParams(TOptions * Parameters,
bool Switches)
{
UnicodeString Switch;
if (!Switches && Parameters->UnusedSwitch(Switch))
{
throw Exception(FMTLOAD(SCRIPT_UNKNOWN_SWITCH, (Switch)));
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TScriptCommands::ResolveCommand(const UnicodeString & Command)
{
UnicodeString Matches;
int Index = FindCommand(this, Command, &Matches);
if (Index >= 0)
{
return Strings[Index];
}
else
{
return UnicodeString();
}
}
//---------------------------------------------------------------------------
// parameters are by purpose passed by (constant) reference.
// because if passed by value (copy), UnicodeString reference is not for some reason
// decreased on exit by exception, leading to memory leak
void __fastcall TScriptCommands::Execute(const UnicodeString & Command, const UnicodeString & Params)
{
TScriptProcParams * Parameters = new TScriptProcParams(Params);
try
{
UnicodeString Matches;
int Index = FindCommand(this, Command, &Matches);
if (Index == -2)
{
throw Exception(FMTLOAD(SCRIPT_COMMAND_AMBIGUOUS, (Command, Matches)));
}
else if (Index < 0)
{
throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Command)));
}
TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
UnicodeString FullCommand = Strings[Index];
if (Parameters->ParamCount < ScriptCommand->MinParams)
{
throw Exception(FMTLOAD(SCRIPT_MISSING_PARAMS, (FullCommand)));
}
else if ((ScriptCommand->MaxParams >= 0) && (Parameters->ParamCount > ScriptCommand->MaxParams))
{
throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (FullCommand)));
}
else
{
CheckParams(Parameters, ScriptCommand->Switches);
ScriptCommand->Proc(Parameters);
}
}
__finally
{
delete Parameters;
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
__fastcall TScript::TScript(bool LimitedOutput)
{
FLimitedOutput = LimitedOutput;
FTerminal = NULL;
FSessionReopenTimeout = Configuration->SessionReopenTimeout;
FGroups = false;
FWantsProgress = false;
FIncludeFileMaskOptionUsed = false;
FPendingLogLines = new TStringList();
Init();
}
//---------------------------------------------------------------------------
__fastcall TScript::~TScript()
{
delete FCommands;
delete FPendingLogLines;
}
//---------------------------------------------------------------------------
void __fastcall TScript::Init()
{
FBatch = BatchAbort;
FInteractiveBatch = BatchOff;
FConfirm = false;
FInteractiveConfirm = true;
FEcho = false;
FFailOnNoMatch = false;
FSynchronizeParams = 0;
FOnPrint = NULL;
FOnTerminalSynchronizeDirectory = NULL;
FOnSynchronizeStartStop = NULL;
FSynchronizeMode = -1;
FKeepingUpToDate = false;
FWarnNonDefaultCopyParam = false;
FWarnNonDefaultSynchronizeParams = false;
FCommands = new TScriptCommands(this);
FCommands->Register(L"help", SCRIPT_HELP_DESC, SCRIPT_HELP_HELP, &HelpProc, 0, -1, false);
FCommands->Register(L"man", 0, SCRIPT_HELP_HELP, &HelpProc, 0, -1, false);
// the call command does not have switches itself, but the commands may have
FCommands->Register(L"call", SCRIPT_CALL_DESC2, SCRIPT_CALL_HELP2, &CallProc, 1, -1, true);
FCommands->Register(L"!", 0, SCRIPT_CALL_HELP2, &CallProc, 1, -1, false);
FCommands->Register(L"pwd", SCRIPT_PWD_DESC, SCRIPT_PWD_HELP, &PwdProc, 0, 0, false);
FCommands->Register(L"cd", SCRIPT_CD_DESC, SCRIPT_CD_HELP, &CdProc, 0, 1, false);
FCommands->Register(L"ls", SCRIPT_LS_DESC, SCRIPT_LS_HELP2, &LsProc, 0, 1, false);
FCommands->Register(L"dir", 0, SCRIPT_LS_HELP2, &LsProc, 0, 1, false);
FCommands->Register(L"rm", SCRIPT_RM_DESC, SCRIPT_RM_HELP2, &RmProc, 1, -1, false);
FCommands->Register(L"rmdir", SCRIPT_RMDIR_DESC, SCRIPT_RMDIR_HELP, &RmDirProc, 1, -1, false);
FCommands->Register(L"mv", SCRIPT_MV_DESC, SCRIPT_MV_HELP2, &MvProc, 2, -1, false);
FCommands->Register(L"rename", 0, SCRIPT_MV_HELP2, &MvProc, 2, -1, false);
FCommands->Register(L"chmod", SCRIPT_CHMOD_DESC, SCRIPT_CHMOD_HELP2, &ChModProc, 2, -1, false);
FCommands->Register(L"ln", SCRIPT_LN_DESC, SCRIPT_LN_HELP, &LnProc, 2, 2, false);
FCommands->Register(L"symlink", 0, SCRIPT_LN_HELP, &LnProc, 2, 2, false);
FCommands->Register(L"mkdir", SCRIPT_MKDIR_DESC, SCRIPT_MKDIR_HELP, &MkDirProc, 1, 1, false);
FCommands->Register(L"get", SCRIPT_GET_DESC, SCRIPT_GET_HELP7, &GetProc, 1, -1, true);
FCommands->Register(L"recv", 0, SCRIPT_GET_HELP7, &GetProc, 1, -1, false);
FCommands->Register(L"mget", 0, SCRIPT_GET_HELP7, &GetProc, 1, -1, false);
FCommands->Register(L"put", SCRIPT_PUT_DESC, SCRIPT_PUT_HELP7, &PutProc, 1, -1, true);
FCommands->Register(L"send", 0, SCRIPT_PUT_HELP7, &PutProc, 1, -1, false);
FCommands->Register(L"mput", 0, SCRIPT_PUT_HELP7, &PutProc, 1, -1, false);
FCommands->Register(L"option", SCRIPT_OPTION_DESC, SCRIPT_OPTION_HELP7, &OptionProc, -1, 2, false);
FCommands->Register(L"ascii", 0, SCRIPT_OPTION_HELP7, &AsciiProc, 0, 0, false);
FCommands->Register(L"binary", 0, SCRIPT_OPTION_HELP7, &BinaryProc, 0, 0, false);
FCommands->Register(L"synchronize", SCRIPT_SYNCHRONIZE_DESC, SCRIPT_SYNCHRONIZE_HELP7, &SynchronizeProc, 1, 3, true);
FCommands->Register(L"keepuptodate", SCRIPT_KEEPUPTODATE_DESC, SCRIPT_KEEPUPTODATE_HELP4, &KeepUpToDateProc, 0, 2, true);
// the echo command does not have switches actually, but it must handle dashes in its arguments
FCommands->Register(L"echo", SCRIPT_ECHO_DESC, SCRIPT_ECHO_HELP, &EchoProc, -1, -1, true);
FCommands->Register(L"stat", SCRIPT_STAT_DESC, SCRIPT_STAT_HELP, &StatProc, 1, 1, false);
FCommands->Register(L"checksum", SCRIPT_CHECKSUM_DESC, SCRIPT_CHECKSUM_HELP, &ChecksumProc, 2, 2, false);
}
//---------------------------------------------------------------------------
void __fastcall TScript::CheckDefaultCopyParam()
{
if (FWarnNonDefaultCopyParam)
{
// started with non-factory settings and still have them, warn
if (HasNonDefaultCopyParams())
{
PrintLine(LoadStr(SCRIPT_NON_DEFAULT_COPY_PARAM));
}
FWarnNonDefaultCopyParam = false;
}
}
//---------------------------------------------------------------------------
bool __fastcall TScript::HasNonDefaultCopyParams()
{
return !(FCopyParam == TCopyParamType());
}
//---------------------------------------------------------------------------
void __fastcall TScript::SetCopyParam(const TCopyParamType & value)
{
FCopyParam.Assign(&value);
FWarnNonDefaultCopyParam = HasNonDefaultCopyParams();
}
//---------------------------------------------------------------------------
void __fastcall TScript::CheckDefaultSynchronizeParams()
{
if (FWarnNonDefaultSynchronizeParams)
{
// as opposite to CheckDefaultCopyParam(), not checking
// current params as we cannot override any of those we accept anyway
PrintLine(LoadStr(SCRIPT_NON_DEFAULT_SYNC_PARAM));
FWarnNonDefaultSynchronizeParams = false;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::SetSynchronizeParams(int value)
{
const int AcceptedParams =
TTerminal::spExistingOnly | TTerminal::spTimestamp |
TTerminal::spNotByTime | TTerminal::spBySize;
FSynchronizeParams = (value & AcceptedParams);
FWarnNonDefaultSynchronizeParams =
(FSynchronizeParams != (TTerminal::spDefault & AcceptedParams));
}
//---------------------------------------------------------------------------
bool __fastcall TScript::IsTerminalLogging(TTerminal * ATerminal)
{
return (ATerminal != NULL) && ATerminal->Log->Logging;
}
//---------------------------------------------------------------------------
const static UnicodeString ScriptLogFormat(L"Script: %s");
void __fastcall TScript::Log(TLogLineType Type, AnsiString Str)
{
Str = FORMAT(ScriptLogFormat, (Str));
if (IsTerminalLogging(Terminal))
{
Terminal->Log->Add(Type, Str);
}
else if (Configuration->Logging)
{
FPendingLogLines->AddObject(Str, reinterpret_cast<TObject *>(Type));
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::LogOption(const UnicodeString & LogStr)
{
Log(llInput, LogStr);
}
//---------------------------------------------------------------------------
void __fastcall TScript::LogPendingLines(TTerminal * ATerminal)
{
if (IsTerminalLogging(ATerminal) && (FPendingLogLines->Count > 0))
{
// not using Log(), as we want to log to ATerminal, not Terminal,
// what is different here, as we are called from TManagementScript::Connect()
ATerminal->Log->Add(llMessage, FORMAT(ScriptLogFormat, (L"Retrospectively logging previous script records:")));
for (int Index = 0; Index < FPendingLogLines->Count; Index++)
{
ATerminal->Log->Add(
reinterpret_cast<TLogLineType>(FPendingLogLines->Objects[Index]),
FPendingLogLines->Strings[Index]);
}
FPendingLogLines->Clear();
ATerminal->Log->AddSeparator();
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TScript::GetLogCmd(const UnicodeString & FullCommand,
const UnicodeString & /*Command*/, const UnicodeString & /*Params*/)
{
return FullCommand;
}
//---------------------------------------------------------------------------
void __fastcall TScript::StartInteractive()
{
FBatch = FInteractiveBatch;
FConfirm = FInteractiveConfirm;
}
//---------------------------------------------------------------------------
void __fastcall TScript::Command(UnicodeString Cmd)
{
try
{
if (!Cmd.Trim().IsEmpty() && (Cmd[1] != L';') && (Cmd[1] != L'#'))
{
UnicodeString FullCmd = Cmd;
UnicodeString Command;
if (CutToken(Cmd, Command))
{
UnicodeString LogCmd = GetLogCmd(FullCmd, Command, Cmd);
Log(llInput, LogCmd);
if (Configuration->LogProtocol >= 1)
{
UnicodeString DummyLogCmd;
if (ALWAYS_TRUE(CutToken(LogCmd, DummyLogCmd)))
{
std::unique_ptr<TScriptProcParams> Parameters(new TScriptProcParams(LogCmd));
Parameters->LogOptions(LogOption);
}
}
if (FEcho)
{
PrintLine(LogCmd);
}
TTerminal * BeforeGroupTerminal = FGroups ? Terminal : NULL;
if (BeforeGroupTerminal != NULL)
{
BeforeGroupTerminal->ActionLog->BeginGroup(LogCmd);
}
int ASessionReopenTimeout = Configuration->SessionReopenTimeout;
try
{
Configuration->SessionReopenTimeout = FSessionReopenTimeout;
try
{
FCommands->Execute(Command, Cmd);
}
catch(Exception & E)
{
// seemingly duplicate (to the method-level one) catch clause,
// ensures the <failure/> tag is enclosed in <group/> tag
if (!HandleExtendedException(&E))
{
throw;
}
}
}
__finally
{
Configuration->SessionReopenTimeout = ASessionReopenTimeout;
TTerminal * AfterGroupTerminal = FGroups ? Terminal : NULL;
if (AfterGroupTerminal != NULL)
{
// this happens for "open" command
if (AfterGroupTerminal != BeforeGroupTerminal)
{
AfterGroupTerminal->ActionLog->BeginGroup(LogCmd);
}
AfterGroupTerminal->ActionLog->EndGroup();
}
}
}
}
}
catch(Exception & E)
{
if (!HandleExtendedException(&E))
{
throw;
}
}
}
//---------------------------------------------------------------------------
TStrings * __fastcall TScript::CreateFileList(TScriptProcParams * Parameters, int Start,
int End, TFileListType ListType)
{
TStrings * Result = new TStringList();
TStrings * FileLists = NULL;
try
{
try
{
for (int i = Start; i <= End; i++)
{
UnicodeString FileName = Parameters->Param[i];
if (FLAGSET(ListType, fltDirectories))
{
TRemoteFile * File = new TRemoteFile();
File->FileName = FileName;
File->Type = FILETYPE_DIRECTORY;
Result->AddObject(FileName, File);
}
else if (FLAGSET(ListType, fltMask) && TFileMasks::IsMask(FileName))
{
UnicodeString FileDirectory = UnixExtractFilePath(FileName);
UnicodeString Directory = FileDirectory;
if (Directory.IsEmpty())
{
Directory = UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory);
}
TRemoteFileList * FileList = NULL;
if (FileLists != NULL)
{
int Index = FileLists->IndexOf(Directory);
if (Index > 0)
{
FileList = dynamic_cast<TRemoteFileList *>(FileLists->Objects[Index]);
}
}
if (FileList == NULL)
{
FileList = FTerminal->CustomReadDirectoryListing(Directory, false);
if (FileLists == NULL)
{
FileLists = new TStringList();
}
FileLists->AddObject(Directory, FileList);
}
TFileMasks Mask;
Mask.SetMask(UnixExtractFileName(FileName));
bool AnyFound = false;
for (int i = 0; i < FileList->Count; i++)
{
TRemoteFile * File = FileList->Files[i];
TFileMasks::TParams Params;
Params.Size = File->Size;
Params.Modification = File->Modification;
if (!File->IsThisDirectory && !File->IsParentDirectory &&
Mask.Matches(File->FileName, false, UnicodeString(), &Params))
{
Result->AddObject(FileDirectory + File->FileName,
FLAGSET(ListType, fltQueryServer) ? File->Duplicate() : NULL);
AnyFound = true;
}
}
if (!AnyFound)
{
NoMatch(Mask.Masks, UnicodeString());
}
}
else
{
TRemoteFile * File = NULL;
if (FLAGSET(ListType, fltQueryServer))
{
FTerminal->ExceptionOnFail = true;
try
{
FTerminal->ReadFile(FileName, File);
if (!File->HaveFullFileName)
{
File->FullFileName = FileName;
}
}
__finally
{
FTerminal->ExceptionOnFail = false;
}
}
Result->AddObject(FileName, File);
}
}
}
catch(...)
{
FreeFileList(Result);
throw;
}
}
__finally
{
if (FileLists != NULL)
{
for (int i = 0; i < FileLists->Count; i++)
{
delete FileLists->Objects[i];
}
delete FileLists;
}
}
return Result;
}
//---------------------------------------------------------------------------
TStrings * __fastcall TScript::CreateLocalFileList(TScriptProcParams * Parameters,
int Start, int End, TFileListType ListType)
{
TStrings * Result = new TStringList();
try
{
for (int i = Start; i <= End; i++)
{
// FindFirstFile called (indirectly) below fails if path ends with slash.
// (it actually won't make a difference functionally as we fall back to adding
// the path as is in "else" branch, but the comment "let it fail later" won't stand)
UnicodeString FileName = ExcludeTrailingBackslash(Parameters->Param[i]);
if (FLAGSET(ListType, fltMask))
{
TSearchRecChecked SearchRec;
int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
UnicodeString Error;
bool AnyFound = false;
if (FindFirstUnchecked(FileName, FindAttrs, SearchRec) == 0)
{
UnicodeString Directory = ExtractFilePath(FileName);
try
{
do
{
if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
{
Result->Add(Directory + SearchRec.Name);
AnyFound = true;
}
}
while (FindNextChecked(SearchRec) == 0);
}
__finally
{
FindClose(SearchRec);
}
}
else
{
if (FileName.LastDelimiter(L"?*") == 0)
{
// no match, and it is not a mask, let it fail latter
Result->Add(FileName);
AnyFound = true;
}
else
{
Error = ListingSysErrorMessage();
}
}
if (!AnyFound)
{
NoMatch(ExtractFileName(FileName), Error);
}
}
else
{
Result->Add(FileName);
}
}
}
catch(...)
{
delete Result;
throw;
}
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TScript::ListingSysErrorMessage()
{
UnicodeString Result;
int LastError = GetLastError();
// System error text for ERROR_FILE_NOT_FOUND is more or less redundant to ours
// SCRIPT_MATCH_NO_MATCH. Also the system error does not look nice/user friendly
// so avoid using it for this frequent case.
if (LastError != ERROR_FILE_NOT_FOUND)
{
Result = SysErrorMessageForError(LastError);
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TScript::NoMatch(const UnicodeString & Mask, const UnicodeString & Error)
{
UnicodeString Message = FMTLOAD(SCRIPT_MATCH_NO_MATCH, (Mask));
if (!Error.IsEmpty())
{
Message += FORMAT(L" (%s)", (Error));
}
if (FFailOnNoMatch)
{
throw Exception(Message);
}
else
{
PrintLine(Message);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::FreeFileList(TStrings * FileList)
{
for (int i = 0; i < FileList->Count; i++)
{
if (FileList->Objects[i] != NULL)
{
TRemoteFile * File = dynamic_cast<TRemoteFile *>(FileList->Objects[i]);
delete File;
}
}
delete FileList;
}
//---------------------------------------------------------------------------
void __fastcall TScript::ConnectTerminal(TTerminal * ATerminal)
{
ATerminal->Open();
}
//---------------------------------------------------------------------------
void __fastcall TScript::Print(const UnicodeString Str)
{
if (FOnPrint != NULL)
{
FOnPrint(this, Str);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::PrintLine(const UnicodeString Str)
{
Log(llOutput, Str);
Print(Str + L"\n");
}
//---------------------------------------------------------------------------
bool __fastcall TScript::HandleExtendedException(Exception * E, TTerminal * ATerminal)
{
bool Result = (OnShowExtendedException != NULL);
if (Result)
{
if (ATerminal == NULL)
{
ATerminal = FTerminal;
}
OnShowExtendedException(ATerminal, E, NULL);
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TScript::CheckSession()
{
if (FTerminal == NULL)
{
throw Exception(LoadStr(SCRIPT_NO_SESSION));
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::NotSupported()
{
throw Exception(LoadStr(NOTSUPPORTED));
}
//---------------------------------------------------------------------------
void __fastcall TScript::CheckParams(TScriptProcParams * Parameters)
{
TScriptCommands::CheckParams(Parameters, false);
}
//---------------------------------------------------------------------------
void __fastcall TScript::TransferParamParams(int & Params, TScriptProcParams * Parameters)
{
Params |= FLAGMASK(!FConfirm, cpNoConfirmation);
if (Parameters->FindSwitch(L"delete"))
{
Params |= cpDelete;
}
if (Parameters->FindSwitch(L"resume"))
{
Params |= cpResume;
}
else if (Parameters->FindSwitch(L"append"))
{
Params |= cpAppend;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::CopyParamParams(TCopyParamType & CopyParam, TScriptProcParams * Parameters)
{
UnicodeString Value;
if (!FWantsProgress)
{
// total size is not visualized, hence it makes no sense to calculate it
CopyParam.CalculateSize = false;
}
if (Parameters->FindSwitch(L"nopreservetime"))
{
CopyParam.PreserveTime = false;
}
if (Parameters->FindSwitch(L"preservetime"))
{
CopyParam.PreserveTime = true;
}
if (Parameters->FindSwitch(L"nopermissions"))
{
CopyParam.PreserveRights = false;
}
if (Parameters->FindSwitch(L"permissions", Value))
{
CopyParam.PreserveRights = true;
CopyParam.Rights.Octal = Value;
}
if (Parameters->FindSwitch(L"speed", Value))
{
int CPSLimit;
if (Value.IsEmpty())
{
CPSLimit = 0;
}
else
{
CPSLimit = StrToInt(Value) * 1024;
if (CPSLimit < 0)
{
CPSLimit = 0;
}
}
CopyParam.CPSLimit = CPSLimit;
}
if (Parameters->FindSwitch(L"transfer", Value))
{
CopyParam.TransferMode = ParseTransferModeName(Value);
}
if (Parameters->FindSwitch(L"filemask", Value))
{
CopyParam.IncludeFileMask = Value;
if (FIncludeFileMaskOptionUsed)
{
PrintLine(LoadStr(SCRIPT_FILEMASK_INCLUDE_EXCLUDE));
}
}
if (Parameters->FindSwitch(L"resumesupport", Value))
{
int ToggleValue = TScriptCommands::FindCommand(ToggleNames,
LENOF(ToggleNames), Value);
if (ToggleValue >= 0)
{
switch (ToggleValue)
{
case Off:
CopyParam.ResumeSupport = rsOff;
break;
case On:
CopyParam.ResumeSupport = rsOn;
break;
default:
FAIL;
break;
}
}
else
{
int ThresholdValue;
if (!TryStrToInt(Value, ThresholdValue))
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"resumesupport", Value)));
}
CopyParam.ResumeSupport = rsSmart;
CopyParam.ResumeThreshold = ThresholdValue * 1024;
}
}
if (Parameters->FindSwitch(L"noneweronly"))
{
CopyParam.NewerOnly = false;
}
if (Parameters->FindSwitch(L"neweronly"))
{
CopyParam.NewerOnly = true;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::ResetTransfer()
{
}
//---------------------------------------------------------------------------
bool __fastcall TScript::EnsureCommandSessionFallback(
TFSCapability Capability, TSessionAction & Action)
{
bool Result = FTerminal->IsCapable[Capability] ||
FTerminal->CommandSessionOpened;
if (!Result)
{
try
{
ConnectTerminal(FTerminal->CommandSession);
Result = true;
}
catch(Exception & E)
{
Action.Rollback(&E);
HandleExtendedException(&E, FTerminal->CommandSession);
Result = false;
}
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TScript::HelpProc(TScriptProcParams * Parameters)
{
UnicodeString Output;
if (Parameters->ParamCount == 0)
{
UnicodeString Command;
UnicodeString Description;
int Index = 0;
while (FCommands->Enumerate(Index, &Command, &Description, NULL))
{
if (!Description.IsEmpty())
{
Output += FORMAT(L"%-8s %s\n", (Command, Description));
}
Index++;
}
}
else
{
for (int i = 1; i <= Parameters->ParamCount; i++)
{
UnicodeString Help;
if (FCommands->Info(Parameters->Param[i], NULL, &Help))
{
Output += Help;
}
else
{
throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Parameters->Param[i])));
}
}
}
Print(Output);
}
//---------------------------------------------------------------------------
void __fastcall TScript::CallProc(TScriptProcParams * Parameters)
{
CheckSession();
if (!FTerminal->IsCapable[fcAnyCommand] &&
!FTerminal->IsCapable[fcSecondaryShell])
{
NotSupported();
}
// this is used only to log failures to open separate shell session,
// the actual call logging is done in TTerminal::AnyCommand
TCallSessionAction Action(
FTerminal->ActionLog, Parameters->ParamsStr, FTerminal->CurrentDirectory);
if (EnsureCommandSessionFallback(fcAnyCommand, Action))
{
Action.Cancel();
FTerminal->AnyCommand(Parameters->ParamsStr, TerminalCaptureLog);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::EchoProc(TScriptProcParams * Parameters)
{
PrintLine(Parameters->ParamsStr);
}
//---------------------------------------------------------------------------
void __fastcall TScript::StatProc(TScriptProcParams * Parameters)
{
CheckSession();
UnicodeString Path = Parameters->Param[1];
FTerminal->ExceptionOnFail = true;
TRemoteFile * File = NULL;
try
{
File = FTerminal->ReadFileListing(Path);
PrintLine(File->ListingStr);
}
__finally
{
FTerminal->ExceptionOnFail = false;
delete File;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::ChecksumProc(TScriptProcParams * Parameters)
{
CheckSession();
if (!FTerminal->IsCapable[fcCalculatingChecksum])
{
NotSupported();
}
UnicodeString Alg = Parameters->Param[1];
std::unique_ptr<TStrings> Checksums(new TStringList());
TStrings * FileList = CreateFileList(Parameters, 2, 2, fltQueryServer);
FTerminal->ExceptionOnFail = true;
try
{
if ((FileList->Count != 1) ||
NOT_NULL(dynamic_cast<TRemoteFile *>(FileList->Objects[0]))->IsDirectory)
{
throw Exception(FMTLOAD(NOT_FILE_ERROR, (FileList->Strings[0])));
}
FTerminal->CalculateFilesChecksum(Alg, FileList, Checksums.get(), NULL);
if (ALWAYS_TRUE(Checksums->Count == 1))
{
PrintLine(FORMAT(L"%s %s", (Checksums->Strings[0], FileList->Strings[0])));
}
}
__finally
{
FTerminal->ExceptionOnFail = false;
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::TerminalCaptureLog(const UnicodeString & AddedLine,
TCaptureOutputType OutputType)
{
if ((OutputType == cotOutput) || (OutputType == cotError))
{
PrintLine(AddedLine);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::PwdProc(TScriptProcParams * /*Parameters*/)
{
CheckSession();
PrintLine(FTerminal->CurrentDirectory);
TCwdSessionAction Action(FTerminal->ActionLog, FTerminal->CurrentDirectory);
}
//---------------------------------------------------------------------------
void __fastcall TScript::CdProc(TScriptProcParams * Parameters)
{
CheckSession();
if (Parameters->ParamCount == 0)
{
FTerminal->HomeDirectory();
}
else
{
FTerminal->ChangeDirectory(Parameters->Param[1]);
}
PrintLine(FTerminal->CurrentDirectory);
}
//---------------------------------------------------------------------------
void __fastcall TScript::LsProc(TScriptProcParams * Parameters)
{
CheckSession();
UnicodeString Directory;
TFileMasks Mask;
bool HaveMask = false;
if (Parameters->ParamCount > 0)
{
Directory = Parameters->Param[1];
UnicodeString MaskStr = UnixExtractFileName(Directory);
HaveMask = TFileMasks::IsMask(MaskStr);
if (HaveMask)
{
Mask.SetMask(MaskStr);
Directory = UnixExtractFilePath(Directory);
}
}
if (Directory.IsEmpty())
{
Directory = FTerminal->CurrentDirectory;
}
TRemoteFileList * FileList = FTerminal->ReadDirectoryListing(Directory, Mask);
// on error user may select "skip", then we get NULL
if (FileList != NULL)
{
try
{
if (FileList->Count > 0)
{
for (int i = 0; i < FileList->Count; i++)
{
PrintLine(FileList->Files[i]->ListingStr);
}
}
else
{
if (HaveMask)
{
NoMatch(Mask.Masks, UnicodeString());
}
}
}
__finally
{
delete FileList;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::RmProc(TScriptProcParams * Parameters)
{
CheckSession();
TStrings * FileList = CreateFileList(
Parameters, 1, Parameters->ParamCount,
(TFileListType)(fltQueryServer | fltMask));
try
{
FTerminal->DeleteFiles(FileList);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::RmDirProc(TScriptProcParams * Parameters)
{
CheckSession();
TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount, fltDirectories);
try
{
FTerminal->DeleteFiles(FileList);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::MvProc(TScriptProcParams * Parameters)
{
CheckSession();
TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount - 1,
fltMask);
try
{
assert(Parameters->ParamCount >= 1);
UnicodeString Target = Parameters->Param[Parameters->ParamCount];
UnicodeString TargetDirectory = UnixExtractFilePath(Target);
UnicodeString FileMask = UnixExtractFileName(Target);
FTerminal->MoveFiles(FileList, TargetDirectory, FileMask);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::ChModProc(TScriptProcParams * Parameters)
{
CheckSession();
if (!FTerminal->IsCapable[fcModeChanging])
{
NotSupported();
}
TStrings * FileList = CreateFileList(Parameters, 2, Parameters->ParamCount,
fltMask);
try
{
TRemoteProperties Properties;
Properties.Valid = TValidProperties() << vpRights;
Properties.Rights.Octal = Parameters->Param[1];
FTerminal->ChangeFilesProperties(FileList, &Properties);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::LnProc(TScriptProcParams * Parameters)
{
CheckSession();
assert(Parameters->ParamCount == 2);
FTerminal->CreateLink(Parameters->Param[2], Parameters->Param[1], true);
}
//---------------------------------------------------------------------------
void __fastcall TScript::MkDirProc(TScriptProcParams * Parameters)
{
CheckSession();
FTerminal->CreateDirectory(Parameters->Param[1]);
}
//---------------------------------------------------------------------------
void __fastcall TScript::GetProc(TScriptProcParams * Parameters)
{
CheckSession();
ResetTransfer();
int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
TStrings * FileList = CreateFileList(Parameters, 1, LastFileParam,
(TFileListType)(fltQueryServer | fltMask));
try
{
CheckDefaultCopyParam();
TCopyParamType CopyParam = FCopyParam;
UnicodeString TargetDirectory;
if (Parameters->ParamCount == 1)
{
TargetDirectory = GetCurrentDir();
CopyParam.FileMask = L"";
}
else
{
UnicodeString Target = Parameters->Param[Parameters->ParamCount];
TargetDirectory = ExtractFilePath(Target);
if (TargetDirectory.IsEmpty())
{
TargetDirectory = GetCurrentDir();
}
CopyParam.FileMask = ExtractFileName(Target);
}
int Params = 0;
TransferParamParams(Params, Parameters);
CopyParamParams(CopyParam, Parameters);
CheckParams(Parameters);
FTerminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, Params);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::PutProc(TScriptProcParams * Parameters)
{
CheckSession();
ResetTransfer();
int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
TStrings * FileList = CreateLocalFileList(Parameters, 1, LastFileParam, fltMask);
try
{
CheckDefaultCopyParam();
TCopyParamType CopyParam = FCopyParam;
UnicodeString TargetDirectory;
if (Parameters->ParamCount == 1)
{
TargetDirectory = FTerminal->CurrentDirectory;
CopyParam.FileMask = L"";
}
else
{
UnicodeString Target = Parameters->Param[Parameters->ParamCount];
TargetDirectory = UnixExtractFilePath(Target);
if (TargetDirectory.IsEmpty())
{
TargetDirectory = FTerminal->CurrentDirectory;
}
CopyParam.FileMask = UnixExtractFileName(Target);
}
int Params = 0;
TransferParamParams(Params, Parameters);
CopyParamParams(CopyParam, Parameters);
CheckParams(Parameters);
FTerminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, Params);
}
__finally
{
FreeFileList(FileList);
}
}
//---------------------------------------------------------------------------
TTransferMode __fastcall TScript::ParseTransferModeName(UnicodeString Name)
{
assert((tmBinary == 0) && (tmAscii == 1) && (tmAutomatic == 2));
int Value = TScriptCommands::FindCommand(TransferModeNames,
LENOF(TransferModeNames), Name);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"transfer", Name)));
}
return (TTransferMode)Value;
}
//---------------------------------------------------------------------------
void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString ValueName)
{
enum { Echo, Batch, Confirm, Transfer, SynchDelete, Exclude, Include, ReconnectTime, FailOnNoMatch };
static const wchar_t * Names[] = { L"echo", L"batch", L"confirm", L"transfer",
L"synchdelete", L"exclude", L"include", L"reconnecttime", L"failonnomatch" };
assert((BatchOff == 0) && (BatchOn == 1) && (BatchAbort == 2) && (BatchContinue == 3));
static const wchar_t * BatchModeNames[] = { L"off", L"on", L"abort", L"continue" };
int Option = -1;
if (!OptionName.IsEmpty())
{
Option = TScriptCommands::FindCommand(Names, LENOF(Names), OptionName);
if (Option < 0)
{
throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (OptionName)));
}
else
{
OptionName = Names[Option];
}
}
#define OPT(OPT) ((Option < 0) || (Option == OPT))
const wchar_t * ListFormat = L"%-15s %-10s";
bool SetValue = !ValueName.IsEmpty();
bool PrintReconnectTime = false;
if (OPT(Echo))
{
if (SetValue)
{
int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
FEcho = (Value == On);
}
PrintLine(FORMAT(ListFormat, (Names[Echo], ToggleNames[FEcho ? On : Off])));
}
if (OPT(Batch))
{
if (SetValue)
{
int Value = TScriptCommands::FindCommand(BatchModeNames, LENOF(BatchModeNames), ValueName);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
FBatch = (TBatchMode)Value;
FInteractiveBatch = FBatch;
if (SetValue && (FBatch != BatchOff) && (FSessionReopenTimeout == 0))
{
// keep in sync with Session constructor in .NET
FSessionReopenTimeout = 2 * MSecsPerSec * SecsPerMin; // 2 mins
PrintReconnectTime = true;
}
}
PrintLine(FORMAT(ListFormat, (Names[Batch], BatchModeNames[FBatch])));
}
if (OPT(Confirm))
{
if (SetValue)
{
int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
FConfirm = (Value == On);
FInteractiveConfirm = FConfirm;
}
PrintLine(FORMAT(ListFormat, (Names[Confirm], ToggleNames[FConfirm ? On : Off])));
}
// omit the option in listing
if (Option == Transfer)
{
if (SetValue)
{
FCopyParam.TransferMode = ParseTransferModeName(ValueName);
}
assert(FCopyParam.TransferMode < (TTransferMode)LENOF(TransferModeNames));
const wchar_t * Value = TransferModeNames[FCopyParam.TransferMode];
PrintLine(FORMAT(ListFormat, (Names[Transfer], Value)));
}
// omit the option in listing
if (Option == SynchDelete)
{
if (SetValue)
{
int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
FSynchronizeParams =
(FSynchronizeParams & ~TTerminal::spDelete) |
FLAGMASK(Value == On, TTerminal::spDelete);
}
PrintLine(FORMAT(ListFormat, (Names[SynchDelete],
ToggleNames[FLAGSET(FSynchronizeParams, TTerminal::spDelete) ? On : Off])));
}
static const wchar_t * Clear = L"clear";
// omit the option in listing
if (Option == Include)
{
if (SetValue)
{
FCopyParam.IncludeFileMask =
(ValueName == Clear ? UnicodeString() : ValueName);
FIncludeFileMaskOptionUsed = (ValueName != Clear);
}
PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
}
// omit the option in listing
if (Option == Exclude)
{
if (SetValue)
{
// will throw if ValueName already includes IncludeExcludeFileMasksDelimiter
FCopyParam.IncludeFileMask =
(ValueName == Clear ? UnicodeString() : UnicodeString(IncludeExcludeFileMasksDelimiter) + ValueName);
FIncludeFileMaskOptionUsed = (ValueName != Clear);
}
PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
}
if (OPT(ReconnectTime) || PrintReconnectTime)
{
if (SetValue && !PrintReconnectTime)
{
int Value;
if (AnsiSameText(ValueName, ToggleNames[Off]))
{
Value = 0;
}
else
{
if (!TryStrToInt(ValueName, Value))
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
else
{
Value *= MSecsPerSec;
}
}
FSessionReopenTimeout = Value;
}
if (FSessionReopenTimeout == 0)
{
ValueName = ToggleNames[Off];
}
else
{
ValueName = IntToStr(FSessionReopenTimeout / MSecsPerSec);
}
PrintLine(FORMAT(ListFormat, (Names[ReconnectTime], ValueName)));
}
if (OPT(FailOnNoMatch))
{
if (SetValue)
{
int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
if (Value < 0)
{
throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
}
FFailOnNoMatch = (Value == On);
}
PrintLine(FORMAT(ListFormat, (Names[FailOnNoMatch], ToggleNames[FFailOnNoMatch ? On : Off])));
}
#undef OPT
}
//---------------------------------------------------------------------------
void __fastcall TScript::OptionProc(TScriptProcParams * Parameters)
{
UnicodeString OptionName;
UnicodeString ValueName;
if (Parameters->ParamCount >= 1)
{
OptionName = Parameters->Param[1];
}
if (Parameters->ParamCount >= 2)
{
ValueName = Parameters->Param[2];
}
OptionImpl(OptionName, ValueName);
}
//---------------------------------------------------------------------------
void __fastcall TScript::AsciiProc(TScriptProcParams * /*Parameters*/)
{
OptionImpl(L"transfer", L"ascii");
}
//---------------------------------------------------------------------------
void __fastcall TScript::BinaryProc(TScriptProcParams * /*Parameters*/)
{
OptionImpl(L"transfer", L"binary");
}
//---------------------------------------------------------------------------
void __fastcall TScript::SynchronizeDirectories(TScriptProcParams * Parameters,
UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int FirstParam)
{
if (Parameters->ParamCount >= FirstParam)
{
LocalDirectory = Parameters->Param[FirstParam];
}
else
{
LocalDirectory = GetCurrentDir();
}
if (Parameters->ParamCount >= FirstParam + 1)
{
RemoteDirectory = Parameters->Param[FirstParam + 1];
}
else
{
RemoteDirectory = FTerminal->CurrentDirectory;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TScript::SynchronizeFileRecord(
const UnicodeString & RootDirectory, const TSynchronizeChecklist::TItem * Item, bool Local)
{
const TSynchronizeChecklist::TItem::TFileInfo & FileInfo =
Local ? Item->Local : Item->Remote;
UnicodeString Path;
if (Local)
{
Path = IncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
}
else
{
Path = UnixIncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
}
if (SameText(RootDirectory, Path.SubString(1, RootDirectory.Length())))
{
Path[1] = L'.';
Path.Delete(2, RootDirectory.Length() - 2);
}
UnicodeString Result;
if (Item->IsDirectory)
{
if (Local)
{
Result = IncludeTrailingBackslash(Path);
}
else
{
Result = UnixIncludeTrailingBackslash(Path);
}
}
else
{
UnicodeString SizeStr = IntToStr(FileInfo.Size);
UnicodeString ModificationStr =
::ModificationStr(FileInfo.Modification, FileInfo.ModificationFmt);
Result = FORMAT("%s [%s, %s]", (Path, SizeStr, ModificationStr));
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TScript::SynchronizePreview(
UnicodeString LocalDirectory, UnicodeString RemoteDirectory,
TSynchronizeChecklist * Checklist)
{
LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
for (int Index = 0; (Index < Checklist->Count); Index++)
{
const TSynchronizeChecklist::TItem * Item = Checklist->Item[Index];
if (Item->Checked)
{
UnicodeString Message;
UnicodeString LocalRecord = SynchronizeFileRecord(LocalDirectory, Item, true);
UnicodeString RemoteRecord = SynchronizeFileRecord(RemoteDirectory, Item, false);
switch (Item->Action)
{
case TSynchronizeChecklist::saUploadNew:
Message =
FMTLOAD(SCRIPT_SYNC_UPLOAD_NEW, (LocalRecord));
break;
case TSynchronizeChecklist::saDownloadNew:
Message =
FMTLOAD(SCRIPT_SYNC_DOWNLOAD_NEW, (RemoteRecord));
break;
case TSynchronizeChecklist::saUploadUpdate:
Message =
FMTLOAD(SCRIPT_SYNC_UPLOAD_UPDATE,
(LocalRecord, RemoteRecord));
break;
case TSynchronizeChecklist::saDownloadUpdate:
Message =
FMTLOAD(SCRIPT_SYNC_DOWNLOAD_UPDATE,
(RemoteRecord, LocalRecord));
break;
case TSynchronizeChecklist::saDeleteRemote:
Message =
FMTLOAD(SCRIPT_SYNC_DELETE_REMOTE, (RemoteRecord));
break;
case TSynchronizeChecklist::saDeleteLocal:
Message =
FMTLOAD(SCRIPT_SYNC_DELETE_LOCAL, (LocalRecord));
break;
default:
FAIL;
}
PrintLine(Message);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
{
CheckSession();
ResetTransfer();
static const wchar_t * ModeNames[] = { L"remote", L"local", L"both" };
UnicodeString ModeName = Parameters->Param[1];
assert(FSynchronizeMode < 0);
FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
try
{
if (FSynchronizeMode < 0)
{
throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
}
UnicodeString LocalDirectory;
UnicodeString RemoteDirectory;
SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 2);
CheckDefaultCopyParam();
TCopyParamType CopyParam = FCopyParam;
CopyParamParams(CopyParam, Parameters);
CheckDefaultSynchronizeParams();
int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
UnicodeString Value;
if (Parameters->FindSwitch(L"delete"))
{
SynchronizeParams |= TTerminal::spDelete;
}
if (Parameters->FindSwitch(L"mirror") &&
(FSynchronizeMode != TTerminal::smBoth))
{
SynchronizeParams |= TTerminal::spMirror;
}
if (Parameters->FindSwitch(L"criteria", Value))
{
enum { None, Time, Size, Either, EitherBoth };
static const wchar_t * CriteriaNames[] = { L"none", L"time", L"size", L"either", L"both" };
int Criteria = TScriptCommands::FindCommand(CriteriaNames, LENOF(CriteriaNames), Value);
switch (Criteria)
{
case None:
SynchronizeParams |= TTerminal::spNotByTime;
SynchronizeParams &= ~TTerminal::spBySize;
break;
case Time:
SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
break;
case Size:
SynchronizeParams |= TTerminal::spNotByTime | TTerminal::spBySize;
break;
case Either:
case EitherBoth:
SynchronizeParams &= ~TTerminal::spNotByTime;
SynchronizeParams |= TTerminal::spBySize;
break;
}
}
bool Preview = Parameters->FindSwitch(L"preview");
// enforce rules
if (FSynchronizeMode == TTerminal::smBoth)
{
SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
}
CheckParams(Parameters);
PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_COLLECTING));
TSynchronizeChecklist * Checklist =
FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
&CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL);
try
{
bool AnyChecked = false;
for (int Index = 0; !AnyChecked && (Index < Checklist->Count); Index++)
{
AnyChecked = Checklist->Item[Index]->Checked;
}
if (AnyChecked)
{
if (Preview)
{
PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_CHECKLIST));
SynchronizePreview(LocalDirectory, RemoteDirectory, Checklist);
}
else
{
PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_SYNCHRONIZING));
FTerminal->SynchronizeApply(Checklist, LocalDirectory, RemoteDirectory,
&CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
}
}
else
{
PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_NODIFFERENCE));
}
}
__finally
{
delete Checklist;
}
}
__finally
{
FSynchronizeMode = -1;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::Synchronize(const UnicodeString LocalDirectory,
const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
int SynchronizeParams, TSynchronizeChecklist ** Checklist)
{
try
{
FKeepingUpToDate = true;
TSynchronizeChecklist * AChecklist =
FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
&CopyParam, SynchronizeParams, NULL, NULL);
try
{
if (AChecklist->Count > 0)
{
FTerminal->SynchronizeApply(AChecklist, LocalDirectory, RemoteDirectory,
&CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
}
}
__finally
{
if (Checklist == NULL)
{
delete AChecklist;
}
else
{
*Checklist = AChecklist;
}
}
// to break line after the last transfer (if any);
Print(L"");
FKeepingUpToDate = false;
}
catch(Exception & E)
{
FKeepingUpToDate = false;
HandleExtendedException(&E);
throw;
}
}
//---------------------------------------------------------------------------
void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
{
if (OnSynchronizeStartStop == NULL)
{
Abort();
}
CheckSession();
ResetTransfer();
UnicodeString LocalDirectory;
UnicodeString RemoteDirectory;
SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
CheckDefaultSynchronizeParams();
int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
TTerminal::spSubDirs;
if (Parameters->FindSwitch(L"delete"))
{
SynchronizeParams |= TTerminal::spDelete;
}
CheckDefaultCopyParam();
TCopyParamType CopyParam = FCopyParam;
CopyParamParams(CopyParam, Parameters);
CheckParams(Parameters);
PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory, CopyParam, SynchronizeParams);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
__fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions,
bool LimitedOutput) :
TScript(LimitedOutput)
{
assert(StoredSessions != NULL);
FOnInput = NULL;
FOnTerminalPromptUser = NULL;
FOnShowExtendedException = NULL;
FOnTerminalQueryUser = NULL;
FStoredSessions = StoredSessions;
FTerminalList = new TTerminalList(Configuration);
FOnQueryCancel = NULL;
FContinue = true;
OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
FCommands->Register(L"exit", SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
FCommands->Register(L"bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
FCommands->Register(L"open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP6, &OpenProc, 0, -1, true);
FCommands->Register(L"close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1, false);
FCommands->Register(L"session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1, false);
FCommands->Register(L"lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0, false);
FCommands->Register(L"lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1, false);
FCommands->Register(L"lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP2, &LLsProc, 0, 1, false);
}
//---------------------------------------------------------------------------
__fastcall TManagementScript::~TManagementScript()
{
while (FTerminalList->Count > 0)
{
FreeTerminal(FTerminalList->Terminals[0]);
}
delete FTerminalList;
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::FreeTerminal(TTerminal * ATerminal)
{
TSessionData * Data = StoredSessions->FindSame(ATerminal->SessionData);
if (Data != NULL)
{
ATerminal->SessionData->RemoteDirectory = ATerminal->CurrentDirectory;
bool Changed = false;
if (ATerminal->SessionData->UpdateDirectories)
{
Data->RemoteDirectory = ATerminal->SessionData->RemoteDirectory;
Changed = true;
}
if (Changed)
{
// only modified, implicit
StoredSessions->Save(false, false);
}
}
FTerminalList->FreeTerminal(ATerminal);
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::Input(const UnicodeString Prompt,
UnicodeString & Str, bool AllowEmpty)
{
do
{
Str = L"";
if (FOnInput != NULL)
{
FOnInput(this, Prompt, Str);
}
else
{
Abort();
}
}
while (Str.Trim().IsEmpty() && !AllowEmpty);
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::PrintProgress(bool First, const UnicodeString Str)
{
if (FOnPrintProgress != NULL)
{
FOnPrintProgress(this, First, Str);
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::ResetTransfer()
{
TScript::ResetTransfer();
FLastProgressFile = L"";
FLastProgressTime = 0;
FLastProgressEventTime = 0;
FLastProgressMessage = L"";
}
//---------------------------------------------------------------------------
bool __fastcall TManagementScript::QueryCancel()
{
bool Result = false;
if (OnQueryCancel != NULL)
{
OnQueryCancel(this, Result);
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalInformation(TTerminal * ATerminal,
const UnicodeString & Str, bool /*Status*/, int Phase)
{
assert(ATerminal != NULL);
if ((Phase < 0) && (ATerminal->Status == ssOpening))
{
PrintLine(Str);
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalPromptUser(TTerminal * ATerminal,
TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
TStrings * Results, bool & Result, void * Arg)
{
// When authentication using stored password fails,
// do not ask user for another password.
if ((!ATerminal->StoredCredentialsTried ||
!IsAuthenticationPrompt(Kind) ||
(Prompts->Count == 0)) && // allow instructions-only prompts
(OnTerminalPromptUser != NULL))
{
OnTerminalPromptUser(ATerminal, Kind, Name, Instructions, Prompts, Results, Result, Arg);
}
}
//---------------------------------------------------------------------------
bool __fastcall TManagementScript::Synchronizing()
{
return (FKeepingUpToDate || (FSynchronizeMode >= 0));
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::ShowPendingProgress()
{
if (!FSynchronizeIntro.IsEmpty())
{
if (Synchronizing())
{
PrintLine(FSynchronizeIntro);
}
FSynchronizeIntro = L"";
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalOperationProgress(
TFileOperationProgressType & ProgressData)
{
if ((ProgressData.Operation == foCopy) ||
(ProgressData.Operation == foMove))
{
if (ProgressData.InProgress && ProgressData.FileInProgress &&
!ProgressData.FileName.IsEmpty())
{
bool DoPrint = false;
bool First = false;
UnicodeString ProgressFileName = ProgressData.FileName;
if (ProgressData.Side == osLocal)
{
ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
}
else
{
ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
}
if (ProgressFileName != FLastProgressFile)
{
First = true;
DoPrint = true;
ShowPendingProgress();
}
time_t Time = time(NULL);
if ((OnProgress != NULL) && WantsProgress &&
(DoPrint || (FLastProgressEventTime != Time) || ProgressData.IsTransferDone()))
{
FLastProgressEventTime = Time;
TScriptProgress Progress;
Progress.Operation = ProgressData.Operation;
Progress.Side = ProgressData.Side;
Progress.FileName = ProgressData.FileName;
Progress.Directory = ProgressData.Directory;
Progress.OverallProgress = ProgressData.OverallProgress();
Progress.FileProgress = ProgressData.TransferProgress();
Progress.CPS = ProgressData.CPS();
OnProgress(this, Progress);
}
if (!DoPrint && ((FLastProgressTime != Time) || ProgressData.IsTransferDone()))
{
DoPrint = true;
}
if (DoPrint)
{
static int WidthFileName = 25;
UnicodeString FileName;
if (FLimitedOutput)
{
FileName = MinimizeName(ProgressFileName, WidthFileName,
ProgressData.Side == osRemote);
}
else
{
FileName = ProgressFileName;
}
UnicodeString TransferedSizeStr;
if (ProgressData.TransferedSize < 1024)
{
TransferedSizeStr = FORMAT("%d B", (static_cast<int>(ProgressData.TransferedSize)));
}
else
{
TransferedSizeStr = FORMAT("%d KB", (static_cast<int>(ProgressData.TransferedSize / 1024)));
}
UnicodeString ProgressMessage = FORMAT(L"%-*s | %14s | %6.1f KB/s | %-6.6s | %3d%%",
(WidthFileName, FileName,
TransferedSizeStr,
static_cast<float>(ProgressData.CPS()) / 1024,
ProgressData.AsciiTransfer ? L"ascii" : L"binary",
ProgressData.TransferProgress()));
if (FLastProgressMessage != ProgressMessage)
{
FLastProgressTime = Time;
PrintProgress(First, ProgressMessage);
FLastProgressMessage = ProgressMessage;
FLastProgressFile = ProgressFileName;
}
}
}
else
{
FLastProgressFile = L"";
}
}
if (QueryCancel())
{
ProgressData.Cancel = csCancel;
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalOperationFinished(
TFileOperation Operation, TOperationSide /*Side*/,
bool /*Temp*/, const UnicodeString & FileName, Boolean Success,
TOnceDoneOperation & /*OnceDoneOperation*/)
{
if (Success &&
(Operation != foCalculateSize) && (Operation != foCalculateChecksum) &&
(Operation != foCopy) && (Operation != foMove))
{
ShowPendingProgress();
// For FKeepingUpToDate we should send events to synchronize controller eventually.
if (Synchronizing() && (Operation == foDelete))
{
// Note that this is duplicated with "keep up to date" log.
PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
}
else
{
PrintLine(FileName);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalSynchronizeDirectory(
const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
bool & Continue, bool Collect)
{
int SynchronizeMode = FSynchronizeMode;
if (FKeepingUpToDate)
{
SynchronizeMode = TTerminal::smRemote;
}
UnicodeString Arrow;
switch (SynchronizeMode)
{
case TTerminal::smRemote:
Arrow = L"=>";
break;
case TTerminal::smLocal:
Arrow = L"<=";
break;
case TTerminal::smBoth:
Arrow = L"<=>";
break;
}
UnicodeString Progress = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
if (Collect)
{
PrintProgress(false, Progress);
}
else
{
FSynchronizeIntro = Progress;
}
if (QueryCancel())
{
Continue = false;
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::TerminalInitializeLog(TObject * Sender)
{
TTerminal * ATerminal = dynamic_cast<TTerminal *>(Sender);
if (ALWAYS_TRUE(ATerminal != NULL))
{
LogPendingLines(ATerminal);
}
}
//---------------------------------------------------------------------------
TTerminal * __fastcall TManagementScript::FindSession(const UnicodeString Index)
{
int i = StrToIntDef(Index, -1);
if ((i <= 0) || (i > FTerminalList->Count))
{
throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
}
else
{
return FTerminalList->Terminals[i - 1];
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::PrintActiveSession()
{
assert(FTerminal != NULL);
PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
(FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
}
//---------------------------------------------------------------------------
bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
TTerminal * ATerminal)
{
bool Result = TScript::HandleExtendedException(E, ATerminal);
if (ATerminal == NULL)
{
ATerminal = FTerminal;
}
if ((ATerminal != NULL) && (ATerminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
{
try
{
DoClose(ATerminal);
}
catch(...)
{
// ignore disconnect errors
}
}
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TManagementScript::GetLogCmd(const UnicodeString & FullCommand,
const UnicodeString & Command, const UnicodeString & Params)
{
UnicodeString Result = FullCommand;
if (SameText(FCommands->ResolveCommand(Command), L"open") &&
!Configuration->LogSensitive)
{
UnicodeString AParams = Params;
std::unique_ptr<TScriptProcParams> Parameters(new TScriptProcParams(L""));
UnicodeString Url;
UnicodeString MaskedParamsPre;
UnicodeString MaskedParamsPost;
UnicodeString Param;
UnicodeString RawParam;
bool AnySensitiveOption = false;
while (CutToken(AParams, Param, &RawParam))
{
Parameters->Add(Param);
if ((Parameters->ParamCount == 1) && Url.IsEmpty())
{
Url = Param;
}
else
{
UnicodeString & MaskedParams = Url.IsEmpty() ? MaskedParamsPre : MaskedParamsPost;
UnicodeString Switch;
if (Parameters->WasSwitchAdded(Switch) &&
TSessionData::IsSensitiveOption(Switch))
{
// We should use something like TProgramParams::FormatSwitch here
RawParam = FORMAT(L"-%s=***", (Switch));
AnySensitiveOption = true;
}
AddToList(MaskedParams, RawParam, L" ");
}
}
if (!Url.IsEmpty() || AnySensitiveOption)
{
UnicodeString MaskedUrl;
bool DefaultsOnly;
if (!Url.IsEmpty())
{
std::unique_ptr<TSessionData> Data(
FStoredSessions->ParseUrl(Url, Parameters.get(), DefaultsOnly, NULL, NULL, &MaskedUrl));
}
if ((Url != MaskedUrl) || AnySensitiveOption)
{
Result = Command;
// AddToList is noop, when respective component is empty
AddToList(Result, MaskedParamsPre, L" ");
AddToList(Result, MaskedUrl, L" ");
AddToList(Result, MaskedParamsPost, L" ");
}
}
}
return TScript::GetLogCmd(Result, Command, Params);
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::Connect(const UnicodeString Session,
TOptions * Options, bool CheckParams)
{
try
{
bool DefaultsOnly;
if (FStoredSessions->IsFolder(Session) ||
FStoredSessions->IsWorkspace(Session))
{
throw Exception(LoadStr(CANNOT_OPEN_SESSION_FOLDER));
}
TSessionData * Data = FStoredSessions->ParseUrl(Session, Options, DefaultsOnly);
try
{
if (CheckParams)
{
if (Options->ParamCount > 1)
{
throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"open")));
}
TScriptCommands::CheckParams(Options, false);
}
assert(Data != NULL);
if (!Data->CanLogin || DefaultsOnly)
{
if (Data->HostName.IsEmpty())
{
UnicodeString Value;
Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
Data->HostName = Value;
}
assert(Data->CanLogin);
}
TTerminal * ATerminal = FTerminalList->NewTerminal(Data);
try
{
ATerminal->AutoReadDirectory = false;
ATerminal->OnInformation = TerminalInformation;
ATerminal->OnPromptUser = TerminalPromptUser;
ATerminal->OnShowExtendedException = OnShowExtendedException;
ATerminal->OnQueryUser = OnTerminalQueryUser;
ATerminal->OnProgress = TerminalOperationProgress;
ATerminal->OnFinished = TerminalOperationFinished;
ATerminal->OnInitializeLog = TerminalInitializeLog;
ConnectTerminal(ATerminal);
}
catch(Exception & E)
{
// make sure errors (mainly fatal ones) are associated
// with this terminal, not the last active one
bool Handled = HandleExtendedException(&E, ATerminal);
FTerminalList->FreeTerminal(ATerminal);
ATerminal = NULL;
if (!Handled)
{
throw;
}
}
if (ATerminal != NULL)
{
FTerminal = ATerminal;
if (!Data->LocalDirectory.IsEmpty())
{
try
{
DoChangeLocalDirectory(ExpandFileName(Data->LocalDirectory));
}
catch(Exception & E)
{
if (!HandleExtendedException(&E))
{
throw;
}
}
}
PrintActiveSession();
}
}
__finally
{
delete Data;
}
}
catch(Exception & E)
{
if (!HandleExtendedException(&E))
{
throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::DoClose(TTerminal * ATerminal)
{
int Index = FTerminalList->IndexOf(ATerminal);
assert(Index >= 0);
bool WasActiveTerminal = (FTerminal == ATerminal);
try
{
if (ATerminal->Active)
{
ATerminal->Close();
}
UnicodeString SessionName = ATerminal->SessionData->SessionName;
FreeTerminal(ATerminal);
if (WasActiveTerminal)
{
FTerminal = NULL;
}
PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
}
__finally
{
if (WasActiveTerminal)
{
if (FTerminalList->Count > 0)
{
if (Index < FTerminalList->Count)
{
FTerminal = FTerminalList->Terminals[Index];
}
else
{
FTerminal = FTerminalList->Terminals[0];
}
PrintActiveSession();
}
else
{
PrintLine(LoadStr(SCRIPT_NO_SESSION));
}
}
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::DoChangeLocalDirectory(UnicodeString Directory)
{
if (!SetCurrentDir(ApiPath(Directory)))
{
throw EOSExtException(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
{
FContinue = false;
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
{
Connect(Parameters->ParamCount > 0 ? Parameters->Param[1] : UnicodeString(),
Parameters, true);
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
{
CheckSession();
TTerminal * ATerminal;
if (Parameters->ParamCount == 0)
{
ATerminal = FTerminal;
}
else
{
ATerminal = FindSession(Parameters->Param[1]);
}
DoClose(ATerminal);
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
{
CheckSession();
if (Parameters->ParamCount == 0)
{
for (int i = 0; i < FTerminalList->Count; i++)
{
PrintLine(FORMAT(L"%3d %s",
(i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
}
PrintActiveSession();
}
else
{
FTerminal = FindSession(Parameters->Param[1]);
PrintActiveSession();
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
{
PrintLine(GetCurrentDir());
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
{
assert(Parameters->ParamCount == 1);
DoChangeLocalDirectory(Parameters->Param[1]);
PrintLine(GetCurrentDir());
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
{
UnicodeString Directory;
UnicodeString Mask;
if (Parameters->ParamCount > 0)
{
Directory = Parameters->Param[1];
Mask = ExtractFileName(Directory);
if (TFileMasks::IsMask(Mask))
{
Directory = ExtractFilePath(Directory);
}
else
{
Mask = L"";
}
}
if (Directory.IsEmpty())
{
Directory = GetCurrentDir();
}
if (Mask.IsEmpty())
{
Mask = L"*.*";
}
TSearchRecChecked SearchRec;
int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
if (FindFirstUnchecked(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
{
NoMatch(Mask, ListingSysErrorMessage());
}
else
{
try
{
UnicodeString TimeFormat = FixedLenDateTimeFormat(FormatSettings.ShortTimeFormat);
UnicodeString DateFormat = FixedLenDateTimeFormat(FormatSettings.ShortDateFormat);
int DateLen = 0;
int TimeLen = 0;
bool First = true;
do
{
if (SearchRec.Name != L".")
{
TDateTime DateTime = SearchRec.TimeStamp;
UnicodeString TimeStr = FormatDateTime(TimeFormat, DateTime);
UnicodeString DateStr = FormatDateTime(DateFormat, DateTime);
if (First)
{
if (TimeLen < TimeStr.Length())
{
TimeLen = TimeStr.Length();
}
if (DateLen < DateStr.Length())
{
DateLen = DateStr.Length();
}
First = false;
}
UnicodeString SizeStr;
if (FLAGSET(SearchRec.Attr, faDirectory))
{
SizeStr = L"<DIR>";
}
else
{
SizeStr = FORMAT(L"%14.0n", (double(SearchRec.Size)));
}
PrintLine(FORMAT(L"%-*s %-*s %-14s %s", (
DateLen, DateStr, TimeLen, TimeStr, SizeStr, SearchRec.Name)));
}
}
while (FindNextChecked(SearchRec) == 0);
}
__finally
{
FindClose(SearchRec);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TManagementScript::ReflectSettings()
{
for (int i = 0; i < FTerminalList->Count; i++)
{
FTerminalList->Terminals[i]->ReflectSettings();
}
}
//---------------------------------------------------------------------------
| pmverma/winscp | source/core/Script.cpp | C++ | gpl-3.0 | 77,623 |
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.lagis.report;
import javax.swing.JFrame;
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
public class ReportSwingWorkerDialog extends javax.swing.JDialog {
//~ Instance fields --------------------------------------------------------
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
//~ Constructors -----------------------------------------------------------
/**
* Creates new form ReportSwingWorkerDialog.
*
* @param parent DOCUMENT ME!
* @param modal DOCUMENT ME!
*/
public ReportSwingWorkerDialog(final java.awt.Frame parent, final boolean modal) {
super(parent, modal);
initComponents();
}
//~ Methods ----------------------------------------------------------------
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jProgressBar1 = new javax.swing.JProgressBar();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
// setTitle(org.openide.util.NbBundle.getMessage(ReportSwingWorkerDialog.class, "ReportSwingWorkerDialog.title")); // NOI18N
setTitle("ReportSwingWorkerDialog.title"); // NOI18N
setModal(true);
setResizable(false);
getContentPane().setLayout(new java.awt.GridBagLayout());
jProgressBar1.setIndeterminate(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(jProgressBar1, gridBagConstraints);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/jasperreports/printer.png"))); // NOI18N
// jLabel1.setText(org.openide.util.NbBundle.getMessage(
// ReportSwingWorkerDialog.class,
// "ReportSwingWorkerDialog.jLabel1.text"));
jLabel1.setText("ReportSwingWorkerDialog.jLabel1.text");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(jLabel1, gridBagConstraints);
pack();
} // </editor-fold>
}
| cismet/lagis-client | src/main/java/de/cismet/lagis/report/ReportSwingWorkerDialog.java | Java | gpl-3.0 | 3,062 |
using Editor_Mono.Cecil.Metadata;
using System;
namespace Editor_Mono.Cecil
{
public sealed class PinnedType : TypeSpecification
{
public override bool IsValueType
{
get
{
return false;
}
set
{
throw new InvalidOperationException();
}
}
public override bool IsPinned
{
get
{
return true;
}
}
public PinnedType(TypeReference type) : base(type)
{
Mixin.CheckType(type);
this.etype = Editor_Mono.Cecil.Metadata.ElementType.Pinned;
}
}
}
| lichunlincn/cshotfix | CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil/PinnedType.cs | C# | gpl-3.0 | 531 |
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
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/>.
*/
use Gibbon\Services\Format;
use Gibbon\Contracts\Comms\Mailer;
include '../../gibbon.php';
$URL = $session->get('absoluteURL').'/index.php?q=/modules/System Admin/thirdPartySettings.php';
if (isActionAccessible($guid, $connection2, '/modules/System Admin/thirdPartySettings.php') == false) {
// Access denied
$URL .= '&return=error0';
header("Location: {$URL}");
exit;
} else {
// Proceed!
$email = $_GET['email'] ?? $session->get('email');
$mail = $container->get(Mailer::class);
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'error_log';
$mail->AddAddress($session->get('email'));
$mail->setDefaultSender(__('Test Email'));
$mail->renderBody('mail/message.twig.html', [
'title' => __('Test Email'),
'body' => '',
'details' => [
__('Recipient') => $email,
__('Date') => Format::dateTime(date('Y-m-d H:i:s')),
]
]);
$sent = $mail->Send();
if (!$sent) {
$session->set('testEmailError', $mail->ErrorInfo);
$session->set('testEmailRecipient', $email);
}
$URL .= !$sent
? '&return=error10'
: '&return=success0';
header("Location: " . $URL);
}
| rossdotparker/core | modules/System Admin/thirdPartySettings_emailProcess.php | PHP | gpl-3.0 | 1,911 |
package application;
/* Model is where data processing occurs. In this case, the logic of math calculations */
public class Model {
public float calculate(long number1, long number2, String operator){
switch(operator){
case "+":
return number1 + number2;
case "-":
return number1 - number2;
case "*":
return number1 * number2;
case "/":
if (number2 == 0){
return 0;
}
return number1 / number2;
default:
return 0;
}
}
}
| AlexWang-16/learn_javafx | JFX04/src/application/Model.java | Java | gpl-3.0 | 461 |
from . import models
from . import materialized_views | sumihai-tekindo/account_sicepat | customer_classification/__init__.py | Python | gpl-3.0 | 54 |
# = key_event_adapter.rb - Semantic key states
#
# Makes :hit, :down, :up, :released key states available for querying.
module QuickRPG
class KeyEventAdapter
attr_reader :keys
def initialize(supported_keys = (0..255))
@keys = {}
supported_keys.each do |key|
@keys[key] = :released
end
end
def button_down(id)
keys[id] = :down if hit? id
keys[id] = :hit if released? id
end
def button_up(id)
keys[id] = :released if up? id
keys[id] = :up if down? id
end
def hit?(id)
keys[id] == :hit
end
def down?(id)
keys[id] == :down or hit? id
end
def up?(id)
keys[id] == :up
end
def released?(id)
keys[id] == :released or up? id
end
def state(id)
keys[id]
end
end
end
| DivineDominion/quickrpg-clone | lib/qrpg/keyboard_control/key_event_adapter.rb | Ruby | gpl-3.0 | 855 |
Template.addAction.actionCreationCancelled=function() {
var context=EditContext.getContext();
if(context!=null) {
context.keepEditContextOnNextRoute();
var route=context.getReturnRoute();
route.onCancel();
}
else {
Router.go('actions');
}
return false;
}
Template.addAction.events({
'click .cancel' :Template.addAction.actionCreationCancelled,
'click .goBack' : Template.addAction.actionCreationCancelled
});
Router.route('action-create', function () {
this.render('addAction');
}, { name: 'addAction'});
Template.addAction.helpers({
collection: function() {
return Collections.Actions;
},
editContext : function() {
return EditContext.getContext();
},
schema: Schemas.Action
});
AutoForm.hooks({
addActionForm: {
after: {
'method-update': function(err,result) {
//Router.go('actions');
var context=EditContext.getContext();
console.log('save action!');
if(context!=undefined) {
context.keepEditContextOnNextRoute();
}
Router.go('render.action',{_id: result});
}
}
}
}); | dubsky/robolos | src/client/html/actions/addAction.js | JavaScript | gpl-3.0 | 1,248 |
package the.bytecode.club.bytecodeviewer.decompilers;
import org.objectweb.asm.tree.ClassNode;
/***************************************************************************
* 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/>. *
***************************************************************************/
/**
* Used to represent a decompiler/disassembler
*
* @author Konloch
*/
public abstract class InternalDecompiler
{
public abstract String decompileClassNode(ClassNode cn, byte[] b);
public abstract void decompileToZip(String sourceJar, String zipName);
}
| Konloch/bytecode-viewer | src/main/java/the/bytecode/club/bytecodeviewer/decompilers/InternalDecompiler.java | Java | gpl-3.0 | 1,677 |
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
* @author Alex Nevsky
*
* Date: 27/05/2021
*/
public class Permutation {
// CMD+D to enter EOF
public static void main(String[] args) {
int k = Integer.parseInt(args[0]);
RandomizedQueue<String> q = new RandomizedQueue<>();
do {
String input = StdIn.readString();
if (q.size() < k) q.enqueue(input);
} while ((!StdIn.isEmpty()));
for (int i = 0; i < k; ++i) {
StdOut.println(q.dequeue());
}
}
}
| anevsky/algorithms | princeton/src/main/java/Permutation.java | Java | gpl-3.0 | 529 |
<?php
/**
* TrcIMPLAN - SMI Indicadores Gómez Palacio Sustentabilidad Empresas Certificadas como Limpias (Creado por Central:SmiLanzadera)
*
* Copyright (C) 2015 Guillermo Valdés Lozano
*
* 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/>.
*
*/
// Namespace
namespace SMIIndicadoresGomezPalacio;
/**
* Clase SustentabilidadEmpresasCertificadasComoLimpias
*/
class SustentabilidadEmpresasCertificadasComoLimpias extends \Base\Publicacion {
/**
* Constructor
*/
public function __construct() {
// Título, autor y fecha
$this->nombre = 'Empresas Certificadas como Limpias en Gómez Palacio';
$this->autor = 'Dirección de Investigación Estratégica';
$this->fecha = '2015-07-14T12:28';
// El nombre del archivo a crear (obligatorio) y rutas relativas a las imágenes
$this->archivo = 'sustentabilidad-empresas-certificadas-como-limpias';
$this->imagen = '../smi/introduccion/imagen.jpg';
$this->imagen_previa = '../smi/introduccion/imagen-previa.jpg';
// La descripción y claves dan información a los buscadores y redes sociales
$this->descripcion = 'Incluido en el subíndice "Manejo Sustentable del Medio Ambiente". Mide el número de empresas que cuentan con la certificación de “Empresa Limpia”emitido por la Procuraduría Federal de Protección al Ambiente (PROFEPA), que evidencia el cumplimiento de la normatividad y buenas prácticas ambientales.';
$this->claves = 'IMPLAN, Gómez Palacio, Índice de Competitividad Urbana, Empresas';
// El directorio en la raíz donde se guardará el archivo HTML
$this->directorio = 'indicadores-gomez-palacio';
// Opción del menú Navegación a poner como activa cuando vea esta publicación
$this->nombre_menu = 'Indicadores';
// El estado puede ser 'publicar' (crear HTML y agregarlo a índices/galerías), 'revisar' (sólo crear HTML y accesar por URL) o 'ignorar'
$this->estado = 'publicar';
// Si para compartir es verdadero, aparecerán al final los botones de compartir en Twitter y Facebook
$this->para_compartir = true;
// Instancia de SchemaPostalAddress que tiene la localidad, municipio y país
$region = new \Base\SchemaPostalAddress();
$region->addressCountry = 'MX';
$region->addressRegion = 'Durango';
$region->addressLocality = 'Gómez Palacio';
// Instancia de SchemaPlace agrupa la región y el mapa
$lugar = new \Base\SchemaPlace();
$lugar->address = $region;
// El contenido es estructurado en un esquema
$schema = new \Base\SchemaArticle();
$schema->name = $this->nombre;
$schema->description = $this->descripcion;
$schema->datePublished = $this->fecha;
$schema->image = $this->imagen;
$schema->image_show = false;
$schema->author = $this->autor;
$schema->contentLocation = $lugar;
// El contenido es una instancia de SchemaArticle
$this->contenido = $schema;
// Para el Organizador
$this->categorias = array('Índice de Competitividad Urbana', 'Empresas');
$this->fuentes = array('IMCO');
$this->regiones = 'Gómez Palacio';
} // constructor
/**
* HTML
*
* @return string Código HTML
*/
public function html() {
// Cargar en el Schema el HTML de las lengüetas
$this->contenido->articleBody = <<<FINAL
<ul class="nav nav-tabs lenguetas" id="smi-indicador">
<li><a href="#smi-indicador-datos" data-toggle="tab">Datos</a></li>
<li><a href="#smi-indicador-grafica" data-toggle="tab">Gráfica</a></li>
<li><a href="#smi-indicador-otras_regiones" data-toggle="tab">Otras regiones</a></li>
</ul>
<div class="tab-content lengueta-contenido">
<div class="tab-pane" id="smi-indicador-datos">
<h3>Información recopilada</h3>
<table class="table table-hover table-bordered matriz">
<thead>
<tr>
<th>Fecha</th>
<th>Dato</th>
<th>Fuente</th>
<th>Notas</th>
</tr>
</thead>
<tbody>
<tr>
<td>31/12/2008</td>
<td>0.5000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2009</td>
<td>2.0000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2010</td>
<td>4.5000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2011</td>
<td>4.2000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2012</td>
<td>3.8000</td>
<td>IMCO</td>
<td></td>
</tr>
</tbody>
</table>
<p><b>Unidad:</b> Por cada mil.</p>
<h3>Observaciones</h3>
<p>Unidades: Empresas certificadas como limpias por cada mil. Fuente: Procuraduría Federal de Protección al Ambiente (PROFEPA), 2009-2012.</p>
</div>
<div class="tab-pane" id="smi-indicador-grafica">
<h3>Gráfica de Empresas Certificadas como Limpias en Gómez Palacio</h3>
<div id="graficaDatos" class="grafica"></div>
</div>
<div class="tab-pane" id="smi-indicador-otras_regiones">
<h3>Gráfica con los últimos datos de Empresas Certificadas como Limpias</h3>
<div id="graficaOtrasRegiones" class="grafica"></div>
<h3>Últimos datos de Empresas Certificadas como Limpias</h3>
<table class="table table-hover table-bordered matriz">
<thead>
<tr>
<th>Región</th>
<th>Fecha</th>
<th>Dato</th>
<th>Fuente</th>
<th>Notas</th>
</tr>
</thead>
<tbody>
<tr>
<td>Torreón</td>
<td>2012-12-31</td>
<td>1.2000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Gómez Palacio</td>
<td>2012-12-31</td>
<td>3.8000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Lerdo</td>
<td>2012-12-31</td>
<td>1.4000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Matamoros</td>
<td>2012-12-31</td>
<td>0.0000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>La Laguna</td>
<td>2012-12-31</td>
<td>1.8000</td>
<td>IMCO</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
FINAL;
// Ejecutar este método en el padre
return parent::html();
} // html
/**
* Javascript
*
* @return string No hay código Javascript, entrega un texto vacío
*/
public function javascript() {
// JavaScript
$this->javascript[] = <<<FINAL
// LENGUETA smi-indicador-grafica
$('#smi-indicador a[href="#smi-indicador-grafica"]').on('shown.bs.tab', function(e){
// Gráfica
if (typeof vargraficaDatos === 'undefined') {
vargraficaDatos = Morris.Line({
element: 'graficaDatos',
data: [{ fecha: '2008-12-31', dato: 0.5000 },{ fecha: '2009-12-31', dato: 2.0000 },{ fecha: '2010-12-31', dato: 4.5000 },{ fecha: '2011-12-31', dato: 4.2000 },{ fecha: '2012-12-31', dato: 3.8000 }],
xkey: 'fecha',
ykeys: ['dato'],
labels: ['Dato'],
lineColors: ['#FF5B02'],
xLabelFormat: function(d) { return d.getDate()+'/'+(d.getMonth()+1)+'/'+d.getFullYear(); },
dateFormat: function(ts) { var d = new Date(ts); return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear(); }
});
}
});
// LENGUETA smi-indicador-otras_regiones
$('#smi-indicador a[href="#smi-indicador-otras_regiones"]').on('shown.bs.tab', function(e){
// Gráfica
if (typeof vargraficaOtrasRegiones === 'undefined') {
vargraficaOtrasRegiones = Morris.Bar({
element: 'graficaOtrasRegiones',
data: [{ region: 'Torreón', dato: 1.2000 },{ region: 'Gómez Palacio', dato: 3.8000 },{ region: 'Lerdo', dato: 1.4000 },{ region: 'Matamoros', dato: 0.0000 },{ region: 'La Laguna', dato: 1.8000 }],
xkey: 'region',
ykeys: ['dato'],
labels: ['Dato'],
barColors: ['#FF5B02']
});
}
});
// TWITTER BOOTSTRAP TABS, ESTABLECER QUE LA LENGÜETA ACTIVA ES smi-indicador-datos
$(document).ready(function(){
$('#smi-indicador a[href="#smi-indicador-datos"]').tab('show')
});
FINAL;
// Ejecutar este método en el padre
return parent::javascript();
} // javascript
/**
* Redifusion HTML
*
* @return string Código HTML
*/
public function redifusion_html() {
// Para redifusión, se pone el contenido sin lengüetas
$this->redifusion = <<<FINAL
<h3>Descripción</h3>
<p>Incluido en el subíndice "Manejo Sustentable del Medio Ambiente". Mide el número de empresas que cuentan con la certificación de “Empresa Limpia”emitido por la Procuraduría Federal de Protección al Ambiente (PROFEPA), que evidencia el cumplimiento de la normatividad y buenas prácticas ambientales.</p>
<h3>Información recopilada</h3>
<table class="table table-hover table-bordered matriz">
<thead>
<tr>
<th>Fecha</th>
<th>Dato</th>
<th>Fuente</th>
<th>Notas</th>
</tr>
</thead>
<tbody>
<tr>
<td>31/12/2008</td>
<td>0.5000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2009</td>
<td>2.0000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2010</td>
<td>4.5000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2011</td>
<td>4.2000</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2012</td>
<td>3.8000</td>
<td>IMCO</td>
<td></td>
</tr>
</tbody>
</table>
<p><b>Unidad:</b> Por cada mil.</p>
<h3>Observaciones</h3>
<p>Unidades: Empresas certificadas como limpias por cada mil. Fuente: Procuraduría Federal de Protección al Ambiente (PROFEPA), 2009-2012.</p>
FINAL;
// Ejecutar este método en el padre
return parent::redifusion_html();
} // redifusion_html
} // Clase SustentabilidadEmpresasCertificadasComoLimpias
?>
| TRCIMPLAN/beta | lib/SMIIndicadoresGomezPalacio/SustentabilidadEmpresasCertificadasComoLimpias.php | PHP | gpl-3.0 | 11,613 |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using SmartStore.Core.Domain.Localization;
namespace SmartStore.Core.Domain.Catalog
{
/// <summary>
/// Represents a product variant attribute mapping
/// </summary>
[DataContract]
public partial class ProductVariantAttribute : BaseEntity, ILocalizedEntity
{
private ICollection<ProductVariantAttributeValue> _productVariantAttributeValues;
/// <summary>
/// Gets or sets the product identifier
/// </summary>
[DataMember]
[Index("IX_Product_ProductAttribute_Mapping_ProductId_DisplayOrder", 1)]
public int ProductId { get; set; }
/// <summary>
/// Gets or sets the product attribute identifier
/// </summary>
[DataMember]
public int ProductAttributeId { get; set; }
/// <summary>
/// Gets or sets a value a text prompt
/// </summary>
[DataMember]
public string TextPrompt { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is required
/// </summary>
[DataMember]
public bool IsRequired { get; set; }
/// <summary>
/// Gets or sets the attribute control type identifier
/// </summary>
[DataMember]
public int AttributeControlTypeId { get; set; }
/// <summary>
/// Gets or sets the display order
/// </summary>
[DataMember]
[Index("IX_Product_ProductAttribute_Mapping_ProductId_DisplayOrder", 2)]
public int DisplayOrder { get; set; }
/// <summary>
/// Gets the attribute control type
/// </summary>
[DataMember]
public AttributeControlType AttributeControlType
{
get
{
return (AttributeControlType)this.AttributeControlTypeId;
}
set
{
this.AttributeControlTypeId = (int)value;
}
}
public bool IsListTypeAttribute()
{
switch (AttributeControlType)
{
case AttributeControlType.Checkboxes:
case AttributeControlType.ColorSquares:
case AttributeControlType.DropdownList:
case AttributeControlType.RadioList:
return true;
default:
return false;
}
}
/// <summary>
/// Gets the product attribute
/// </summary>
[DataMember]
public virtual ProductAttribute ProductAttribute { get; set; }
/// <summary>
/// Gets the product
/// </summary>
public virtual Product Product { get; set; }
/// <summary>
/// Gets the product variant attribute values
/// </summary>
[DataMember]
public virtual ICollection<ProductVariantAttributeValue> ProductVariantAttributeValues
{
get { return _productVariantAttributeValues ?? (_productVariantAttributeValues = new HashSet<ProductVariantAttributeValue>()); }
protected set { _productVariantAttributeValues = value; }
}
}
}
| mfalkao/SmartStoreNET | src/Libraries/SmartStore.Core/Domain/Catalog/ProductVariantAttribute.cs | C# | gpl-3.0 | 3,030 |
package kirjanpito.models;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.HashMap;
import java.util.jar.JarFile;
import javax.swing.SwingWorker;
import kirjanpito.db.Account;
import kirjanpito.db.AccountDAO;
import kirjanpito.db.COAHeading;
import kirjanpito.db.COAHeadingDAO;
import kirjanpito.db.DataAccessException;
import kirjanpito.db.DataSource;
import kirjanpito.db.Document;
import kirjanpito.db.Period;
import kirjanpito.db.ReportStructure;
import kirjanpito.db.Session;
import kirjanpito.db.Settings;
/**
* <code>SwingWorker</code>, joka lisää tyhjään tietokantaan
* pakolliset perustiedot.
*/
public class DataSourceInitializationWorker extends SwingWorker<Void, Void> {
private DataSource dataSource;
private Session sess;
private File archiveFile;
private JarFile jar;
private boolean initialized;
public DataSourceInitializationWorker(DataSource dataSource,
File archiveFile) {
this.dataSource = dataSource;
this.archiveFile = archiveFile;
}
/**
* Ilmoittaa, onko perustietojen lisääminen onnistunut.
*
* @return <code>true</code>, jos perustiedot on lisätty
*/
public boolean isInitialized() {
return initialized;
}
protected Void doInBackground() throws Exception {
try {
sess = dataSource.openSession();
jar = new JarFile(archiveFile);
init();
createCOA();
copyReportStructure("balance-sheet");
copyReportStructure("balance-sheet-detailed");
copyReportStructure("income-statement");
copyReportStructure("income-statement-detailed");
if (isCancelled()) {
sess.rollback();
}
else {
sess.commit();
}
}
catch (Exception e) {
if (sess != null) sess.rollback();
throw e;
}
finally {
sess.close();
}
return null;
}
private void init() throws DataAccessException {
/* Luodaan tilikausi, jonka alkamispäivä on
* nykyisen vuoden ensimmäinen päivä ja päättymispäivä
* vuoden viimeinen päivä. */
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
Period period = new Period();
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
period.setStartDate(cal.getTime());
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 31);
period.setEndDate(cal.getTime());
dataSource.getPeriodDAO(sess).save(period);
/* Asetetaan luotu tilikausi nykyiseksi tilikaudeksi. */
Settings settings = dataSource.getSettingsDAO(sess).get();
settings.setCurrentPeriodId(period.getId());
settings.setName("");
settings.setBusinessId("");
settings.setDocumentTypeId(-1);
dataSource.getSettingsDAO(sess).save(settings);
/* Luodaan 0-tosite, johon tallennetaan taseen tilien alkusaldot. */
Document document = new Document();
document.setDate(period.getStartDate());
document.setNumber(0);
document.setPeriodId(period.getId());
dataSource.getDocumentDAO(sess).save(document);
}
private void createCOA() throws IOException, DataAccessException {
/* Luodaan tilikartta. */
BufferedReader reader = new BufferedReader(new InputStreamReader(
jar.getInputStream(jar.getEntry("chart-of-accounts.txt")),
Charset.forName("UTF-8")));
String line;
String[] fields;
AccountDAO accountDAO = dataSource.getAccountDAO(sess);
COAHeadingDAO headingDAO = dataSource.getCOAHeadingDAO(sess);
HashMap<String, Account> accounts = new HashMap<String, Account>();
Account account;
COAHeading heading;
int index;
double count;
boolean containsVatAccounts = false;
final BigDecimal[] vatRateMapping = {
BigDecimal.ZERO,
new BigDecimal("22"),
new BigDecimal("17"),
new BigDecimal("8"),
new BigDecimal("12"),
new BigDecimal("9"),
new BigDecimal("13"),
new BigDecimal("23")
};
line = reader.readLine();
count = Integer.parseInt(line);
index = 0;
/* Luetaan tilit ja otsikot CSV-tiedostosta. */
while ((line = reader.readLine()) != null && !isCancelled()) {
fields = line.split(";");
if (fields.length < 2)
continue;
/* Tiliriveissä ensimmäinen kenttä on "A" */
if (fields[0].equals("A")) {
/* 2. tilinumero, 3. nimi, 4. tyyppi */
account = new Account();
account.setNumber(fields[1]);
account.setName(fields[2]);
account.setType(Integer.parseInt(fields[3]));
account.setVatAccount1Id(-1);
account.setVatAccount2Id(-1);
accountDAO.save(account);
accounts.put(account.getNumber(), account);
}
/* Otsikkoriveissä ensimmäinen kenttä on "H" */
else if (fields[0].equals("H")) {
/* 2. numero, 3. teksti, 4. otsikkotaso */
heading = new COAHeading();
heading.setNumber(fields[1]);
heading.setText(fields[2]);
heading.setLevel(Integer.parseInt(fields[3]));
headingDAO.save(heading);
}
/* ALV-riveissä ensimmäinen kenttä on "V" */
else if (fields[0].equals("V")) {
account = accounts.get(fields[1]);
account.setVatCode(Integer.parseInt(fields[2]));
if (fields[3].endsWith("%")) {
account.setVatRate(new BigDecimal(
fields[3].substring(0, fields[3].length() - 1)));
}
else {
account.setVatRate(vatRateMapping[Integer.parseInt(fields[3])]);
}
if (fields.length > 4) {
account.setVatAccount1Id(accounts.get(fields[4]).getId());
}
else {
account.setVatAccount1Id(-1);
}
if (fields.length > 5) {
account.setVatAccount2Id(accounts.get(fields[5]).getId());
}
else {
account.setVatAccount2Id(-1);
}
if (account.getVatCode() == 2 || account.getVatCode() == 3) {
containsVatAccounts = true;
}
accountDAO.save(account);
}
setProgress((int)(index / count * 100));
index++;
}
reader.close();
/* Piilotetaan ALV-sarake, jos tilikarttamalli ei sisällä ALV-tilejä. */
if (!containsVatAccounts) {
Settings settings = dataSource.getSettingsDAO(sess).get();
settings.setProperty("vatVisible", "false");
dataSource.getSettingsDAO(sess).save(settings);
}
}
private void copyReportStructure(String name) throws IOException, DataAccessException {
String filename = name + ".txt";
BufferedReader reader = new BufferedReader(new InputStreamReader(
jar.getInputStream(jar.getEntry(filename)),
Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
ReportStructure s = new ReportStructure();
s.setId(name);
s.setData(sb.toString());
dataSource.getReportStructureDAO(sess).save(s);
}
}
| thelineva/tilitin | src/kirjanpito/models/DataSourceInitializationWorker.java | Java | gpl-3.0 | 6,719 |
function zeroFill( number, width )
{
width -= number.toString().length;
if ( width > 0 )
{
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
function populateEndtime()
{
var startVal = parseInt($('started').value,10);
var hrsVal = parseInt($('workhours').value,10);
var finVal = startVal + hrsVal;
finVal = zeroFill(finVal,2);
$('ended').value = finVal + ":00";
}
function populateHours()
{
var startVal = parseInt($('started').value,10);
var endVal = parseInt($('ended').value,10);
var hrsVal = parseInt($('workhours').value,10);
var finVal = endVal - startVal;
if(hrsVal != finVal && finVal >= 0)
{
$('workhours').value = finVal;
}
} | cosycode/collabtive2 | include/js/timetracker_widget.js | JavaScript | gpl-3.0 | 745 |
package com.a5corp.weather.app;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.os.Build;
import java.util.Locale;
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
Configuration config = context.getResources().getConfiguration();
Locale sysLocale = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sysLocale = getSystemLocale(config);
} else {
sysLocale = getSystemLocaleLegacy(config);
}
if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
context = context.createConfigurationContext(config);
} else {
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
return new MyContextWrapper(context);
}
@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config){
return config.locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config){
return config.getLocales().get(0);
}
@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale){
config.locale = locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale){
config.setLocale(locale);
}
} | Sparker0i/Weather | app/src/main/java/com/a5corp/weather/app/MyContextWrapper.java | Java | gpl-3.0 | 2,119 |
# -*- coding: utf-8 -*-
#
# cosmic documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 21 14:05:08 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import re
from cosmic import __version__ as cosmic_version
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.imgmath',
'sphinx.ext.autosummary',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.linkcode',
'sphinx.ext.ifconfig',
'sphinx_automodapi.automodapi',
'sphinxcontrib.programoutput',
'matplotlib.sphinxext.plot_directive',
'IPython.sphinxext.ipython_console_highlighting',
'IPython.sphinxext.ipython_directive',
'numpydoc',
]
# -- Extensions ---------------------------------------------------------------
# -- autodoc ------------------------------------
autoclass_content = 'class'
autodoc_default_flags = ['show-inheritance', 'members', 'inherited-members']
# -- autosummary --------------------------------
autosummary_generate = True
# -- numpydoc -----------------------------------
# fix numpydoc autosummary
numpydoc_show_class_members = False
# use blockquotes (numpydoc>=0.8 only)
numpydoc_use_blockquotes = True
# auto-insert plot directive in examples
numpydoc_use_plots = True
# try and update the plot detection to include .show() calls
try: # requires numpydoc >= 0.8
from numpydoc import docscrape_sphinx
parts = re.split('[\(\)|]', docscrape_sphinx.IMPORT_MATPLOTLIB_RE)[1:-1]
except AttributeError:
pass
else:
parts.extend(('fig.show()', 'plot.show()'))
docscrape_sphinx.IMPORT_MATPLOTLIB_RE = r'\b({})\b'.format('|'.join(parts))
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
fortran_ext = ['f']
fortran_src = '../cosmic/src/'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'cosmic'
copyright = u'2017, Katie Breivik'
author = u'Katie Breivik'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = cosmic_version
# The full version, including alpha/beta/rc tags.
release = cosmic_version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
# html_title = u'cosmic v0.1'
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16
# or 32x32 pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'cosmicdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
# Latex figure (float) alignment
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'cosmic.tex', u'cosmic Documentation',
u'Katie Breivik', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'cosmic', u'cosmic Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'cosmic', u'cosmic Documentation',
author, 'cosmic', 'White dwarf Accretion w/ COSMIC.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# -- Extensions -----------------------------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('https://docs.python.org/', None),
'numpy': ('https://docs.scipy.org/doc/numpy/', None),
'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None),
'astropy': ('http://docs.astropy.org/en/stable/', None),
}
# -- linkcode -----------------------------------------------------------------
def linkcode_resolve(domain, info):
"""Determine the URL corresponding to Python object
This code is stolen with thanks from the scipy team.
"""
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except:
return None
# try and sneak past a decorator
try:
obj = obj.im_func.func_closure[0].cell_contents
except (AttributeError, TypeError):
pass
try:
fn = inspect.getsourcefile(obj)
except:
fn = None
if not fn:
try:
fn = inspect.getsourcefile(sys.modules[obj.__module__])
except:
fn = None
if not fn:
return None
try:
source, lineno = inspect.findsource(obj)
except:
lineno = None
if lineno:
linespec = "#L%d" % (lineno + 1)
else:
linespec = ""
fn = os.path.relpath(fn, start=os.path.dirname(cosmic.__file__))
if fn.startswith(os.path.pardir):
return None
return ("http://github.com/COSMIC-PopSynth/COSMIC/tree/%s/COSMIC/%s%s"
% (GWPY_VERSION['full-revisionid'], fn, linespec))
| aCOSMIC/aCOSMIC | docs/conf.py | Python | gpl-3.0 | 12,863 |
/**
* 3Sum:
* solution 1: O(n) hash table, O(n^2) scan and check;
* solution 2: O(n^2) hash table, O(n) scan and check;
* solution 3: sort, then for each i, do 2Sum in range [i+1, n];
* O(nlogn) + O(n^2) = O(n^2) time, O(1) space
*
* Solution 3 can also be used for 3Sum closest
*/
class Solution {
private:
void twoSum(const vector<int> &nums, int start, set<vector<int>> &ret) {
int target = -nums[start - 1];
int i = start, j = nums.size() - 1;
while (i < j) {
int sum = nums[i] + nums[j];
if (sum < target) {
++i;
} else if (sum > target) {
--j;
} else { // found
ret.insert({-target, nums[i], nums[j]});
++i, --j;
}
}
}
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> ret;
int n = nums.size();
for (int i = 0; i < n; i++) {
twoSum(nums, i+1, ret);
}
return vector<vector<int>>(ret.begin(), ret.end());
}
};
| louyx/algo | lc/lc_15_3sum.cpp | C++ | gpl-3.0 | 1,127 |
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Mesh_triangulation_3.h>
#include <CGAL/Mesh_complex_3_in_triangulation_3.h>
#include <CGAL/Mesh_criteria_3.h>
#include <CGAL/Labeled_image_mesh_domain_3.h>
#include <CGAL/make_mesh_3.h>
#include <CGAL/Image_3.h>
// Domain
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Labeled_image_mesh_domain_3<CGAL::Image_3,K> Mesh_domain;
#ifdef CGAL_CONCURRENT_MESH_3
typedef CGAL::Parallel_tag Concurrency_tag;
#else
typedef CGAL::Sequential_tag Concurrency_tag;
#endif
// Triangulation
typedef CGAL::Mesh_triangulation_3<Mesh_domain,CGAL::Default,Concurrency_tag>::type Tr;
typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;
// Mesh Criteria
typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;
// To avoid verbose function and named parameters call
using namespace CGAL::parameters;
int main(int argc, char*argv[])
{
const char* fname = (argc>1)?argv[1]:"data/liver.inr.gz";
// Domain
CGAL::Image_3 image;
if(!image.read(fname)){
std::cerr << "Error: Cannot read file " << fname << std::endl;
return EXIT_FAILURE;
}
Mesh_domain domain(image);
// Mesh criteria
Mesh_criteria criteria(facet_angle=30, facet_distance=1.2,
cell_radius_edge_ratio=2);
// Mesh generation and optimization in one call
C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria,
lloyd(time_limit=30),
no_perturb(),
exude(time_limit=10, sliver_bound=10));
// Mesh generation and optimization in several call
C3t3 c3t3_bis = CGAL::make_mesh_3<C3t3>(domain, criteria,
no_perturb(), no_exude());
CGAL::lloyd_optimize_mesh_3(c3t3_bis, domain, time_limit=30);
CGAL::exude_mesh_3(c3t3_bis, sliver_bound=10, time_limit=10);
// Output
std::ofstream medit_file("out.mesh");
c3t3.output_to_medit(medit_file);
std::ofstream medit_file_bis("out_bis.mesh");
c3t3_bis.output_to_medit(medit_file_bis);
return 0;
}
| FEniCS/mshr | 3rdparty/CGAL/examples/Mesh_3/mesh_optimization_lloyd_example.cpp | C++ | gpl-3.0 | 2,125 |
@extends ('admin')
@section ('contenido')
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h3>Editar Perfil: {{$admin -> nombre}}</h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
{!!Form::open(array('url'=>'/admin/editarPerfil/'.$admin -> id,'method'=>'POST'))!!}
{{Form::token()}}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label for="ci">CI</label>
<input type="text" name="ci" class="form-control" value="{{$admin -> ci}}" required >
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" name="nombre" class="form-control" value="{{$admin -> nombre}}" required>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label for="direccion">Direccion</label>
<input type="text" name="direccion" class="form-control" value="{{$admin -> direccion}}" required >
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label for="telefono">Telefono</label>
<input type="text" name="telefono" class="form-control" value="{{$admin -> telefono}}" required >
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
{!!Form::close()!!}
</div>
</div>
@endsection | rodrigoAb21/ERP3 | resources/views/admin/Seguridad/perfil/editarPerfil.blade.php | PHP | gpl-3.0 | 1,992 |
package vistas;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import sistemaReserva.SistemaReserva;
import sistemaReserva.ItemTarifaView;
import sistemaReserva.ServicioAdicionalView;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;;
public class VentanaEditarServicioAdicional extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField tfPrecio;
private JButton btnAceptar;
private JButton btnCancelar;
private JTextField tfCodigo;
private JButton btnBuscar;
private JButton btnEliminar;
private ServicioAdicionalView servicioAdicional;
private JTextField tfDescripcion;
/**
* Launch the application.
*/
/*
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
modificarCliente frame = new modificarCliente();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
*/
/**
* Create the frame.
*/
public void buscar(SistemaReserva sistema)
{
int codigo;
try
{
codigo = Integer.parseInt(tfCodigo.getText());
}
catch (NumberFormatException e)
{
JOptionPane.showInternalMessageDialog(contentPane, "El codigo debe ser un numero. ");
return;
}
servicioAdicional = sistema.buscarServicioAdicionalView(codigo);
if(servicioAdicional != null)
{
tfPrecio.setEnabled(true);
tfPrecio.setText(Double.toString(servicioAdicional.getPrecio()));
tfDescripcion.setEnabled(true);
tfDescripcion.setText(servicioAdicional.getDescripcion());
btnEliminar.setEnabled(true);
btnAceptar.setEnabled(true);
}else
{
JOptionPane.showInternalMessageDialog(contentPane, "No existe un servicio adicional con ese codigo.");
}
}
public void guardar(SistemaReserva sistema)
{
if (servicioAdicional != null)
{
String descripcion = tfDescripcion.getText();
if (descripcion.equals(""))
{
JOptionPane.showMessageDialog(contentPane, "La descripcion no puede estar en blanco.");
return;
}
Double precio;
try
{
precio = Double.parseDouble(tfPrecio.getText());
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(contentPane, "El precio debe ser un numero.");
return;
}
if (precio <= 0)
{
JOptionPane.showMessageDialog(contentPane, "El precio debe ser mayor a 0. ");
}
else
{
sistema.modificarServicioAdicional(servicioAdicional.getCodigo(), descripcion, precio);
JOptionPane.showMessageDialog(contentPane, "Cambio exitoso. ");
dispose();
}
}
}
public void baja(SistemaReserva sistema)
{
if (servicioAdicional != null)
{
int respuesta = JOptionPane.showConfirmDialog(contentPane, "Esta seguro que desea ELIMINAR este servicio adicional?");
if(respuesta == JOptionPane.YES_OPTION)
{
sistema.bajaServicio(servicioAdicional.getCodigo());
JOptionPane.showMessageDialog(contentPane, "Servicio adicional eliminado. ");
dispose();
}
}
}
public VentanaEditarServicioAdicional(SistemaReserva sistema)
{
setResizable(false);//Que no lo puedan maximizar
setTitle("Modificar tarifa");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 700, 480);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCodigo = new JLabel("Codigo: ");
lblCodigo.setBounds(226, 11, 101, 44);
contentPane.add(lblCodigo);
tfCodigo = new JTextField();
tfCodigo.setBounds(337, 23, 150, 20);
contentPane.add(tfCodigo);
tfCodigo.setColumns(10);
JLabel lblPrecio = new JLabel("Precio: ");
lblPrecio.setBounds(226, 84, 80, 14);
contentPane.add(lblPrecio);
tfPrecio = new JTextField();
tfPrecio.setEnabled(false);
tfPrecio.setBounds(337, 81, 150, 20);
contentPane.add(tfPrecio);
tfPrecio.setColumns(10);
btnBuscar = new JButton("Buscar");
btnBuscar.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
buscar(sistema);
}
});
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buscar(sistema);
}
});
btnBuscar.setBounds(497, 22, 89, 23);
contentPane.add(btnBuscar);
btnAceptar = new JButton("Aceptar");
btnAceptar.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
guardar(sistema);
}
});
btnAceptar.setEnabled(false);
btnAceptar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
guardar(sistema);
}
});
btnAceptar.setBounds(208, 125, 89, 23);
contentPane.add(btnAceptar);
btnCancelar = new JButton("Cancelar");
btnCancelar.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
dispose();
}
});
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
btnCancelar.setBounds(337, 125, 89, 23);
contentPane.add(btnCancelar);
btnEliminar = new JButton("Eliminar");
btnEliminar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
baja(sistema);
}
});
btnEliminar.setEnabled(false);
btnEliminar.setBounds(497, 125, 89, 23);
contentPane.add(btnEliminar);
JLabel lblDescripcion = new JLabel("Descripcion: ");
lblDescripcion.setBounds(226, 53, 71, 14);
contentPane.add(lblDescripcion);
tfDescripcion = new JTextField();
tfDescripcion.setEnabled(false);
tfDescripcion.setBounds(337, 50, 150, 20);
contentPane.add(tfDescripcion);
tfDescripcion.setColumns(10);
}
}
| dforce2055/ReservaHotel | src/vistas/VentanaEditarServicioAdicional.java | Java | gpl-3.0 | 7,064 |
from token import *
from network import *
from logical_node import *
from role_criteria import *
##################################################################################
# Example code that roughly shows how the framework is to be used. Note: the
# relationship between the network and the logical nodes will likely change.
##################################################################################
class MyAwesomeRoleCriteria(RoleCriteria):
def __init__(self, name, happy, excited):
self.name = name
self.happy = happy
self.excited = excited
def evaluate_against(self, node_parameters):
return int(self.happy == node_parameters["happy"] and self.excited == node_parameters["excited"])
# Clients will define their own RoleCriteria, which will expect
# a certain set of parameters to evaluate on
role_criterias = [
MyAwesomeRoleCriteria("very sad", happy=False, excited=False),
MyAwesomeRoleCriteria("just content", happy=True, excited=False),
MyAwesomeRoleCriteria("freaking excited", happy=True, excited=True)
]
nodes = [
LogicalNode(0, { "happy": True, "excited": True }, role_criterias),
LogicalNode(1, { "happy": True, "excited": True }, role_criterias),
LogicalNode(2, { "happy": False, "excited": False }, role_criterias),
LogicalNode(3, { "happy": True, "excited": False }, role_criterias)
]
if __name__ == '__main__':
network = SimulatedNetwork(nodes)
token = nodes[0].begin_logical_assignment()
if token:
print "Error! Some roles couldn't be satisfied"
for role_id in token.unassigned_roles:
print "Role %d: %s" % (role_id, role_criterias[role_id].name)
else:
print "Success! All roles assigned!"
for node in nodes:
if node.assigned_role is not None:
print "Node %d's role: %s" % (node.node_id, role_criterias[node.assigned_role].name) | triskadecaepyon/DF_RoleMatrix | example_simple.py | Python | gpl-3.0 | 1,926 |
//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like "dwarfdump".
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/RelocVisitor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstring>
#include <list>
#include <string>
#include <system_error>
using namespace llvm;
using namespace object;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::desc("<input object files or .dSYM bundles>"),
cl::ZeroOrMore);
static cl::opt<DIDumpType> DumpType(
"debug-dump", cl::init(DIDT_All), cl::desc("Dump of debug sections:"),
cl::values(
clEnumValN(DIDT_All, "all", "Dump all debug sections"),
clEnumValN(DIDT_Abbrev, "abbrev", ".debug_abbrev"),
clEnumValN(DIDT_AbbrevDwo, "abbrev.dwo", ".debug_abbrev.dwo"),
clEnumValN(DIDT_AppleNames, "apple_names", ".apple_names"),
clEnumValN(DIDT_AppleTypes, "apple_types", ".apple_types"),
clEnumValN(DIDT_AppleNamespaces, "apple_namespaces",
".apple_namespaces"),
clEnumValN(DIDT_AppleObjC, "apple_objc", ".apple_objc"),
clEnumValN(DIDT_Aranges, "aranges", ".debug_aranges"),
clEnumValN(DIDT_Info, "info", ".debug_info"),
clEnumValN(DIDT_InfoDwo, "info.dwo", ".debug_info.dwo"),
clEnumValN(DIDT_Types, "types", ".debug_types"),
clEnumValN(DIDT_TypesDwo, "types.dwo", ".debug_types.dwo"),
clEnumValN(DIDT_Line, "line", ".debug_line"),
clEnumValN(DIDT_LineDwo, "line.dwo", ".debug_line.dwo"),
clEnumValN(DIDT_Loc, "loc", ".debug_loc"),
clEnumValN(DIDT_LocDwo, "loc.dwo", ".debug_loc.dwo"),
clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
clEnumValN(DIDT_Macro, "macro", ".debug_macinfo"),
clEnumValN(DIDT_Ranges, "ranges", ".debug_ranges"),
clEnumValN(DIDT_Pubnames, "pubnames", ".debug_pubnames"),
clEnumValN(DIDT_Pubtypes, "pubtypes", ".debug_pubtypes"),
clEnumValN(DIDT_GnuPubnames, "gnu_pubnames", ".debug_gnu_pubnames"),
clEnumValN(DIDT_GnuPubtypes, "gnu_pubtypes", ".debug_gnu_pubtypes"),
clEnumValN(DIDT_Str, "str", ".debug_str"),
clEnumValN(DIDT_StrDwo, "str.dwo", ".debug_str.dwo"),
clEnumValN(DIDT_StrOffsetsDwo, "str_offsets.dwo",
".debug_str_offsets.dwo"),
clEnumValN(DIDT_CUIndex, "cu_index", ".debug_cu_index"),
clEnumValN(DIDT_TUIndex, "tu_index", ".debug_tu_index"), clEnumValEnd));
static void error(StringRef Filename, std::error_code EC) {
if (!EC)
return;
errs() << Filename << ": " << EC.message() << "\n";
exit(1);
}
static void DumpObjectFile(ObjectFile &Obj, Twine Filename) {
std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj));
outs() << Filename.str() << ":\tfile format " << Obj.getFileFormatName()
<< "\n\n";
// Dump the complete DWARF structure.
DICtx->dump(outs(), DumpType);
}
static void DumpInput(StringRef Filename) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
error(Filename, BuffOrErr.getError());
std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
Expected<std::unique_ptr<Binary>> BinOrErr =
object::createBinary(Buff->getMemBufferRef());
if (!BinOrErr)
error(Filename, errorToErrorCode(BinOrErr.takeError()));
if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get()))
DumpObjectFile(*Obj, Filename);
else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get()))
for (auto &ObjForArch : Fat->objects()) {
auto MachOOrErr = ObjForArch.getAsObjectFile();
error(Filename, MachOOrErr.getError());
DumpObjectFile(**MachOOrErr,
Filename + " (" + ObjForArch.getArchTypeName() + ")");
}
}
/// If the input path is a .dSYM bundle (as created by the dsymutil tool),
/// replace it with individual entries for each of the object files inside the
/// bundle otherwise return the input path.
static std::vector<std::string> expandBundle(std::string InputPath) {
std::vector<std::string> BundlePaths;
SmallString<256> BundlePath(InputPath);
// Manually open up the bundle to avoid introducing additional dependencies.
if (sys::fs::is_directory(BundlePath) &&
sys::path::extension(BundlePath) == ".dSYM") {
std::error_code EC;
sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
const std::string &Path = Dir->path();
sys::fs::file_status Status;
EC = sys::fs::status(Path, Status);
error(Path, EC);
switch (Status.type()) {
case sys::fs::file_type::regular_file:
case sys::fs::file_type::symlink_file:
case sys::fs::file_type::type_unknown:
BundlePaths.push_back(Path);
break;
default: /*ignore*/;
}
}
error(BundlePath, EC);
}
if (!BundlePaths.size())
BundlePaths.push_back(InputPath);
return BundlePaths;
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n");
// Defaults to a.out if no filenames specified.
if (InputFilenames.size() == 0)
InputFilenames.push_back("a.out");
// Expand any .dSYM bundles to the individual object files contained therein.
std::vector<std::string> Objects;
for (auto F : InputFilenames) {
auto Objs = expandBundle(F);
Objects.insert(Objects.end(), Objs.begin(), Objs.end());
}
std::for_each(Objects.begin(), Objects.end(), DumpInput);
return EXIT_SUCCESS;
}
| vinutah/apps | tools/llvm/llvm_39/opt/tools/llvm-dwarfdump/llvm-dwarfdump.cpp | C++ | gpl-3.0 | 6,674 |
// $Id$
package com.jclark.xsl.dom;
import com.jclark.xsl.om.*;
/**
* Wraps a W3C DOM XML Comment Node as an om.Node
*/
class CommentNode extends NodeBase
{
CommentNode(org.w3c.dom.Node domNode,
ContainerNode parent,
int childIndex)
{
super(domNode, parent, childIndex);
}
public byte getType()
{
return COMMENT;
}
public final String getData()
{
return domNode.getNodeValue();
}
}
| srnsw/xena | plugins/office/ext/src/xt-20051206/src/xt/java/com/jclark/xsl/dom/CommentNode.java | Java | gpl-3.0 | 483 |
<?php
/**
* This a View/Edit Toggle button for a menu.
*
* @package Framework
* @subpackage Presentation
* @author Ryan Somma
* @see Menu
*/
abstract class MenuViewEditToggle extends Menu
{
/**
* Builds javascript for flipping between view and edit modes.
* @param string $toggleItem Human-readable label for what's being toggled.
* @param string $pageCode Current pagecode.
*/
protected function buildViewEditToggleMenu($toggleItem='',$pageCode='')
{
// if (Security::getEditPrivileges(PageConfiguration::getCurrentPageSecurityCode(),ApplicationSession::getValue('currentOrgId')))
// {
$this->source .=
"<script type=\"text/javascript\">"
."var update{$pageCode}Menu = function()"
."{"
. "if ($(\"hidViewEdit{$pageCode}Menu\") != null)"
. "{"
. "if ($(\"hidViewEdit{$pageCode}Menu\").value == \"view\")"
. "{"
. "$(\"menu_view_edit{$pageCode}\").innerHTML = \"<a href=\\\"javascript:{$pageCode}ViewEditSwitchContent.switchContent('{$pageCode}_edit','{$pageCode}_view')\\\">Edit {$toggleItem}</a>\";"
. "$(\"hidViewEdit{$pageCode}Menu\").value = \"edit\";"
. "}"
. "else if ($(\"hidViewEdit{$pageCode}Menu\").value == \"edit\")"
. "{"
. "$(\"menu_view_edit{$pageCode}\").innerHTML = \"<a href=\\\"javascript:{$pageCode}ViewEditSwitchContent.switchContent('{$pageCode}_view','{$pageCode}_edit')\\\">View {$toggleItem}</a>\";"
. "$(\"hidViewEdit{$pageCode}Menu\").value = \"view\";"
. "}"
. "}"
."};"
."addLoadEvent(function()"
."{"
. "{$pageCode}ViewEditSwitchContent = new SwitchContent;"
. "{$pageCode}ViewEditSwitchContent.initialize();"
. "{$pageCode}ViewEditSwitchContent.subscribe(update{$pageCode}Menu);"
. "update{$pageCode}Menu();"
."});"
."</script>"
. "<span id=\"menu_view_edit{$pageCode}\"></span>";
//View by Default
$this->source .=
"<input type=\"hidden\" id=\"hidViewEdit{$pageCode}Menu\" name=\"hidViewEdit{$pageCode}Menu\" value=\"view\">";
//INCLUDE SWITCH CONTENT JAVASCRIPT
JavaScript::addJavaScriptInclude("switchContent");
// }
}
}
| ideonexus/memexplex | memexplex/framework/classes/presentation/menus/MenuViewEditToggle.php | PHP | gpl-3.0 | 2,215 |
package com.teamten.beanstalk;
/*
*
* Copyright 2009-2010 Robert Tykulsker *
* This file is part of JavaBeanstalkCLient.
*
* JavaBeanstalkCLient 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, or alternatively, the BSD license
* supplied
* with this project in the file "BSD-LICENSE".
*
* JavaBeanstalkCLient 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 JavaBeanstalkCLient. If not, see <http://www.gnu.org/licenses/>.
*
*/
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Concrete implementation of the BeanstalkClient interface.
*/
public class BeanstalkClientImpl implements BeanstalkClient {
private static final String CLIENT_VERSION = "1.4.9";
private static final long MAX_PRIORITY = 4294967296L;
private ProtocolHandler protocolHandler = null;
/**
* Create a client with the default {@link BeanstalkClient#DEFAULT_HOST host}
* and {@link BeanstalkClient#DEFAULT_PORT port}.
*
* @throws IOException if it could not connect to the server.
*/
public BeanstalkClientImpl() throws IOException {
this(DEFAULT_HOST, DEFAULT_PORT);
}
/**
* Create a client with the specified host and port.
*
* @param host the hostname to connect to.
* @param port the port to connect to.
* @throws IOException if it could not connect to the server.
*/
public BeanstalkClientImpl(String host, int port) throws IOException {
protocolHandler = new ProtocolHandler(host, port);
}
// ****************************************************************
// Producer methods
// ****************************************************************
@Override // BeanstalkClient
public long put(long priority, int delaySeconds, int timeToRun, byte[] data) throws IOException {
if (data == null) {
throw new NullPointerException("null data");
}
if (priority > MAX_PRIORITY) {
throw new IllegalArgumentException("invalid priority");
}
long jobId = -1;
Request request = new Request(
"put " + priority + " " + delaySeconds + " " + timeToRun + " " + data.length,
new String[] {
"INSERTED", "BURIED"
},
new String[] {
"JOB_TOO_BIG"
},
data,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
if (response != null && response.getStatus().equals("JOB_TOO_BIG")) {
throw new BeanstalkException(response.getStatus());
}
if (response != null && response.isMatchOk()) {
jobId = Long.parseLong(response.getReponse());
}
return jobId;
}
@Override // BeanstalkClient
public void useTube(String tubeName) throws IOException {
if (tubeName == null) {
throw new NullPointerException("null tubeName");
}
Request request = new Request(
"use " + tubeName,
"USING",
null,
null,
ExpectedResponse.None);
protocolHandler.processRequest(request);
}
// ****************************************************************
// Consumer methods
// job-related
// ****************************************************************
@Override // BeanstalkClient
public Job reserve(Integer timeoutSeconds) throws IOException {
Job job = null;
String command = (timeoutSeconds == null)
? "reserve"
: "reserve-with-timeout " + timeoutSeconds.toString();
Request request = new Request(
command,
new String[] {
"RESERVED"
},
new String[] {
"DEADLINE_SOON", "TIMED_OUT",
},
null,
ExpectedResponse.ByteArray,
2);
Response response = protocolHandler.processRequest(request);
if (response != null && response.getStatus().equals("DEADLINE_SOON")) {
throw new BeanstalkException(response.getStatus());
}
if (response != null && response.isMatchOk()) {
long jobId = Long.parseLong(response.getReponse());
job = new JobImpl(jobId);
job.setData((byte[]) response.getData());
}
return job;
}
@Override // BeanstalkClient
public boolean delete(long jobId) throws IOException {
Request request = new Request(
"delete " + jobId,
"DELETED",
"NOT_FOUND",
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return response != null && response.isMatchOk();
}
@Override // BeanstalkClient
public boolean release(long jobId, long priority, int delaySeconds) throws IOException {
Request request = new Request(
"release " + jobId + " " + priority + " " + delaySeconds,
new String[] {
"RELEASED"
},
new String[] {
"NOT_FOUND", "BURIED"
},
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return response != null && response.isMatchOk();
}
@Override // BeanstalkClient
public boolean bury(long jobId, long priority) throws IOException {
Request request = new Request(
"bury " + jobId + " " + priority,
"BURIED",
"NOT_FOUND",
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return response != null && response.isMatchOk();
}
@Override // BeanstalkClient
public boolean touch(long jobId) throws IOException {
Request request = new Request(
"touch " + jobId,
"TOUCHED",
"NOT_FOUND",
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return response != null && response.isMatchOk();
}
// ****************************************************************
// Consumer methods
// tube-related
// ****************************************************************
@Override // BeanstalkClient
public int watch(String tubeName) throws IOException {
if (tubeName == null) {
throw new NullPointerException("null tubeName");
}
Request request = new Request(
"watch " + tubeName,
"WATCHING",
null,
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return Integer.parseInt(response.getReponse());
}
@Override // BeanstalkClient
public int ignore(String tubeName) throws IOException {
if (tubeName == null) {
throw new NullPointerException("null tubeName");
}
Request request = new Request(
"ignore " + tubeName,
new String[] {
"WATCHING", "NOT_IGNORED"
},
null,
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
return (response.getReponse() == null) ? -1 : Integer.parseInt(response.getReponse());
}
// ****************************************************************
// Consumer methods
// peek-related
// ****************************************************************
@Override // BeanstalkClient
public Job peek(long jobId) throws IOException {
Job job = null;
Request request = new Request(
"peek " + jobId,
"FOUND",
"NOT_FOUND",
null,
ExpectedResponse.ByteArray,
2);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
jobId = Long.parseLong(response.getReponse());
job = new JobImpl(jobId);
job.setData((byte[]) response.getData());
}
return job;
}
@Override // BeanstalkClient
public Job peekBuried() throws IOException {
Job job = null;
Request request = new Request(
"peek-buried",
"FOUND",
"NOT_FOUND",
null,
ExpectedResponse.ByteArray,
2);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
long jobId = Long.parseLong(response.getReponse());
job = new JobImpl(jobId);
job.setData((byte[]) response.getData());
}
return job;
}
@Override // BeanstalkClient
public Job peekDelayed() throws IOException {
Job job = null;
Request request = new Request(
"peek-delayed",
"FOUND",
"NOT_FOUND",
null,
ExpectedResponse.ByteArray,
2);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
long jobId = Long.parseLong(response.getReponse());
job = new JobImpl(jobId);
job.setData((byte[]) response.getData());
}
return job;
}
@Override // BeanstalkClient
public Job peekReady() throws IOException {
Job job = null;
Request request = new Request(
"peek-ready",
"FOUND",
"NOT_FOUND",
null,
ExpectedResponse.ByteArray,
2);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
long jobId = Long.parseLong(response.getReponse());
job = new JobImpl(jobId);
job.setData((byte[]) response.getData());
}
return job;
}
@Override // BeanstalkClient
public int kick(int count) throws IOException {
Request request = new Request(
"kick " + count,
"KICKED",
null,
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
count = Integer.parseInt(response.getReponse());
}
return count;
}
// ****************************************************************
// Consumer methods
// stats-related
// ****************************************************************
@SuppressWarnings("unchecked")
@Override // BeanstalkClient
public Map<String, String> statsJob(long jobId) throws IOException {
Request request = new Request(
"stats-job " + jobId,
"OK",
"NOT_FOUND",
null,
ExpectedResponse.Map);
Response response = protocolHandler.processRequest(request);
Map<String, String> map = null;
if (response != null && response.isMatchOk()) {
map = (Map<String, String>) response.getData();
}
return map;
}
@SuppressWarnings("unchecked")
@Override // BeanstalkClient
public Map<String, String> statsTube(String tubeName) throws IOException {
if (tubeName == null) {
return null;
}
Request request = new Request(
"stats-tube " + tubeName,
"OK",
"NOT_FOUND",
null,
ExpectedResponse.Map);
Response response = protocolHandler.processRequest(request);
Map<String, String> map = null;
if (response != null && response.isMatchOk()) {
map = (Map<String, String>) response.getData();
}
return map;
}
@SuppressWarnings("unchecked")
@Override // BeanstalkClient
public Map<String, String> stats() throws IOException {
Request request = new Request(
"stats",
"OK",
null,
null,
ExpectedResponse.Map);
Response response = protocolHandler.processRequest(request);
Map<String, String> map = null;
if (response != null && response.isMatchOk()) {
map = (Map<String, String>) response.getData();
}
return map;
}
@SuppressWarnings("unchecked")
@Override // BeanstalkClient
public List<String> listTubes() throws IOException {
Request request = new Request(
"list-tubes",
"OK",
null,
null,
ExpectedResponse.List);
Response response = protocolHandler.processRequest(request);
List<String> list = null;
if (response != null && response.isMatchOk()) {
list = (List<String>) response.getData();
}
return list;
}
@Override // BeanstalkClient
public String listTubeUsed() throws IOException {
String tubeName = null;
Request request = new Request(
"list-tube-used",
"USING",
null,
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
tubeName = response.getReponse();
}
return tubeName;
}
@SuppressWarnings("unchecked")
@Override // BeanstalkClient
public List<String> listTubesWatched() throws IOException {
Request request = new Request(
"list-tubes-watched",
"OK",
null,
null,
ExpectedResponse.List);
Response response = protocolHandler.processRequest(request);
List<String> list = null;
if (response != null && response.isMatchOk()) {
list = (List<String>) response.getData();
}
return list;
}
@Override // BeanstalkClient
public String getClientVersion() {
return CLIENT_VERSION;
}
@Override // BeanstalkClient
public void close() {
protocolHandler.close();
}
@Override // BeanstalkClient
public boolean pauseTube(String tubeName, int pauseDelay) throws IOException {
Request request = new Request(
"pause-tube " + tubeName + " " + pauseDelay,
"PAUSED",
null,
null,
ExpectedResponse.None);
Response response = protocolHandler.processRequest(request);
if (response != null && response.isMatchOk()) {
return true;
}
return false;
}
@Override // BeanstalkClient
public String getServerVersion() throws IOException {
Map<String, String> stats = stats();
if (stats == null) {
throw new BeanstalkException("could not get stats");
}
return stats.get("version").trim();
}
}
| lkesteloot/JavaBeanstalkClient | src/main/java/com/teamten/beanstalk/BeanstalkClientImpl.java | Java | gpl-3.0 | 16,064 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using CMS.FormControls;
using CMS.Forums;
using CMS.Helpers;
using CMS.Localization;
using CMS.MediaLibrary;
using CMS.Base;
using CMS.SiteProvider;
using CMS.Membership;
using CMS.DocumentEngine;
using CMS.UIControls;
using CMS.ExtendedControls;
using TreeNode = CMS.DocumentEngine.TreeNode;
using CMS.Taxonomy;
using CMS.DataEngine;
using CMS.Synchronization;
using CMS.Modules;
using CMS.Search;
public partial class CMSModules_Departments_FormControls_DepartmentSectionsManager : FormEngineUserControl
{
#region "Constants"
private const int ITEMS_PER_ROW = 4;
private const string FORUM_DOCUMENT_ALIAS = "forums";
private const string MEDIA_DOCUMENT_ALIAS = "media";
private const string HIDDEN_DOCUMENT_ALIAS = ";home;search;rss;";
#endregion
#region "Variables"
private DataSet mTemplateDocuments;
private TreeProvider mTreeProvider;
private bool mDocumentSaved;
private ArrayList mCheckboxReferences;
private string mSelectedValue;
#endregion
#region "Properties"
/// <summary>
/// Gets or sets selected departments.
/// </summary>
public override object Value
{
get
{
StringBuilder sb = new StringBuilder();
if (CheckboxReferences.Count > 0)
{
// Get selected values from registered checkboxes
foreach (CMSCheckBox chk in CheckboxReferences)
{
if (chk.Checked)
{
sb.Append(chk.Attributes["Value"].ToLowerCSafe());
sb.Append(";");
}
}
return sb.ToString().TrimEnd(';');
}
return null;
}
set
{
mSelectedValue = ValidationHelper.GetString(value, null);
}
}
/// <summary>
/// Department template path.
/// </summary>
private string DepartmentTemplatePath
{
get
{
return SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSDepartmentTemplatePath");
}
}
/// <summary>
/// Gets DataSet of first level template documents.
/// </summary>
public DataSet TemplateDocuments
{
get
{
if (mTemplateDocuments == null)
{
string templatePath = DepartmentTemplatePath;
if (!String.IsNullOrEmpty(templatePath))
{
templatePath = TreePathUtils.EnsureSingleNodePath(templatePath).TrimEnd('/') + "/%";
mTemplateDocuments = DocumentHelper.GetDocuments(SiteContext.CurrentSiteName, templatePath, null, false, null, "NodeAlias != ''", "NodeOrder ASC", 1, false, 0, "NodeID, DocumentCulture, NodeAlias, NodeClassID", null);
}
}
return mTemplateDocuments;
}
}
/// <summary>
/// ArrayList with checkbox references.
/// </summary>
private ArrayList CheckboxReferences
{
get
{
if (mCheckboxReferences == null)
{
mCheckboxReferences = new ArrayList();
}
return mCheckboxReferences;
}
}
/// <summary>
/// Gets instance of tree provider.
/// </summary>
private TreeProvider TreeProvider
{
get
{
if (mTreeProvider == null)
{
mTreeProvider = new TreeProvider(MembershipContext.AuthenticatedUser);
}
return mTreeProvider;
}
}
#endregion
#region "Control methods"
/// <summary>
/// Page load.
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
if (Form == null)
{
return;
}
GenerateContent();
// Attach on after save event
Form.OnAfterSave += ProcessDepartment;
//Atach Pre Render event
Page.PreRender += Page_PreRender;
}
/// <summary>
/// PreRender action on which security settings are set.
/// </summary>
private void Page_PreRender(object sender, EventArgs e)
{
if ((Form == null) || !mDocumentSaved)
{
return;
}
TreeNode editedNode = Form.EditedObject as TreeNode;
// Create or rebuild department content index
CreateDepartmentContentSearchIndex(editedNode);
if ((editedNode == null) || !editedNode.NodeIsACLOwner)
{
return;
}
ForumInfo fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);
// Check if forum of media library exists
if ((fi == null) && (mi == null))
{
return;
}
// Get allowed roles ID
int aclID = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
DataSet listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
string roleIDs = null;
if (!DataHelper.DataSourceIsEmpty(listRoles))
{
IList<string> roles = DataHelper.GetStringValues(listRoles.Tables[0], "RoleID");
roleIDs = TextHelper.Join(";", roles);
}
// Set permissions for forum
if (fi != null)
{
// Get resource object
ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");
// Get permissions IDs
DataSet dsForumPerm = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resForums.ResourceID + " AND (PermissionName != '" + CMSAdminControl.PERMISSION_READ + "' AND PermissionName != '" + CMSAdminControl.PERMISSION_MODIFY + "')", null, 0, "PermissionID");
string forumPermissions = null;
if (!DataHelper.DataSourceIsEmpty(dsForumPerm))
{
foreach (DataRow drForumPerm in dsForumPerm.Tables[0].Rows)
{
forumPermissions += drForumPerm["PermissionID"] + ";";
}
forumPermissions = forumPermissions.TrimEnd(';');
}
// Delete old permissions apart attach file permission
ForumRoleInfoProvider.DeleteAllRoles("ForumID = " + fi.ForumID + " AND PermissionID IN (" + forumPermissions.Replace(";", ", ") + ")");
// Set forum permissions
ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIDs, forumPermissions);
// Log staging task
SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
}
// Set permissions for media library
if (mi == null)
{
return;
}
// Get resource object
ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");
// Get permissions IDs
DataSet dsMediaLibPerm = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resMediaLibs.ResourceID + " AND (PermissionName = 'LibraryAccess' OR PermissionName = 'FileCreate')", null, 0, "PermissionID");
string mediaLibPermissions = null;
if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
{
foreach (DataRow drMediaLibPerm in dsMediaLibPerm.Tables[0].Rows)
{
mediaLibPermissions += drMediaLibPerm["PermissionID"] + ";";
}
mediaLibPermissions = mediaLibPermissions.TrimEnd(';');
}
// Delete old permissions only for Create file and See library content permissions
MediaLibraryRolePermissionInfoProvider.DeleteAllRoles("LibraryID = " + mi.LibraryID + " AND PermissionID IN (" + mediaLibPermissions.Replace(";", ", ") + ")");
// Set media library permissions
MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIDs, mediaLibPermissions);
// Log staging task
SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
}
/// <summary>
/// Generate control output.
/// </summary>
public void GenerateContent()
{
string templatePath = DepartmentTemplatePath;
if (String.IsNullOrEmpty(templatePath))
{
ltlContent.Text = ResHelper.GetString("departmentsectionsmanager.notemplate");
ltlContent.Visible = true;
}
else
{
if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
{
int counter = 0;
Table tb = new Table();
string value = ValidationHelper.GetString(mSelectedValue, "");
string docAliases = ";" + value.ToLowerCSafe() + ";";
TreeNode editedNode = (TreeNode)Form.EditedObject;
if (Form.IsInsertMode)
{
// Alias path for new department has to have special 'child node path' because of correct check for document type scopes
editedNode.SetValue("NodeAliasPath", ((TreeNode)Form.ParentObject).NodeAliasPath + "/department");
}
TableRow tr = new TableRow();
foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
{
// For each section td element is generated
string docAlias = ValidationHelper.GetString(drDoc["NodeAlias"], "");
TableCell td = new TableCell();
CMSCheckBox cbCell = new CMSCheckBox();
cbCell.ID = "chckSection" + counter;
cbCell.Text = docAlias;
cbCell.Attributes.Add("Value", docAlias);
// Check if child allowed
int sourceClassId = ValidationHelper.GetInteger(drDoc["NodeClassID"], 0);
if (!DocumentHelper.IsDocumentTypeAllowed(editedNode, sourceClassId))
{
cbCell.Enabled = false;
cbCell.ToolTip = ResHelper.GetString("departmentsectionsmanager.notallowedchild");
}
// Disable default hidden documents
if (HIDDEN_DOCUMENT_ALIAS.Contains(";" + docAlias.ToLowerCSafe() + ";"))
{
cbCell.Checked = cbCell.Enabled;
cbCell.Enabled = false;
}
// Check for selected value
if (docAliases.Contains(";" + docAlias.ToLowerCSafe() + ";") || ((mSelectedValue == null) && (Form.Mode == FormModeEnum.Insert)))
{
if (cbCell.Enabled)
{
cbCell.Checked = true;
}
}
// If editing existing document register alert script
if ((Form.Mode != FormModeEnum.Insert) && cbCell.Checked)
{
cbCell.Attributes.Add("OnClick", "if(!this.checked){alert(" + ScriptHelper.GetString(ResHelper.GetString("departmentsectionsmanagerformcontrol.removesectionwarning")) + ");}");
}
// Add reference to checkbox arraylist
CheckboxReferences.Add(cbCell);
counter++;
td.Controls.Add(cbCell);
tr.Cells.Add(td);
// If necessary create new row
if ((counter % ITEMS_PER_ROW) == 0)
{
tr.CssClass = "Row";
tb.Rows.Add(tr);
tr = new TableRow();
}
}
// If last row contains data add it
if (counter > 0)
{
tb.Rows.Add(tr);
}
pnlContent.Controls.Add(tb);
}
else
{
ltlContent.Text = ResHelper.GetString("departmentsectionsmanager.notemplate");
ltlContent.Visible = true;
}
}
}
#endregion
#region "Additional department actions"
/// <summary>
/// Copy documents section.
/// </summary>
/// <param name="source">Source document</param>
/// <param name="target">Target document</param>
/// <param name="tree">Tree provider</param>
private void CopyDocumentSection(TreeNode source, TreeNode target, TreeProvider tree)
{
DocumentHelper.CopyDocument(source, target, true, tree);
}
/// <summary>
/// Delete documents section.
/// </summary>
/// <param name="node">Node to be deleted</param>
/// <param name="tree">Tree provider</param>
private void DeleteDocumentSection(TreeNode node, TreeProvider tree)
{
// Delete all document cultures
DocumentHelper.DeleteDocument(node, tree, true);
}
/// <summary>
/// Creates department forum group.
/// </summary>
/// <param name="departmentNode">Department node</param>
private void CreateDepartmentForumGroup(TreeNode departmentNode)
{
// Set general values
string departmentName = departmentNode.GetDocumentName();
string suffix = "";
#region "Create forum group"
// Get forum group code name
string groupCodeName = "Department_" + departmentNode.NodeGUID;
// Check if forum group with given name already exists
if (ForumGroupInfoProvider.GetForumGroupInfo(groupCodeName, SiteContext.CurrentSiteID) != null)
{
return;
}
// Create base URL for forums
string baseUrl = DocumentURLProvider.GetUrl(departmentNode.NodeAliasPath + "/" + FORUM_DOCUMENT_ALIAS);
ForumGroupInfo forumGroupObj = new ForumGroupInfo();
forumGroupObj.GroupDescription = "Forum group for " + departmentName + " department.";
suffix = " forum group";
forumGroupObj.GroupDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix;
forumGroupObj.GroupName = groupCodeName;
forumGroupObj.GroupOrder = 0;
forumGroupObj.GroupEnableQuote = true;
forumGroupObj.GroupSiteID = SiteContext.CurrentSiteID;
forumGroupObj.GroupBaseUrl = baseUrl;
// Additional settings
forumGroupObj.GroupEnableCodeSnippet = true;
forumGroupObj.GroupEnableFontBold = true;
forumGroupObj.GroupEnableFontColor = true;
forumGroupObj.GroupEnableFontItalics = true;
forumGroupObj.GroupEnableFontStrike = true;
forumGroupObj.GroupEnableFontUnderline = true;
forumGroupObj.GroupEnableQuote = true;
forumGroupObj.GroupEnableURL = true;
forumGroupObj.GroupEnableImage = true;
ForumGroupInfoProvider.SetForumGroupInfo(forumGroupObj);
#endregion
#region "Create forum"
string codeName = "Default_department_" + departmentNode.NodeGUID;
// Check if forum with given name already exists
if (ForumInfoProvider.GetForumInfo(codeName, SiteContext.CurrentSite.SiteID) != null)
{
return;
}
ForumInfo forumObj = new ForumInfo();
forumObj.ForumSiteID = SiteContext.CurrentSiteID;
forumObj.ForumIsLocked = false;
forumObj.ForumOpen = true;
forumObj.ForumDisplayEmails = false;
forumObj.ForumDescription = "Forum for " + departmentName + " department.";
forumObj.ForumRequireEmail = false;
suffix = " forum";
forumObj.ForumDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix;
forumObj.ForumName = codeName;
forumObj.ForumGroupID = forumGroupObj.GroupID;
forumObj.ForumModerated = false;
forumObj.ForumAccess = 40000;
forumObj.ForumPosts = 0;
forumObj.ForumThreads = 0;
forumObj.ForumPostsAbsolute = 0;
forumObj.ForumThreadsAbsolute = 0;
forumObj.ForumOrder = 0;
forumObj.ForumUseCAPTCHA = false;
forumObj.SetValue("ForumHTMLEditor", null);
// Set security
forumObj.AllowAccess = SecurityAccessEnum.AuthorizedRoles;
forumObj.AllowAttachFiles = SecurityAccessEnum.AuthorizedRoles;
forumObj.AllowMarkAsAnswer = SecurityAccessEnum.AuthorizedRoles;
forumObj.AllowPost = SecurityAccessEnum.AuthorizedRoles;
forumObj.AllowReply = SecurityAccessEnum.AuthorizedRoles;
forumObj.AllowSubscribe = SecurityAccessEnum.AuthorizedRoles;
if (ForumInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Forums, ObjectActionEnum.Insert))
{
ForumInfoProvider.SetForumInfo(forumObj);
}
#endregion
}
/// <summary>
/// Creates department media library.
/// </summary>
/// <param name="departmentNode">Department node</param>
private void CreateDepartmentMediaLibrary(TreeNode departmentNode)
{
// Set general values
string departmentName = departmentNode.GetDocumentName();
string codeName = "Department_" + departmentNode.NodeGUID;
string suffix = "";
// Check if library with same name already exists
MediaLibraryInfo mlInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(codeName, SiteContext.CurrentSiteName);
if (mlInfo != null)
{
return;
}
// Create new object (record) if needed
mlInfo = new MediaLibraryInfo();
suffix = " media library";
mlInfo.LibraryDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix;
mlInfo.LibraryFolder = departmentNode.NodeAlias;
mlInfo.LibraryDescription = "Media library for " + departmentName + " department.";
mlInfo.LibraryName = codeName;
mlInfo.LibrarySiteID = SiteContext.CurrentSiteID;
// Set security
mlInfo.FileCreate = SecurityAccessEnum.AuthorizedRoles;
mlInfo.FileDelete = SecurityAccessEnum.AuthorizedRoles;
mlInfo.FileModify = SecurityAccessEnum.AuthorizedRoles;
mlInfo.FolderCreate = SecurityAccessEnum.AuthorizedRoles;
mlInfo.FolderDelete = SecurityAccessEnum.AuthorizedRoles;
mlInfo.FolderModify = SecurityAccessEnum.AuthorizedRoles;
mlInfo.Access = SecurityAccessEnum.AuthorizedRoles;
try
{
MediaLibraryInfoProvider.SetMediaLibraryInfo(mlInfo);
}
catch
{
return;
}
}
/// <summary>
/// Creates or rebuild department content search index.
/// </summary>
/// <param name="departmentNode">Department node</param>
private void CreateDepartmentContentSearchIndex(TreeNode departmentNode)
{
string codeName = "default_department_" + departmentNode.NodeGUID;
string departmentName = departmentNode.GetDocumentName();
SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(codeName);
if (sii == null)
{
// Create search index info
sii = new SearchIndexInfo();
sii.IndexName = codeName;
string suffix = " - Default";
sii.IndexDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix;
sii.IndexAnalyzerType = SearchAnalyzerTypeEnum.StandardAnalyzer;
sii.IndexType = TreeNode.OBJECT_TYPE;
sii.IndexIsCommunityGroup = false;
// Create search index settings info
SearchIndexSettingsInfo sisi = new SearchIndexSettingsInfo();
sisi.ID = Guid.NewGuid();
sisi.Path = departmentNode.NodeAliasPath + "/%";
sisi.Type = SearchIndexSettingsInfo.TYPE_ALLOWED;
sisi.ClassNames = "";
// Create settings item
SearchIndexSettings sis = new SearchIndexSettings();
// Update settings item
sis.SetSearchIndexSettingsInfo(sisi);
// Update xml value
sii.IndexSettings = sis;
SearchIndexInfoProvider.SetSearchIndexInfo(sii);
// Assign to current website
SearchIndexSiteInfoProvider.AddSearchIndexToSite(sii.IndexID, SiteContext.CurrentSiteID);
}
// Add current culture to search index
CultureInfo ci = CultureInfoProvider.GetCultureInfo(departmentNode.DocumentCulture);
SearchIndexCultureInfoProvider.AddSearchIndexCulture(sii.IndexID, ci.CultureID);
// Rebuild search index
SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Rebuild, null, null, sii.IndexName, sii.IndexID);
}
/// <summary>
/// Creates forum search index.
/// </summary>
/// <param name="departmentNode">Department node</param>
private void CreateDepartmentForumSearchIndex(TreeNode departmentNode)
{
string codeName = "forums_department_" + departmentNode.NodeGUID;
string departmentName = departmentNode.GetDocumentName();
SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(codeName);
if (sii == null)
{
// Create search index info
sii = new SearchIndexInfo();
sii.IndexName = codeName;
string suffix = " - Forums";
sii.IndexDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix;
sii.IndexAnalyzerType = SearchAnalyzerTypeEnum.StandardAnalyzer;
sii.IndexType = PredefinedObjectType.FORUM;
sii.IndexIsCommunityGroup = false;
// Create search index settings info
SearchIndexSettingsInfo sisi = new SearchIndexSettingsInfo();
sisi.ID = Guid.NewGuid();
sisi.Type = SearchIndexSettingsInfo.TYPE_ALLOWED;
sisi.SiteName = SiteContext.CurrentSiteName;
sisi.ForumNames = "*_department_" + departmentNode.NodeGUID;
// Create settings item
SearchIndexSettings sis = new SearchIndexSettings();
// Update settings item
sis.SetSearchIndexSettingsInfo(sisi);
// Update xml value
sii.IndexSettings = sis;
SearchIndexInfoProvider.SetSearchIndexInfo(sii);
// Assign to current website and current culture
SearchIndexSiteInfoProvider.AddSearchIndexToSite(sii.IndexID, SiteContext.CurrentSiteID);
CultureInfo ci = CultureInfoProvider.GetCultureInfo(departmentNode.DocumentCulture);
SearchIndexCultureInfoProvider.AddSearchIndexCulture(sii.IndexID, ci.CultureID);
}
}
/// <summary>
/// Process additional department tasks.
/// </summary>
public void ProcessDepartment(object sender, EventArgs e)
{
TreeNode editedNode = Form.EditedObject as TreeNode;
// Get department template source document
TreeNode sourceNode = DocumentHelper.GetDocument(SiteContext.CurrentSiteName, DepartmentTemplatePath, null, true, null, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider);
// Copy relevant template data to department document. Proceed only when creating a department, updating a department must not rewrite its data with template's data.
if (Form.IsInsertMode && (sourceNode != null))
{
string excludeColumns = "DocumentName;NodeAlias;DocumentTagGroupID;DocumentStylesheetID;DocumentPublishFrom;DocumentPublishTo";
DocumentHelper.CopyNodeData(sourceNode, editedNode, new CopyNodeDataSettings(true, true, false, true, true, false, false, false, excludeColumns));
DocumentHelper.UpdateDocument(editedNode, TreeProvider);
}
#region "Create department tag group"
// Get tag group info
TagGroupInfo tgi = TagGroupInfoProvider.GetTagGroupInfo(editedNode.DocumentTagGroupID);
// If not exist, create new tag group and set it to document
if (tgi == null)
{
// Populate tag group info fields
tgi = new TagGroupInfo();
tgi.TagGroupDisplayName = editedNode.GetDocumentName();
tgi.TagGroupName = editedNode.NodeGUID.ToString();
tgi.TagGroupDescription = "";
tgi.TagGroupSiteID = SiteContext.CurrentSiteID;
tgi.TagGroupIsAdHoc = false;
// Store tag group info to DB
TagGroupInfoProvider.SetTagGroupInfo(tgi);
// Update document Tag group ID
editedNode.DocumentTagGroupID = tgi.TagGroupID;
DocumentHelper.UpdateDocument(editedNode, TreeProvider);
}
#endregion
if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
{
// List of selected documents
string selectedDocs = ";" + Value + ";";
// Get already created documents under edited document
DataSet dsExistingDocs = DocumentHelper.GetDocuments(SiteContext.CurrentSiteName, editedNode.NodeAliasPath + "/%", editedNode.DocumentCulture, true, null, null, null, 1, false, 0, "NodeAlias, " + DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, null);
StringBuilder sbExistDocs = new StringBuilder();
// Process existing documents to obtain list of aliases
foreach (DataRow drExistDoc in dsExistingDocs.Tables[0].Rows)
{
sbExistDocs.Append(";");
sbExistDocs.Append(drExistDoc["NodeAlias"].ToString().ToLowerCSafe());
}
sbExistDocs.Append(";");
string existingDocs = sbExistDocs.ToString();
// Set same ordering as for original template documents
bool orgUseAutomaticOrdering = TreeProvider.UseAutomaticOrdering;
TreeProvider.UseAutomaticOrdering = false;
// Process template documents
foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
{
if (DocumentHelper.IsDocumentTypeAllowed(editedNode, ValidationHelper.GetInteger(drDoc["NodeClassID"], 0)))
{
string nodeAlias = drDoc["NodeAlias"].ToString().ToLowerCSafe();
string contNodeAlias = ";" + nodeAlias + ";";
// Set marks
bool existing = existingDocs.Contains(contNodeAlias);
bool selected = selectedDocs.Contains(contNodeAlias);
int nodeId = ValidationHelper.GetInteger(drDoc["NodeID"], 0);
string docCulture = ValidationHelper.GetString(drDoc["DocumentCulture"], "");
TreeNode srcNode = DocumentHelper.GetDocument(nodeId, docCulture, editedNode.TreeProvider);
// Check if section exists
if (srcNode != null)
{
// Copy or remove marked document sections
if (selected)
{
if (!existing)
{
CopyDocumentSection(srcNode, editedNode, TreeProvider);
}
}
else
{
if (existing)
{
// Select node to delete
TreeNode delNode = TreeHelper.SelectSingleNode(editedNode.NodeAliasPath + "/" + nodeAlias);
if (delNode != null)
{
DeleteDocumentSection(delNode, TreeProvider);
}
}
}
// Process additional operations
if (selected && !existing)
{
switch (nodeAlias)
{
// Create department forum
case FORUM_DOCUMENT_ALIAS:
CreateDepartmentForumGroup(editedNode);
CreateDepartmentForumSearchIndex(editedNode);
break;
// Create media library
case MEDIA_DOCUMENT_ALIAS:
CreateDepartmentMediaLibrary(editedNode);
break;
}
}
}
}
}
// Set previous ordering
TreeProvider.UseAutomaticOrdering = orgUseAutomaticOrdering;
}
mDocumentSaved = true;
}
#endregion
} | CCChapel/ccchapel.com | CMS/CMSModules/Departments/FormControls/DepartmentSectionsManager.ascx.cs | C# | gpl-3.0 | 29,179 |
(function() {
"use strict";
pwf.reg_class('ui.list.team.member', {
'parents':['ui.link'],
'storage':{
'opts':{
'path':'user'
}
},
'proto':{
'prefix':'member',
'els':[
'avatar',
{
'name':'data',
'els':['name', 'roles']
},
{
'name':'cleaner',
'prefix':null
}
],
'create_link':function(p)
{
p('fill');
},
'fill':function()
{
var
el = this.get_el(),
item = this.get('item'),
user = item.get('user');
this.set('params', {'user':this.get('user').get('id')});
el.data.name.html(pwf.site.get_user_name(user));
pwf.thumb.fit(user.get('avatar'), el.avatar);
pwf.create('ui.intra.team.member.role.list', {
'parent':el.data.roles,
'roles':item.get('roles')
});
}
}
});
})();
| just-paja/improliga | share/scripts/ui/list/team/member.js | JavaScript | gpl-3.0 | 819 |
package com.example.weiguangmeng.contentprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by weiguangmeng on 16/2/28.
*/
public class BookProvider extends ContentProvider {
private static final String TAG = "BookProvider";
public static final String AUTHORITY = "com.example.weiguangmeng.contentprovider.provider";
public static final Uri BOOK_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/book");
public static final Uri USER_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/user");
public static final int BOOK_URI_CODE = 0;
public static final int USER_URI_CODE = 1;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE);
sUriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE);
} //Java 静态代码块,只执行一遍, 常常进行初始化
private Context mContext;
private SQLiteDatabase mDb;
@Override
public boolean onCreate() {
Log.d(TAG, "onCreate, current thread:" + Thread.currentThread().getName());
mContext = getContext();
initProviderData();
return true; //true : the provider success loaded
}
private void initProviderData() {
mDb = new DbOpenHelper(mContext, null, null, 1).getWritableDatabase();
mDb.execSQL("delete from " + DbOpenHelper.BOOK_TABLE_NAME);
mDb.execSQL("delete from " + DbOpenHelper.USER_TABLE_NAME);
mDb.execSQL("insert into book values(3, 'Android');");
mDb.execSQL("insert into book values(4, 'Ios');");
mDb.execSQL("insert into book values(5, 'Html');");
mDb.execSQL("insert into user values(1, 'jake', 1);");
mDb.execSQL("insert into user values(2, 'jasmine', 0);");
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.d(TAG, "query, current thread:" + Thread.currentThread().getName());
String table = getTableName(uri);
if(null == table) {
throw new IllegalArgumentException("Unsupported Uri:" + uri);
}
return mDb.query(table, projection, selection, selectionArgs, null, null, sortOrder, null);
}
@Nullable
@Override
public String getType(Uri uri) {
Log.d(TAG, "getType");
return null;
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.d(TAG, "insert");
String table = getTableName(uri);
if(null == table) {
throw new IllegalArgumentException("Unsupported Uri:" +uri);
}
mDb.insert(table, null, values);
mContext.getContentResolver().notifyChange(uri, null);
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.d(TAG, "delete");
String table = getTableName(uri);
if(null == table) {
throw new IllegalArgumentException("Unsupported Uri:" + uri);
}
int count = mDb.delete(table, selection, selectionArgs);
if(count > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Log.d(TAG, "update");
String table = getTableName(uri);
if(null == table) {
throw new IllegalArgumentException("Unsupported URI:" + uri);
}
int row = mDb.update(table, values, selection, selectionArgs);
if(row > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return row;
}
private String getTableName(Uri uri) {
String tableName = null;
switch (sUriMatcher.match(uri)) {
case BOOK_URI_CODE:
tableName = DbOpenHelper.BOOK_TABLE_NAME;
break;
case USER_URI_CODE:
tableName = DbOpenHelper.USER_TABLE_NAME;
break;
default:
break;
}
return tableName;
}
}
| supermanmwg/AndroidArtExplore | chapter2/ContentProvider/app/src/main/java/com/example/weiguangmeng/contentprovider/BookProvider.java | Java | gpl-3.0 | 4,508 |
/*! \file
\brief Header of the bt_utmsg_piecewish_t
*/
#ifndef __NEOIP_BT_UTMSG_PIECEWISH_HPP__
#define __NEOIP_BT_UTMSG_PIECEWISH_HPP__
/* system include */
#include <list>
/* local include */
#include "neoip_bt_utmsg_piecewish_wikidbg.hpp"
#include "neoip_bt_utmsg_vapi.hpp"
#include "neoip_bt_utmsg_cb.hpp"
#include "neoip_bt_utmsgtype.hpp"
#include "neoip_bt_err.hpp"
#include "neoip_bitfield.hpp"
#include "neoip_tokeep_check.hpp"
#include "neoip_copy_ctor_checker.hpp"
#include "neoip_namespace.hpp"
NEOIP_NAMESPACE_BEGIN
// list of forward declaration
class bt_swarm_t;
class bt_cmd_t;
class bt_utmsg_piecewish_cnx_t;
/** \brief class definition for bt_peersrc for http
*
* - it MUST be ctor after bt_swarm_t and dtor before
*/
class bt_utmsg_piecewish_t : NEOIP_COPY_CTOR_DENY, public bt_utmsg_vapi_t
, private wikidbg_obj_t<bt_utmsg_piecewish_t, bt_utmsg_piecewish_wikidbg_init, bt_utmsg_vapi_t>
{
private:
bt_swarm_t * bt_swarm; //!< backpointer to the next
bitfield_t m_local_pwish; //!< the local piecewish
/*************** internal function *******************************/
bitfield_t generate_local_pwish() throw();
/*************** bt_cmd_t building *******************************/
static bt_cmd_t build_cmd_dowish_field(const bitfield_t &wishfield) throw();
static bt_cmd_t build_cmd_delta_bitfield(const bitfield_t &old_piecewish
, const bitfield_t &new_piecewish) throw();
static bt_cmd_t build_cmd_pieceidx(const std::string &cmx_str, size_t pieceidx) throw();
static bt_cmd_t build_cmd_dowish_pieceidx(size_t pieceidx) throw();
static bt_cmd_t build_cmd_nowish_pieceidx(size_t pieceidx) throw();
/*************** bt_utmsg_piecewish_cnx_t *******************************/
std::list<bt_utmsg_piecewish_cnx_t *> cnx_db;
void cnx_dolink(bt_utmsg_piecewish_cnx_t *cnx) throw() { cnx_db.push_back(cnx); }
void cnx_unlink(bt_utmsg_piecewish_cnx_t *cnx) throw() { cnx_db.remove(cnx); }
void send_cmd_to_all_cnx(const bt_cmd_t &bt_cmd) throw();
/*************** callback stuff ***************************************/
bt_utmsg_cb_t * utmsg_cb; //!< callback used to notify peersrc result
void * userptr; //!< userptr associated with the callback
bool notify_utmsg_cb(const bt_utmsg_event_t &event) throw();
TOKEEP_CHECK_DECL_DFL(); //!< used to sanity check the 'tokeep' value returned by callback
public:
/*************** ctor/dtor ***************************************/
bt_utmsg_piecewish_t() throw();
~bt_utmsg_piecewish_t() throw();
/*************** setup function ***************************************/
bt_err_t start(bt_swarm_t *bt_swarm, bt_utmsg_cb_t *utmsg_cb
, void *userptr) throw();
/*************** Query function ***************************************/
bt_swarm_t * get_swarm() const throw() { return bt_swarm; }
const bitfield_t & local_pwish() const throw() { return m_local_pwish; }
size_t nb_piece() const throw() { return local_pwish().size();}
bool local_pwish(size_t pieceidx) const throw() { return local_pwish()[pieceidx]; }
/*************** Action function *******************************/
void notify_pieceprec_change() throw();
void declare_piece_newly_avail(size_t piece_idx) throw();
void declare_piece_nomore_avail(size_t piece_idx) throw();
/*************** bt_utmsg_vapi_t *******************************/
bt_utmsgtype_t utmsgtype() const throw() { return bt_utmsgtype_t::PIECEWISH; }
std::string utmsgstr() const throw();
bt_utmsg_cnx_vapi_t * cnx_ctor(bt_swarm_full_utmsg_t *full_utmsg) throw();
/*************** List of friend class *******************************/
friend class bt_utmsg_piecewish_wikidbg_t;
friend class bt_utmsg_piecewish_cnx_t;
};
NEOIP_NAMESPACE_END
#endif /* __NEOIP_BT_UTMSG_PIECEWISH_HPP__ */
| jeromeetienne/neoip | src/neoip_bt_plugin/utmsg/impl/piecewish/neoip_bt_utmsg_piecewish.hpp | C++ | gpl-3.0 | 3,792 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ReactorConfig(AppConfig):
name = 'reactor'
| cholarajaa/cold-temperature | hotorcold/reactor/apps.py | Python | gpl-3.0 | 154 |
package hadukiclient.serv_connection;
/**
* <p>^Cg: utv</p>
*
* <p>à¾: </p>
*
* <p>ì : Copyright (c) 2007 PSI</p>
*
* <p>ïм: </p>
*
* @author ¢üÍ
* @version 1.0
*/
import java.security.Key;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* Calculates the various Type 3 responses.
*/
public class Responses {
static{
java.security.Security.addProvider(new BouncyCastleProvider());
}
/**
* Calculates the LM Response for the given challenge, using the specified
* password.
*
* @param password The user's password.
* @param challenge The Type 2 challenge from the server.
*
* @return The LM Response.
*/
public static byte[] getLMResponse(String password, byte[] challenge)
throws Exception {
byte[] lmHash = lmHash(password);
return lmResponse(lmHash, challenge);
}
/**
* Calculates the NTLM Response for the given challenge, using the
* specified password.
*
* @param password The user's password.
* @param challenge The Type 2 challenge from the server.
*
* @return The NTLM Response.
*/
public static byte[] getNTLMResponse(String password, byte[] challenge)
throws Exception {
byte[] ntlmHash = ntlmHash(password);
return lmResponse(ntlmHash, challenge);
}
/**
* Calculates the NTLMv2 Response for the given challenge, using the
* specified authentication target, username, password, target information
* block, and client nonce.
*
* @param target The authentication target (i.e., domain).
* @param user The username.
* @param password The user's password.
* @param targetInformation The target information block from the Type 2
* message.
* @param challenge The Type 2 challenge from the server.
* @param clientNonce The random 8-byte client nonce.
*
* @return The NTLMv2 Response.
*/
public static byte[] getNTLMv2Response(String target, String user,
String password, byte[] targetInformation, byte[] challenge,
byte[] clientNonce) throws Exception {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
byte[] blob = createBlob(targetInformation, clientNonce);
return lmv2Response(ntlmv2Hash, blob, challenge);
}
/**
* Calculates the LMv2 Response for the given challenge, using the
* specified authentication target, username, password, and client
* challenge.
*
* @param target The authentication target (i.e., domain).
* @param user The username.
* @param password The user's password.
* @param challenge The Type 2 challenge from the server.
* @param clientNonce The random 8-byte client nonce.
*
* @return The LMv2 Response.
*/
public static byte[] getLMv2Response(String target, String user,
String password, byte[] challenge, byte[] clientNonce)
throws Exception {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
return lmv2Response(ntlmv2Hash, clientNonce, challenge);
}
/**
* Calculates the NTLM2 Session Response for the given challenge, using the
* specified password and client nonce.
*
* @param password The user's password.
* @param challenge The Type 2 challenge from the server.
* @param clientNonce The random 8-byte client nonce.
*
* @return The NTLM2 Session Response. This is placed in the NTLM
* response field of the Type 3 message; the LM response field contains
* the client nonce, null-padded to 24 bytes.
*/
public static byte[] getNTLM2SessionResponse(String password,
byte[] challenge, byte[] clientNonce) throws Exception {
byte[] ntlmHash = ntlmHash(password);
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(challenge);
md5.update(clientNonce);
byte[] sessionHash = new byte[8];
System.arraycopy(md5.digest(), 0, sessionHash, 0, 8);
return lmResponse(ntlmHash, sessionHash);
}
/**
* Creates the LM Hash of the user's password.
*
* @param password The password.
*
* @return The LM Hash of the given password, used in the calculation
* of the LM Response.
*/
private static byte[] lmHash(String password) throws Exception {
byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
int length = Math.min(oemPassword.length, 14);
byte[] keyBytes = new byte[14];
System.arraycopy(oemPassword, 0, keyBytes, 0, length);
Key lowKey = createDESKey(keyBytes, 0);
Key highKey = createDESKey(keyBytes, 7);
byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowHash = des.doFinal(magicConstant);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highHash = des.doFinal(magicConstant);
byte[] lmHash = new byte[16];
System.arraycopy(lowHash, 0, lmHash, 0, 8);
System.arraycopy(highHash, 0, lmHash, 8, 8);
return lmHash;
}
/**
* Creates the NTLM Hash of the user's password.
*
* @param password The password.
*
* @return The NTLM Hash of the given password, used in the calculation
* of the NTLM Response and the NTLMv2 and LMv2 Hashes.
*/
private static byte[] ntlmHash(String password) throws Exception {
byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
MessageDigest md4 = MessageDigest.getInstance("MD4");
return md4.digest(unicodePassword);
}
/**
* Creates the NTLMv2 Hash of the user's password.
*
* @param target The authentication target (i.e., domain).
* @param user The username.
* @param password The password.
*
* @return The NTLMv2 Hash, used in the calculation of the NTLMv2
* and LMv2 Responses.
*/
private static byte[] ntlmv2Hash(String target, String user,
String password) throws Exception {
byte[] ntlmHash = ntlmHash(password);
String identity = user.toUpperCase() + target.toUpperCase();
return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
}
/**
* Creates the LM Response from the given hash and Type 2 challenge.
*
* @param hash The LM or NTLM Hash.
* @param challenge The server challenge from the Type 2 message.
*
* @return The response (either LM or NTLM, depending on the provided
* hash).
*/
private static byte[] lmResponse(byte[] hash, byte[] challenge)
throws Exception {
byte[] keyBytes = new byte[21];
System.arraycopy(hash, 0, keyBytes, 0, 16);
Key lowKey = createDESKey(keyBytes, 0);
Key middleKey = createDESKey(keyBytes, 7);
Key highKey = createDESKey(keyBytes, 14);
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, middleKey);
byte[] middleResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highResponse = des.doFinal(challenge);
byte[] lmResponse = new byte[24];
System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
System.arraycopy(highResponse, 0, lmResponse, 16, 8);
return lmResponse;
}
/**
* Creates the LMv2 Response from the given hash, client data, and
* Type 2 challenge.
*
* @param hash The NTLMv2 Hash.
* @param clientData The client data (blob or client nonce).
* @param challenge The server challenge from the Type 2 message.
*
* @return The response (either NTLMv2 or LMv2, depending on the
* client data).
*/
private static byte[] lmv2Response(byte[] hash, byte[] clientData,
byte[] challenge) throws Exception {
byte[] data = new byte[challenge.length + clientData.length];
System.arraycopy(challenge, 0, data, 0, challenge.length);
System.arraycopy(clientData, 0, data, challenge.length,
clientData.length);
byte[] mac = hmacMD5(data, hash);
byte[] lmv2Response = new byte[mac.length + clientData.length];
System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
System.arraycopy(clientData, 0, lmv2Response, mac.length,
clientData.length);
return lmv2Response;
}
/**
* Creates the NTLMv2 blob from the given target information block and
* client nonce.
*
* @param targetInformation The target information block from the Type 2
* message.
* @param clientNonce The random 8-byte client nonce.
*
* @return The blob, used in the calculation of the NTLMv2 Response.
*/
private static byte[] createBlob(byte[] targetInformation,
byte[] clientNonce) {
byte[] blobSignature = new byte[] {
(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
};
byte[] reserved = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte[] unknown1 = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte[] unknown2 = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
long time = System.currentTimeMillis();
time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
time *= 10000; // tenths of a microsecond.
// convert to little-endian byte array.
byte[] timestamp = new byte[8];
for (int i = 0; i < 8; i++) {
timestamp[i] = (byte) time;
time >>>= 8;
}
byte[] blob = new byte[blobSignature.length + reserved.length +
timestamp.length + clientNonce.length +
unknown1.length + targetInformation.length +
unknown2.length];
int offset = 0;
System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
offset += blobSignature.length;
System.arraycopy(reserved, 0, blob, offset, reserved.length);
offset += reserved.length;
System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
offset += timestamp.length;
System.arraycopy(clientNonce, 0, blob, offset,
clientNonce.length);
offset += clientNonce.length;
System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
offset += unknown1.length;
System.arraycopy(targetInformation, 0, blob, offset,
targetInformation.length);
offset += targetInformation.length;
System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
return blob;
}
/**
* Calculates the HMAC-MD5 hash of the given data using the specified
* hashing key.
*
* @param data The data for which the hash will be calculated.
* @param key The hashing key.
*
* @return The HMAC-MD5 hash of the given data.
*/
private static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
byte[] ipad = new byte[64];
byte[] opad = new byte[64];
for (int i = 0; i < 64; i++) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
}
for (int i = key.length - 1; i >= 0; i--) {
ipad[i] ^= key[i];
opad[i] ^= key[i];
}
byte[] content = new byte[data.length + 64];
System.arraycopy(ipad, 0, content, 0, 64);
System.arraycopy(data, 0, content, 64, data.length);
MessageDigest md5 = MessageDigest.getInstance("MD5");
data = md5.digest(content);
content = new byte[data.length + 64];
System.arraycopy(opad, 0, content, 0, 64);
System.arraycopy(data, 0, content, 64, data.length);
return md5.digest(content);
}
/**
* Creates a DES encryption key from the given key material.
*
* @param bytes A byte array containing the DES key material.
* @param offset The offset in the given byte array at which
* the 7-byte key material starts.
*
* @return A DES encryption key created from the key material
* starting at the specified offset in the given byte array.
*/
private static Key createDESKey(byte[] bytes, int offset) {
byte[] keyBytes = new byte[7];
System.arraycopy(bytes, offset, keyBytes, 0, 7);
byte[] material = new byte[8];
material[0] = keyBytes[0];
material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
material[7] = (byte) (keyBytes[6] << 1);
oddParity(material);
return new SecretKeySpec(material, "DES");
}
/**
* Applies odd parity to the given byte array.
*
* @param bytes The data whose parity bits are to be adjusted for
* odd parity.
*/
private static void oddParity(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
(b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
(b >>> 1)) & 0x01) == 0;
if (needsParity) {
bytes[i] |= (byte) 0x01;
} else {
bytes[i] &= (byte) 0xfe;
}
}
}
}
| ledyba/Haduki | client/HadukiClient/src/hadukiclient/serv_connection/Responses.java | Java | gpl-3.0 | 14,729 |
/*
* 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.framework.ui.diagram;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.util.ObjectUtils;
import org.esa.snap.util.math.IndexValidator;
import org.esa.snap.util.math.Range;
public class DefaultDiagramGraph extends AbstractDiagramGraph {
private String xName;
private double[] xValues;
private String yName;
private double[] yValues;
private Range xRange;
private Range yRange;
public DefaultDiagramGraph() {
}
public DefaultDiagramGraph(String xName,
double[] xValues,
String yName,
double[] yValues) {
Assert.notNull(yName, "yName");
setXName(xName);
setYName(yName);
setXYValues(xValues, yValues);
}
public String getXName() {
return xName;
}
public void setXName(String xName) {
Assert.notNull(xName, "xName");
if (!ObjectUtils.equalObjects(this.xName, xName)) {
this.xName = xName;
invalidate();
}
}
public String getYName() {
return yName;
}
public void setYName(String yName) {
Assert.notNull(yName, "yName");
if (!ObjectUtils.equalObjects(this.yName, yName)) {
this.yName = yName;
invalidate();
}
}
public double[] getXValues() {
return xValues;
}
public double[] getYValues() {
return yValues;
}
public void setXYValues(double[] xValues, double[] yValues) {
Assert.notNull(xValues, "xValues");
Assert.notNull(yValues, "yValues");
Assert.argument(xValues.length > 1, "xValues.length > 1");
Assert.argument(xValues.length == yValues.length, "xValues.length == yValues.length");
if (!ObjectUtils.equalObjects(this.xValues, xValues) || !ObjectUtils.equalObjects(this.yValues, yValues)) {
this.xValues = xValues;
this.yValues = yValues;
this.xRange = Range.computeRangeDouble(xValues, IndexValidator.TRUE, null, ProgressMonitor.NULL);
this.yRange = Range.computeRangeDouble(yValues, IndexValidator.TRUE, null, ProgressMonitor.NULL);
invalidate();
}
}
public int getNumValues() {
return xValues.length;
}
public double getXValueAt(int index) {
return xValues[index];
}
public double getYValueAt(int index) {
return yValues[index];
}
public double getXMin() {
return xRange.getMin();
}
public double getXMax() {
return xRange.getMax();
}
public double getYMin() {
return yRange.getMin();
}
public double getYMax() {
return yRange.getMax();
}
@Override
public void dispose() {
xValues = null;
yValues = null;
super.dispose();
}
}
| arraydev/snap-desktop | snap-ui/src/main/java/org/esa/snap/framework/ui/diagram/DefaultDiagramGraph.java | Java | gpl-3.0 | 3,648 |
/*
Copyright (C) 2017-2022 Topological Manifold
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 "create_facets.h"
#include "normals.h"
#include "position.h"
#include <src/com/chrono.h>
#include <src/com/error.h>
#include <src/com/log.h>
#include <src/com/print.h>
#include <unordered_map>
namespace ns::mesh
{
namespace
{
template <std::size_t N>
std::unique_ptr<Mesh<N>> create_mesh(
const std::vector<Vector<N, float>>& points,
const std::vector<std::array<int, N>>& facets)
{
if (facets.empty())
{
error("No facets for facet object");
}
std::unordered_map<int, int> vertices;
int idx = 0;
for (const std::array<int, N>& facet : facets)
{
for (int vertex_index : facet)
{
const auto [iter, inserted] = vertices.try_emplace(vertex_index);
if (inserted)
{
iter->second = idx++;
}
}
}
ASSERT(idx == static_cast<int>(vertices.size()));
std::unique_ptr<Mesh<N>> mesh = std::make_unique<Mesh<N>>();
mesh->vertices.resize(vertices.size());
for (const auto& [old_index, new_index] : vertices)
{
mesh->vertices[new_index] = points[old_index];
}
mesh->facets.reserve(facets.size());
for (const std::array<int, N>& facet : facets)
{
typename Mesh<N>::Facet mesh_facet;
mesh_facet.material = -1;
mesh_facet.has_texcoord = false;
mesh_facet.has_normal = false;
for (std::size_t i = 0; i < N; ++i)
{
const auto iter = vertices.find(facet[i]);
ASSERT(iter != vertices.cend());
mesh_facet.vertices[i] = iter->second;
mesh_facet.normals[i] = -1;
mesh_facet.texcoords[i] = -1;
}
mesh->facets.push_back(std::move(mesh_facet));
}
set_center_and_length(mesh.get());
return mesh;
}
}
template <std::size_t N>
std::unique_ptr<Mesh<N>> create_mesh_for_facets(
const std::vector<Vector<N, float>>& points,
const std::vector<std::array<int, N>>& facets,
const bool write_log)
{
std::unique_ptr<Mesh<N>> mesh;
{
const Clock::time_point start_time = Clock::now();
mesh = create_mesh(points, facets);
if (write_log)
{
LOG("Mesh created, " + to_string_fixed(duration_from(start_time), 5) + " s");
}
}
{
const Clock::time_point start_time = Clock::now();
compute_normals(mesh.get());
if (write_log)
{
LOG("Mesh normals computed, " + to_string_fixed(duration_from(start_time), 5) + " s");
}
}
return mesh;
}
#define CREATE_MESH_FOR_FACETS_INSTANTIATION(N) \
template std::unique_ptr<Mesh<(N)>> create_mesh_for_facets( \
const std::vector<Vector<(N), float>>&, const std::vector<std::array<int, (N)>>&, bool);
CREATE_MESH_FOR_FACETS_INSTANTIATION(3)
CREATE_MESH_FOR_FACETS_INSTANTIATION(4)
CREATE_MESH_FOR_FACETS_INSTANTIATION(5)
CREATE_MESH_FOR_FACETS_INSTANTIATION(6)
}
| cppd/math | src/model/mesh_utility/create_facets.cpp | C++ | gpl-3.0 | 4,096 |
package com.prosoft.verilog.ir;
public class VOperUnary extends VOper {
VUnaryKind kind;
public VOperUnary(VUnaryKind kind, VOper child) {
super(child);
this.kind = kind;
}
@Override
public VOperKind getKind() {
return VOperKind.UNARY;
}
@Override
protected VType inferTypeInternal(VEnvironment env) {
env.ensureType(VTypeKind.scalar, getChild(0), false);
switch(kind) {
case MINUS:
case PLUS:
case BNOT:
return getChild(0).getType();
case RED_AND:
case RED_NAND:
case RED_NOR:
case RED_OR:
case RED_XNOR:
case RED_XOR:
case LNOT:
return VTypeVector.singleBit;
default:
throw new RuntimeException(kind.getImage());
}
}
public VUnaryKind getUnaryKind() {
return kind;
}
}
| grwlf/vsim | tr/com/prosoft/verilog/ir/VOperUnary.java | Java | gpl-3.0 | 776 |
/* ************************************************************************ */
/* Georgiev Lab (c) 2015 */
/* ************************************************************************ */
/* Department of Cybernetics */
/* Faculty of Applied Sciences */
/* University of West Bohemia in Pilsen */
/* ************************************************************************ */
/* */
/* This file is part of CeCe. */
/* */
/* CeCe 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. */
/* */
/* CeCe 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 CeCe. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* ************************************************************************ */
#pragma once
/* ************************************************************************ */
// CeCe
#include "cece/core/UniquePtr.hpp"
#include "cece/core/FilePath.hpp"
#include "cece/core/String.hpp"
#include "cece/core/InStream.hpp"
#include "cece/core/OutStream.hpp"
/* ************************************************************************ */
namespace cece { namespace simulator { class Simulation; } }
namespace cece { namespace plugin { class Context; } }
/* ************************************************************************ */
namespace cece {
namespace loader {
/* ************************************************************************ */
/**
* @brief Simulation loader interface.
*/
class Loader
{
// Public Ctors & Dtors
public:
/**
* @brief Destructor.
*/
virtual ~Loader()
{
// Nothing to do
}
// Public Operations
public:
/**
* @brief Create a new simulation from source file.
*
* @param filename Path to source file.
*
* @return Pointer to created simulation.
*/
virtual UniquePtr<simulator::Simulation> fromFile(plugin::Context& context,
const FilePath& filename) const;
/**
* @brief Create a new simulation from source code.
*
* @param source String with source.
* @param filename Path to source file.
*
* @return Pointer to created simulation.
*/
virtual UniquePtr<simulator::Simulation> fromSource(plugin::Context& context,
const String& source, const FilePath& filename = "<source>") const;
/**
* @brief Store simulation into file.
*
* @param simulation Source simulation.
* @param filename Path to source file.
*/
virtual void toFile(const simulator::Simulation& simulation,
const FilePath& filename) const;
/**
* @brief Convert simulation into source code.
*
* @param simulation Source simulation.
*
* @return Source code.
*/
virtual String toSource(const simulator::Simulation& simulation,
const FilePath& filename = "<source>") const;
/**
* @brief Read simulation from input stream.
*
* @param is Source stream.
* @param filename Source file name.
*
* @return Created simulation.
*/
virtual UniquePtr<simulator::Simulation> fromStream(plugin::Context& context,
InStream& is, const FilePath& filename = "<stream>") const = 0;
/**
* @brief Write simulation into output stream.
*
* @param os Output stream.
* @param simulation Source simulation.
*
* @return Source code.
*/
virtual void toStream(OutStream& os, const simulator::Simulation& simulation,
const FilePath& filename = "<stream>") const = 0;
};
/* ************************************************************************ */
}
}
/* ************************************************************************ */
| GustavoPB/CeCe | cece/loader/Loader.hpp | C++ | gpl-3.0 | 4,865 |
DataLife Engine 11.2 = 2afa0f13538ef26952650102e9eb8661
| gohdan/DFC | known_files/hashes/engine/classes/htmlpurifier/standalone/HTMLPurifier/Lexer/PH5P.php | PHP | gpl-3.0 | 56 |
/*****************************************************************
* This file is part of CCAFS Planning and Reporting Platform.
* CCAFS P&R 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.
* CCAFS P&R 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 CCAFS P&R. If not, see <http://www.gnu.org/licenses/>.
* ***************************************************************
*/
package org.cgiar.ccafs.utils.db;
import org.cgiar.ccafs.utils.PropertiesManager;
import org.cgiar.ccafs.utils.db.mysql.MySQLDAOManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.google.inject.ImplementedBy;
/**
* @author Héctor Fabio Tobón R.
* @author Hernán David Carvajal.
*/
@ImplementedBy(MySQLDAOManager.class)
public abstract class DAOManager {
private PropertiesManager properties;
public DAOManager(PropertiesManager properties) {
this.properties = properties;
this.registerDriver();
}
/**
* This method close the conection with the database and frees resources.
*
* @deprecated The new java version (7) implements the interface java.lang.AutoCloseable which can be used
* automatically in the try-catch block.
* @param connection
* @return true if all were ok, and false otherwise.
*/
@SuppressWarnings("unused")
@Deprecated
private boolean closeConnection(Connection connection) {
try {
connection.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* Fix a string that contains simple quotes.
*
* @param string that contains quotes.
* @return a fixed string.
*/
public String correctStringToQuery(String string) {
return null;
}
/**
* This method deletes one or more records from the database.
*
* @param preparedUpdateQuery is the prepared String to be executed.
* @param values are the list of values to be inserted.
* @return the number of records deleted, or -1 if an error occurs.
*/
public int delete(String preparedUpdateQuery, Object[] values) {
return -1;
}
/**
* This method deletes all the records (is_active = 0) that have foreign keys relations to a specific table and column
* name.
* ****** PLEASE USE THIS METHOD CAREFULLY *******
* It uses the following Query in SQL:
* SELECT * FROM information_schema.KEY_COLUMN_USAGE
* WHERE REFERENCED_TABLE_NAME = 'tableName'
* AND REFERENCED_COLUMN_NAME = 'columnValue';
*
* @param tableName - the table name.
* @param columnName - the column name
* @param columnValue - is the value of the record that is going to be deleted.
* @param userID - is the user who is making the change.
* @param justification - is the justification statement
* @return true if the deletion process finished successfully, false otherwise.
*/
public boolean deleteOnCascade(String tableName, String columnName, Object columnValue, int userID,
String justification) {
// This method is defined in MySQLDAOManager.
return true;
}
/**
* Create a connection to the database depending on the credential information added in the properties configuration
* file.
*
* @return A new object connection.
*/
public Connection getConnection() throws SQLException {
return null;
}
/**
* Return a properties object that connects to the properties configuration file.
*
* @return A Properties object.
*/
public final PropertiesManager getProperties() {
return properties;
}
/**
* This method make a change in the database. This query has to start with
* the word UPDATE or INSERT. If you want to make a query, you have to use the
* method named "makeQuery".
*
* @param updateQuery
* - SQL code to make an insert or an update.
* @return The number of affected rows after the query. -1 in case an error ocurrs.
*/
public int makeChange(String updateQuery, Connection connection) {
return -1;
}
/**
* This method executes a query. The query string must start with the word
* "SELECT".
*
* @param query
* - SQL code to take data from the database.
* @return ResulSet object which corresponds to the query result. Or null if
* there was an error.
*/
public ResultSet makeQuery(String query, Connection connection) {
return null;
}
/**
* open the connection to the database
*
* @param user
* @param password
* @return A Connection object type
*/
protected Connection openConnection(String user, String password, String ip, String port, String databaseName)
throws SQLException {
return null;
}
/**
* Initialize database driver
*
* @return false if the driver was not found or any other problem occurs.
*/
protected boolean registerDriver() {
return false;
}
/**
* This method saves or updates any record into the database.
*
* @param preparedUpdateQuery is the prepared String to be executed.
* @param values are the list of values to be inserted.
* @return The last inserted id if there was a new record, 0 if the record was updated or -1 if any error happened.
*/
public int saveData(String preparedUpdateQuery, Object[] values) {
return -1;
}
}
| CCAFS/ccafs-ap | utils/src/main/java/org/cgiar/ccafs/utils/db/DAOManager.java | Java | gpl-3.0 | 5,758 |
Simpla CMS 2.3.8 = 57b16f03be6df9584fa91557d51214ef
| gohdan/DFC | known_files/hashes/simpla/PostAdmin.php | PHP | gpl-3.0 | 52 |
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Pixie.Markup;
using Pixie.Options;
namespace UnitTests
{
/// <summary>
/// Defines command-line options for the unit test runner.
/// </summary>
public static class Options
{
/// <summary>
/// The 'help' option, which prints usage information.
/// </summary>
public static readonly FlagOption Help =
FlagOption.CreateFlagOption(
new OptionForm[]
{
OptionForm.Short("h"),
OptionForm.Long("help")
})
.WithDescription(
"Print a description of the options understood by the unit test runner.");
/// <summary>
/// The 'input' pseudo-option, which specifies the assembly to optimize.
/// </summary>
public static readonly SequenceOption<string> Input =
SequenceOption.CreateStringOption(OptionForm.Long("input"))
.WithDescription("A path to the assembly to optimize.")
.WithParameters(new SymbolicOptionParameter("path", true));
private static string DefaultCscPath =
Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe");
/// <summary>
/// The 'csc-path' option, which specifies the path to the C# compiler.
/// </summary>
public static readonly ValueOption<string> CscPath =
ValueOption.CreateStringOption(
OptionForm.Long("csc-path"),
DefaultCscPath)
.WithDescription(
Quotation.QuoteEvenInBold(
"The path to the C# compiler. This is ",
DefaultCscPath,
" by default."))
.WithParameter(new SymbolicOptionParameter("path"));
private static string DefaultClangPath = "clang";
/// <summary>
/// The 'clang-path' option, which specifies the path to Clang.
/// </summary>
public static readonly ValueOption<string> ClangPath =
ValueOption.CreateStringOption(
OptionForm.Long("clang-path"),
DefaultClangPath)
.WithDescription(
Quotation.QuoteEvenInBold(
"The path to Clang. This is ",
DefaultClangPath,
" by default."))
.WithParameter(new SymbolicOptionParameter("path"));
/// <summary>
/// A list of all named options understood by ilopt.
/// </summary>
public static readonly IReadOnlyList<Option> All =
new Option[]
{
Help,
CscPath,
ClangPath
};
}
}
| jonathanvdc/Flame | src/UnitTests/Options.cs | C# | gpl-3.0 | 2,849 |
<?php
namespace D\library\patterns\entity\SQL\builder;
use D\library\patterns\entity\SQL\operators\DML\components\Field;
use D\library\patterns\entity\SQL\operators\DML\components\Join;
use D\library\patterns\entity\SQL\operators\DML\components\Limit;
use D\library\patterns\entity\SQL\operators\DML\components\OrderBy;
use D\library\patterns\entity\SQL\operators\DML\components\Table;
use D\library\patterns\entity\exceptions\dataExceptions\NotFoundDataException;
use D\library\patterns\entity\exceptions\semanticExceptions\InvalidArgumentException;
use D\library\patterns\structure\conversion\Interpreter;
use D\library\patterns\structure\singleton\Singleton;
use D\library\patterns\structure\singleton\TSingleton;
use D\library\patterns\entity\SQL\operators\DML as DML;
/**
* Класс представляет фабрику объектной SQL инструкции Select.
* @author Artur Sh. Mamedbekov
*/
class Select implements Singleton, Interpreter{
use TSingleton;
/**
* @var \D\library\patterns\entity\SQL\operators\DML\Select Объектная SQL инструкция Select.
*/
protected $select;
/**
* @var \D\library\patterns\entity\SQL\builder\Where|null Фабрика Where, являющаяся частью запроса, или null - если запрос не имеет условия.
*/
protected $where;
/**
* Метод определяет поля запроса.
* @param string[]|null $fields [optional] Массив имен полей запроса. Если передан ассоциативный массив, то ключи определяют целевые таблицы полей. Если параметр не передан, выбираются все поля.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function fields(array $fields = null){
if(empty($this->select)){
$this->select = new DML\Select;
}
if(is_null($fields)){
$this->select->addAllField();
}
else{
foreach($fields as $table => $field){
$field = new Field($field);
if(is_string($table)){
$field->setTable(new Table($table));
}
$this->select->addField($field);
}
}
return $this;
}
/**
* Метод определяет целевые таблицы запроса.
* @param string[] $tables Список имен целевых таблиц запроса.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function tables(array $tables){
if(empty($this->select)){
$this->select = new DML\Select;
}
foreach($tables as $table){
$this->select->addTable(new Table($table));
}
return $this;
}
/**
* Метод добавляет объединение типа INNER.
* @param string $table Объединяемая таблица.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|mixed[] $rightOperand Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Добавляет информацию о целевой таблице поля, если в строке присутствует точка.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function innerJoin($table, $leftOperand, $operator, $rightOperand){
InvalidArgumentException::verify($table, 's', [1]);
$this->select->addJoin(new Join(Join::INNER, new Table($table), Where::createCondition($leftOperand, $operator, $rightOperand)));
return $this;
}
/**
* Метод добавляет объединение типа CROSS.
* @param string $table Объединяемая таблица.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|mixed[] $rightOperand Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Добавляет информацию о целевой таблице поля, если в строке присутствует точка.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function crossJoin($table, $leftOperand, $operator, $rightOperand){
InvalidArgumentException::verify($table, 's', [1]);
$this->select->addJoin(new Join(Join::CROSS, new Table($table), Where::createCondition($leftOperand, $operator, $rightOperand)));
return $this;
}
/**
* Метод добавляет объединение типа LEFT.
* @param string $table Объединяемая таблица.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|mixed[] $rightOperand Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Добавляет информацию о целевой таблице поля, если в строке присутствует точка.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function leftJoin($table, $leftOperand, $operator, $rightOperand){
InvalidArgumentException::verify($table, 's', [1]);
$this->select->addJoin(new Join(Join::LEFT, new Table($table), Where::createCondition($leftOperand, $operator, $rightOperand)));
return $this;
}
/**
* Метод добавляет объединение типа RIGHT.
* @param string $table Объединяемая таблица.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|mixed[] $rightOperand Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Добавляет информацию о целевой таблице поля, если в строке присутствует точка.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function rightJoin($table, $leftOperand, $operator, $rightOperand){
InvalidArgumentException::verify($table, 's', [1]);
$this->select->addJoin(new Join(Join::RIGHT, new Table($table), Where::createCondition($leftOperand, $operator, $rightOperand)));
return $this;
}
/**
* Метод добавляет объединение типа FULL.
* @param string $table Объединяемая таблица.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|mixed[] $rightOperand Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Добавляет информацию о целевой таблице поля, если в строке присутствует точка.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function fullJoin($table, $leftOperand, $operator, $rightOperand){
InvalidArgumentException::verify($table, 's', [1]);
$this->select->addJoin(new Join(Join::FULL, new Table($table), Where::createCondition($leftOperand, $operator, $rightOperand)));
return $this;
}
/**
* Метод добавляет компонент Limit.
* @param integer $limit Объем выборки.
* @throws \D\library\patterns\entity\exceptions\semanticExceptions\InvalidArgumentException Выбрасывается при передаче параметра неверного типа.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function limit($limit){
InvalidArgumentException::verify($limit, 'i');
$this->select->insertLimit(new Limit($limit));
return $this;
}
/**
* Метод добавляет компонент OrderBy.
* @param string[] $fields Имена полей сортировки.
* @param string $type [optional] Тип сортировки.
* @return \D\library\patterns\entity\SQL\builder\Select Вызываемый объект.
*/
public function orderBy(array $fields, $type = OrderBy::ASC){
$ob = new OrderBy($type);
foreach($fields as $field){
$ob->addField(new Field($field));
}
$this->select->insertOrderBy($ob);
return $this;
}
/**
* Метод создает объектный SQL компонент Where для данного условия.
* Метод должен быть вызван только после вызова метода table или fields, формирующего инструкцию.
* @param string $leftOperand Левый операнд.
* @param string $operator Оператор. Допустимо одно из следующих значений: >, <, >=, <=, =, !=, in.
* @param string|array $rightOperand [optional] Правый операнд. Может быть массивом, если в качестве оператора передан in. Может быть объектным SQL компонентом Field, если значение обрамлено в косые кавычки (`). Если параметр не задан, значит значение параметризовано.
* @throws \D\library\patterns\entity\exceptions\semanticExceptions\InvalidArgumentException Выбрасывается при передаче параметра неверного типа.
* @throws \D\library\patterns\entity\exceptions\dataExceptions\NotFoundDataException Выбрасывается если метод вызывается до вызова метода table или fields.
* @return \D\library\patterns\entity\SQL\builder\Where Фабрика объектного SQL компонента Where для данной инструкции.
*/
public function where($leftOperand, $operator, $rightOperand = null){
if(empty($this->select)){
throw new NotFoundDataException('Невозможно добавить условие отбора без указания целевой таблицы [D\library\patterns\entity\SQL\builder\Select].');
}
/**
* @var Where $whereBuilder
*/
$whereBuilder = Where::getInstance();
$this->where = $whereBuilder->create($leftOperand, $operator, $rightOperand);
$this->where->select = $this;
return $this->where;
}
/**
* Метод возвращает полученную объектную SQL инструкцию Select.
* @return \D\library\patterns\entity\SQL\operators\DML\Select Результат работы фабрики.
*/
public function get($driver = null){
$select = $this->select;
if(isset($this->where)){
$this->select->insertWhere($this->where->last());
}
$this->clear();
return $select;
}
/**
* @prototype D\library\patterns\structure\conversion\Interpreter
*/
public function interpretation($driver = null){
return $this->get()->interpretation($driver);
}
/**
* Метод удаляет текущую конструкцию.
*/
public function clear(){
unset($this->select);
unset($this->where);
}
} | Bashka/D | library/patterns/entity/SQL/builder/Select.php | PHP | gpl-3.0 | 12,838 |
<?php /* Smarty version Smarty-3.1.19, created on 2016-02-23 18:20:18
compiled from "/var/www/html/prestashop/themes/default-bootstrap/header.tpl" */ ?>
<?php /*%%SmartyHeaderCode:5262045056cca2e2800531-79746740%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'2cc462e8c4778cfa9950b74c613bc44cb6d56020' =>
array (
0 => '/var/www/html/prestashop/themes/default-bootstrap/header.tpl',
1 => 1452095428,
2 => 'file',
),
),
'nocache_hash' => '5262045056cca2e2800531-79746740',
'function' =>
array (
),
'variables' =>
array (
'language_code' => 0,
'meta_title' => 0,
'meta_description' => 0,
'meta_keywords' => 0,
'nobots' => 0,
'nofollow' => 0,
'favicon_url' => 0,
'img_update_time' => 0,
'css_files' => 0,
'css_uri' => 0,
'media' => 0,
'js_defer' => 0,
'js_files' => 0,
'js_def' => 0,
'js_uri' => 0,
'HOOK_HEADER' => 0,
'page_name' => 0,
'body_classes' => 0,
'hide_left_column' => 0,
'hide_right_column' => 0,
'content_only' => 0,
'lang_iso' => 0,
'restricted_country_mode' => 0,
'geolocation_country' => 0,
'force_ssl' => 0,
'base_dir_ssl' => 0,
'base_dir' => 0,
'shop_name' => 0,
'logo_url' => 0,
'logo_image_width' => 0,
'logo_image_height' => 0,
'HOOK_TOP' => 0,
'left_column_size' => 0,
'HOOK_LEFT_COLUMN' => 0,
'right_column_size' => 0,
'cols' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56cca2e4a0ede4_73703507',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56cca2e4a0ede4_73703507')) {function content_56cca2e4a0ede4_73703507($_smarty_tpl) {?><?php if (!is_callable('smarty_function_implode')) include '/var/www/html/prestashop/tools/smarty/plugins/function.implode.php';
?>
<!DOCTYPE HTML>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"<?php if (isset($_smarty_tpl->tpl_vars['language_code']->value)&&$_smarty_tpl->tpl_vars['language_code']->value) {?> lang="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['language_code']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?>><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8 ie7"<?php if (isset($_smarty_tpl->tpl_vars['language_code']->value)&&$_smarty_tpl->tpl_vars['language_code']->value) {?> lang="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['language_code']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?>><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9 ie8"<?php if (isset($_smarty_tpl->tpl_vars['language_code']->value)&&$_smarty_tpl->tpl_vars['language_code']->value) {?> lang="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['language_code']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?>><![endif]-->
<!--[if gt IE 8]> <html class="no-js ie9"<?php if (isset($_smarty_tpl->tpl_vars['language_code']->value)&&$_smarty_tpl->tpl_vars['language_code']->value) {?> lang="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['language_code']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?>><![endif]-->
<html<?php if (isset($_smarty_tpl->tpl_vars['language_code']->value)&&$_smarty_tpl->tpl_vars['language_code']->value) {?> lang="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['language_code']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?>>
<head>
<meta charset="utf-8" />
<title><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['meta_title']->value, ENT_QUOTES, 'UTF-8', true);?>
</title>
<?php if (isset($_smarty_tpl->tpl_vars['meta_description']->value)&&$_smarty_tpl->tpl_vars['meta_description']->value) {?>
<meta name="description" content="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['meta_description']->value, ENT_QUOTES, 'UTF-8', true);?>
" />
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['meta_keywords']->value)&&$_smarty_tpl->tpl_vars['meta_keywords']->value) {?>
<meta name="keywords" content="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['meta_keywords']->value, ENT_QUOTES, 'UTF-8', true);?>
" />
<?php }?>
<meta name="generator" content="PrestaShop" />
<meta name="robots" content="<?php if (isset($_smarty_tpl->tpl_vars['nobots']->value)) {?>no<?php }?>index,<?php if (isset($_smarty_tpl->tpl_vars['nofollow']->value)&&$_smarty_tpl->tpl_vars['nofollow']->value) {?>no<?php }?>follow" />
<meta name="viewport" content="width=device-width, minimum-scale=0.25, maximum-scale=1.6, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="icon" type="image/vnd.microsoft.icon" href="<?php echo $_smarty_tpl->tpl_vars['favicon_url']->value;?>
?<?php echo $_smarty_tpl->tpl_vars['img_update_time']->value;?>
" />
<link rel="shortcut icon" type="image/x-icon" href="<?php echo $_smarty_tpl->tpl_vars['favicon_url']->value;?>
?<?php echo $_smarty_tpl->tpl_vars['img_update_time']->value;?>
" />
<?php if (isset($_smarty_tpl->tpl_vars['css_files']->value)) {?>
<?php $_smarty_tpl->tpl_vars['media'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['media']->_loop = false;
$_smarty_tpl->tpl_vars['css_uri'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['css_files']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['media']->key => $_smarty_tpl->tpl_vars['media']->value) {
$_smarty_tpl->tpl_vars['media']->_loop = true;
$_smarty_tpl->tpl_vars['css_uri']->value = $_smarty_tpl->tpl_vars['media']->key;
?>
<link rel="stylesheet" href="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['css_uri']->value, ENT_QUOTES, 'UTF-8', true);?>
" type="text/css" media="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['media']->value, ENT_QUOTES, 'UTF-8', true);?>
" />
<?php } ?>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['js_defer']->value)&&!$_smarty_tpl->tpl_vars['js_defer']->value&&isset($_smarty_tpl->tpl_vars['js_files']->value)&&isset($_smarty_tpl->tpl_vars['js_def']->value)) {?>
<?php echo $_smarty_tpl->tpl_vars['js_def']->value;?>
<?php $_smarty_tpl->tpl_vars['js_uri'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['js_uri']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['js_files']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['js_uri']->key => $_smarty_tpl->tpl_vars['js_uri']->value) {
$_smarty_tpl->tpl_vars['js_uri']->_loop = true;
?>
<script type="text/javascript" src="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['js_uri']->value, ENT_QUOTES, 'UTF-8', true);?>
"></script>
<?php } ?>
<?php }?>
<?php echo $_smarty_tpl->tpl_vars['HOOK_HEADER']->value;?>
<link rel="stylesheet" href="http<?php if (Tools::usingSecureMode()) {?>s<?php }?>://fonts.googleapis.com/css?family=Open+Sans:300,600&subset=latin,latin-ext" type="text/css" media="all" />
<!--[if IE 8]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body<?php if (isset($_smarty_tpl->tpl_vars['page_name']->value)) {?> id="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['page_name']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php }?> class="<?php if (isset($_smarty_tpl->tpl_vars['page_name']->value)) {?><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['page_name']->value, ENT_QUOTES, 'UTF-8', true);?>
<?php }?><?php if (isset($_smarty_tpl->tpl_vars['body_classes']->value)&&count($_smarty_tpl->tpl_vars['body_classes']->value)) {?> <?php echo smarty_function_implode(array('value'=>$_smarty_tpl->tpl_vars['body_classes']->value,'separator'=>' '),$_smarty_tpl);?>
<?php }?><?php if ($_smarty_tpl->tpl_vars['hide_left_column']->value) {?> hide-left-column<?php } else { ?> show-left-column<?php }?><?php if ($_smarty_tpl->tpl_vars['hide_right_column']->value) {?> hide-right-column<?php } else { ?> show-right-column<?php }?><?php if (isset($_smarty_tpl->tpl_vars['content_only']->value)&&$_smarty_tpl->tpl_vars['content_only']->value) {?> content_only<?php }?> lang_<?php echo $_smarty_tpl->tpl_vars['lang_iso']->value;?>
">
<?php if (!isset($_smarty_tpl->tpl_vars['content_only']->value)||!$_smarty_tpl->tpl_vars['content_only']->value) {?>
<?php if (isset($_smarty_tpl->tpl_vars['restricted_country_mode']->value)&&$_smarty_tpl->tpl_vars['restricted_country_mode']->value) {?>
<div id="restricted-country">
<p><?php echo smartyTranslate(array('s'=>'You cannot place a new order from your country.'),$_smarty_tpl);?>
<?php if (isset($_smarty_tpl->tpl_vars['geolocation_country']->value)&&$_smarty_tpl->tpl_vars['geolocation_country']->value) {?> <span class="bold"><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['geolocation_country']->value, ENT_QUOTES, 'UTF-8', true);?>
</span><?php }?></p>
</div>
<?php }?>
<div id="page">
<div class="header-container">
<header id="header">
<?php $_smarty_tpl->_capture_stack[0][] = array('displayBanner', null, null); ob_start(); ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayBanner'),$_smarty_tpl);?>
<?php list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
if (!empty($_capture_buffer)) {
if (isset($_capture_assign)) $_smarty_tpl->assign($_capture_assign, ob_get_contents());
if (isset( $_capture_append)) $_smarty_tpl->append( $_capture_append, ob_get_contents());
Smarty::$_smarty_vars['capture'][$_capture_buffer]=ob_get_clean();
} else $_smarty_tpl->capture_error();?>
<?php if (Smarty::$_smarty_vars['capture']['displayBanner']) {?>
<div class="banner">
<div class="container">
<div class="row">
<?php echo Smarty::$_smarty_vars['capture']['displayBanner'];?>
</div>
</div>
</div>
<?php }?>
<?php $_smarty_tpl->_capture_stack[0][] = array('displayNav', null, null); ob_start(); ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayNav'),$_smarty_tpl);?>
<?php list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
if (!empty($_capture_buffer)) {
if (isset($_capture_assign)) $_smarty_tpl->assign($_capture_assign, ob_get_contents());
if (isset( $_capture_append)) $_smarty_tpl->append( $_capture_append, ob_get_contents());
Smarty::$_smarty_vars['capture'][$_capture_buffer]=ob_get_clean();
} else $_smarty_tpl->capture_error();?>
<?php if (Smarty::$_smarty_vars['capture']['displayNav']) {?>
<div class="nav">
<div class="container">
<div class="row">
<nav><?php echo Smarty::$_smarty_vars['capture']['displayNav'];?>
</nav>
</div>
</div>
</div>
<?php }?>
<div>
<div class="container">
<div class="row">
<div id="header_logo">
<a href="<?php if (isset($_smarty_tpl->tpl_vars['force_ssl']->value)&&$_smarty_tpl->tpl_vars['force_ssl']->value) {?><?php echo $_smarty_tpl->tpl_vars['base_dir_ssl']->value;?>
<?php } else { ?><?php echo $_smarty_tpl->tpl_vars['base_dir']->value;?>
<?php }?>" title="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['shop_name']->value, ENT_QUOTES, 'UTF-8', true);?>
">
<img class="logo img-responsive" src="<?php echo $_smarty_tpl->tpl_vars['logo_url']->value;?>
" alt="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['shop_name']->value, ENT_QUOTES, 'UTF-8', true);?>
"<?php if (isset($_smarty_tpl->tpl_vars['logo_image_width']->value)&&$_smarty_tpl->tpl_vars['logo_image_width']->value) {?> width="<?php echo $_smarty_tpl->tpl_vars['logo_image_width']->value;?>
"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['logo_image_height']->value)&&$_smarty_tpl->tpl_vars['logo_image_height']->value) {?> height="<?php echo $_smarty_tpl->tpl_vars['logo_image_height']->value;?>
"<?php }?>/>
</a>
</div>
<?php if (isset($_smarty_tpl->tpl_vars['HOOK_TOP']->value)) {?><?php echo $_smarty_tpl->tpl_vars['HOOK_TOP']->value;?>
<?php }?>
</div>
</div>
</div>
</header>
</div>
<div class="columns-container">
<div id="columns" class="container">
<?php if ($_smarty_tpl->tpl_vars['page_name']->value!='index'&&$_smarty_tpl->tpl_vars['page_name']->value!='pagenotfound') {?>
<?php echo $_smarty_tpl->getSubTemplate (((string)$_smarty_tpl->tpl_vars['tpl_dir']->value)."./breadcrumb.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<?php }?>
<div id="slider_row" class="row">
<?php $_smarty_tpl->_capture_stack[0][] = array('displayTopColumn', null, null); ob_start(); ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayTopColumn'),$_smarty_tpl);?>
<?php list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
if (!empty($_capture_buffer)) {
if (isset($_capture_assign)) $_smarty_tpl->assign($_capture_assign, ob_get_contents());
if (isset( $_capture_append)) $_smarty_tpl->append( $_capture_append, ob_get_contents());
Smarty::$_smarty_vars['capture'][$_capture_buffer]=ob_get_clean();
} else $_smarty_tpl->capture_error();?>
<?php if (Smarty::$_smarty_vars['capture']['displayTopColumn']) {?>
<div id="top_column" class="center_column col-xs-12 col-sm-12"><?php echo Smarty::$_smarty_vars['capture']['displayTopColumn'];?>
</div>
<?php }?>
</div>
<div class="row">
<?php if (isset($_smarty_tpl->tpl_vars['left_column_size']->value)&&!empty($_smarty_tpl->tpl_vars['left_column_size']->value)) {?>
<div id="left_column" class="column col-xs-12 col-sm-<?php echo intval($_smarty_tpl->tpl_vars['left_column_size']->value);?>
"><?php echo $_smarty_tpl->tpl_vars['HOOK_LEFT_COLUMN']->value;?>
</div>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['left_column_size']->value)&&isset($_smarty_tpl->tpl_vars['right_column_size']->value)) {?><?php $_smarty_tpl->tpl_vars['cols'] = new Smarty_variable((12-$_smarty_tpl->tpl_vars['left_column_size']->value-$_smarty_tpl->tpl_vars['right_column_size']->value), null, 0);?><?php } else { ?><?php $_smarty_tpl->tpl_vars['cols'] = new Smarty_variable(12, null, 0);?><?php }?>
<div id="center_column" class="center_column col-xs-12 col-sm-<?php echo intval($_smarty_tpl->tpl_vars['cols']->value);?>
">
<?php }?>
<?php }} ?>
| jesusgm/prestashop | cache/smarty/compile/2c/c4/62/2cc462e8c4778cfa9950b74c613bc44cb6d56020.file.header.tpl.php | PHP | gpl-3.0 | 14,630 |
/*
*
*/
package com.jf.carrot.model;
/**
* 性别.
*/
public enum Sex {
/** 男性. */
Male,
/** 女性. */
Female
}
| JohnnyFee/carrot | src/Carrot/src/main/java/com/jf/carrot/model/Sex.java | Java | gpl-3.0 | 143 |
#include "CBox.h"
#include "C3DScene.h"
//-------------------------------------------------------------------------------------------------
using namespace Math;
//-------------------------------------------------------------------------------------------------
// Constantes
#define BOX_SIZE 0.5
//-------------------------------------------------------------------------------------------------
CBox::CBox(C3DScene* pScene, double dMaxDistance)
: CMesh(pScene, dMaxDistance)
, m_vMinimum(-BOX_SIZE, -BOX_SIZE, -BOX_SIZE)
, m_vMaximum( BOX_SIZE, BOX_SIZE, BOX_SIZE)
{
setName("Box");
m_pGeometry->setMaterial(m_pScene->ressourcesManager()->getDefaultMaterial());
m_pGeometry->materials()[0]->setIRFactor(0.4);
fillVertices();
}
//-------------------------------------------------------------------------------------------------
CBox::~CBox()
{
}
//-------------------------------------------------------------------------------------------------
void CBox::setMinimum(const CVector3& vMinimum)
{
m_vMinimum = vMinimum;
fillVertices();
}
//-------------------------------------------------------------------------------------------------
void CBox::setMaximum(const CVector3& vMaximum)
{
m_vMaximum = vMaximum;
fillVertices();
}
//-------------------------------------------------------------------------------------------------
void CBox::setBounds(const CVector3& vMinimum, const CVector3& vMaximum)
{
m_vMinimum = vMinimum;
m_vMaximum = vMaximum;
fillVertices();
}
//-------------------------------------------------------------------------------------------------
void CBox::fillVertices()
{
m_pGeometry->createBox(m_vMinimum, m_vMaximum);
}
| Jango73/Quick3D | Quick3D/Source/Mesh/CBox.cpp | C++ | gpl-3.0 | 1,730 |
#!/usr/bin/env python
#
# test_copy_residue.py
#
# unit tests for residue duplication functionality
#
__author__ = "Magdalena Musielak, Tomasz Puton, Kristian Rother"
__copyright__ = "Copyright 2008, The Moderna Project"
__credits__ = ["Janusz Bujnicki"]
__license__ = "GPL"
__maintainer__ = "Magdalena Musielak"
__email__ = "mmusiel@genesilico.pl"
__status__ = "Prototype"
from unittest import main, TestCase
from moderna.RNAResidue import RNAResidue
from moderna.analyze.BaseRecognizer import BaseRecognizer, BaseRecognitionError
from Bio.PDB import PDBParser
from moderna.util.Errors import RNAResidueError
from moderna.sequence.ModernaAlphabet import Alphabet
from test_data import *
class RNAResidueTests(TestCase):
def setUp(self):
"""Loads the A residue to start with."""
self.a=PDBParser().get_structure('test_struc',A_RESIDUE)[0].child_list[0].child_list[0]
self.chain=PDBParser().get_structure('test_struc',MINI_TEMPLATE)[0].child_list[0]
self.chain2=PDBParser().get_structure('test_struc',MINI_TEMPLATE)[0].child_list[0]
def tearDown(self):
self.a = None
self.chain = None
self.chain2 = None
def test_residue_identity(self):
"""Moderna residues need to be discinct by __eq__ unless they are the same object."""
r1 = RNAResidue(self.chain.child_list[2])
r2 = RNAResidue(self.chain2.child_list[2])
r3 = RNAResidue(self.chain.child_list[3])
r4 = RNAResidue(self.chain.child_list[2])
self.assertEqual(r1, r1)
self.assertNotEqual(r1, r2)
self.assertNotEqual(r1, r3)
self.assertNotEqual(r1, r4)
def test_atom_parent(self):
"""Atoms should link back to their parent."""
resi = RNAResidue(self.a)
for atom in resi:
self.assertEqual(atom.get_parent(),resi)
def test_atom_name(self):
"""Atoms should have the right names."""
resi = RNAResidue(self.a)
self.assertEqual(resi["C4'"].name,"C4'")
self.assertEqual(resi["C4'"].fullname," C4'")
self.assertEqual(resi["C4'"].element,'C')
def test_init(self):
"""Residues should be initializable."""
a = RNAResidue(self.a)
self.assertEqual(a.identifier,'1')
a = RNAResidue(self.chain.child_list[0])
self.assertEqual(a.identifier,'1')
a = RNAResidue(self.chain.child_list[-1])
self.assertEqual(a.identifier,'15')
def test_init_recog_base(self):
"""Base recognition should succeed regardless of parameter"""
alphabet = Alphabet()
# recognition with base recognizer
a = RNAResidue(self.chain.child_list[9])
self.assertEqual(a.long_abbrev,'m2G')
# assignment by alphabet entry
# IMPORTANT FOR BASE RECOGNIZER BYPASS
a = RNAResidue(self.chain.child_list[9], alphabet['m2G'])
self.assertEqual(a.long_abbrev,'m2G')
# assignment by wrong alphabet entry should succeed!
a = RNAResidue(self.chain.child_list[9], alphabet['m7G'])
self.assertEqual(a.long_abbrev,'m7G')
def test_renumber(self):
res = RNAResidue(self.chain.child_list[2])
res.change_number('64')
self.assertEqual(res.identifier, '64')
self.assertEqual(res.id, (' ',64, ' '))
res.change_number('133E')
self.assertEqual(res.identifier, '133E')
self.assertEqual(res.id, (' ',133, 'E'))
res.change_number('2')
self.assertEqual(res.identifier, '2')
self.assertEqual(res.id, (' ',2, ' '))
def test_glycosidic_n(self):
"""Finds N* in tough cases."""
chain = PDBParser().get_structure('test_struc', 'test_data/gaps/1h3e_B.pdb')[0].child_list[0]
resi1 = RNAResidue(chain[(' ', 15, ' ')])
self.assertTrue(resi1['N*'])
resi2 = RNAResidue(chain[(' ', 16, ' ')])
self.assertRaises(RNAResidueError, resi2.__getitem__, 'N*')
def test_purine(self):
"""RNAResidue recognizes purines."""
res = RNAResidue(self.chain.child_list[0])
self.assertTrue(res.purine)
res =RNAResidue(self.chain.child_list[9])
self.assertTrue(res.purine)
res =RNAResidue(self.chain.child_list[1])
self.assertFalse(res.purine)
res = RNAResidue(self.chain.child_list[11])
self.assertFalse(res.purine)
def test_pyrimidine(self):
"""ModernaResidue recognizes pyrimidines."""
res = RNAResidue(self.chain.child_list[1])
self.assertTrue(res.pyrimidine)
res = RNAResidue(self.chain.child_list[11])
self.assertTrue(res.pyrimidine)
res = RNAResidue(self.chain.child_list[0])
self.assertFalse(res.pyrimidine)
res = RNAResidue(self.chain.child_list[9])
self.assertFalse(res.pyrimidine)
if __name__ == '__main__':
main()
| lenarother/moderna | tests/test_rna_residue.py | Python | gpl-3.0 | 4,920 |
#ifdef WIN32
#include<windows.h>
#endif
#ifdef WIN32
#include<windows.h>
#endif
#include<GL/gl.h>
#include<GL/glut.h>
#include<fstream>
#ifndef WIN32
#include <iostream>
#endif
#include <math.h>
#include <stdlib.h>
#include "camara.h"
#define An 640
#define Al 480
#define GL_PI 3.14159265f
#define U_MIN -GL_PI
#define U_MAX GL_PI
#define V_MIN -GL_PI/2
#define V_MAX GL_PI/2
using namespace std;
Point3 eye, look;
Vector3 up;
Camera cam;
void myKeyboard(unsigned char key, int x, int y)
{
switch(key)
{
// controles para camera
case 'l': cam.slide(0,0, 0.2f); break; // slide camera adelante
case 'c': cam.slide(0,0,-0.2f); break; //slide camera atrás
// controles arriba/abajo and izquierde/derecha
case 'b': cam.pitch(-1.0); break;
case 's': cam.pitch( 1.0); break;
// controles de roll
case 'r': cam.roll(-1.0); break;
case 'R': cam.roll( 1.0); break;
// añadir los controles de yaw
case 'y': cam.yaw(-1.0); break;
case 'Y': cam.yaw( 1.0); break;
}
glutPostRedisplay(); // dibuha de nuevo
}
void dibujo(void){
int i,j;
double u,v;
double x,y,z;
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBegin(GLU_LINE);
for(i=U_MIN;i<U_MAX;i+=0.5){
for(j=V_MIN;j<V_MAX;j+=0.5){
glVertex3f(cos(v)*cos(u),cos(v)*sin(u),sin(v)*sin(u));
glEnd();
}
}
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // doble buffers
glutInitWindowSize(640,480);
glutInitWindowPosition(50, 50);
glutCreateWindow("cerca'c' lejos'l' sube's' baja'b' inclinar 'r' y 'R'cabezada 'y' 'Y'");
glutKeyboardFunc(myKeyboard);
glutDisplayFunc(dibujo);
glClearColor(1.0f,1.0f,1.0f,1.0f); // fondeo blanco
glColor3f(0.0f,0.0f,0.0f); // asigna el color
glViewport(0, 0, 640, 480);
eye.x=4; eye.y=4;eye.z=4;
look.x=0;look.y=0;look.z=0;
up.x=0;up.y=1;up.z=0;
//cam.set(4,4,4,0,0,0,0,1,0); // crea la camera inicial
cam.set(eye,look,up);
cam.setShape(30.0f, 64.0f/48.0f, 0.5f, 50.0f);
cam.slide(0,0, 0.0f);
glutMainLoop();
}
| raulperula/uco_student | computer_graphics/practices/src/trabajo5.cpp | C++ | gpl-3.0 | 2,235 |
import { TestBed, async } from '@angular/core/testing';
import { APP_BASE_HREF } from '@angular/common';
import { RouterModule } from '@angular/router';
import { appRoutes } from './app.routes';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './pagenotfound/pagenotfound.component';
describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
PageNotFoundComponent
],
imports: [
RouterModule.forRoot(appRoutes)
],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' }
]
});
TestBed.compileComponents();
});
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
| maservant/raqia | src/app/app.component.spec.ts | TypeScript | gpl-3.0 | 990 |
#region License
/*
Copyright 2014 - 2015 Nikita Bernthaler
Utils.cs is part of SFXDestination.
SFXDestination 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.
SFXDestination 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 SFXDestination. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion License
#region
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using LeagueSharp;
#endregion
namespace SFXDestination.Library
{
public class Utils
{
public static SpellSlot GetSpellSlotByChar(string c)
{
switch (c.ToUpper())
{
case "Q":
return SpellSlot.Q;
case "W":
return SpellSlot.W;
case "E":
return SpellSlot.E;
case "R":
return SpellSlot.R;
default:
return SpellSlot.Unknown;
}
}
public static string GetEnumName(SpellSlot slot)
{
return Enum.GetName(typeof(SpellSlot), slot);
}
public static bool IsXmlValid(string schemaFile, string xmlFile)
{
try
{
var valid = true;
var sc = new XmlSchemaSet();
sc.Add(string.Empty, schemaFile);
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = sc };
settings.ValidationEventHandler += delegate { valid = false; };
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.IgnoreWhitespace = true;
var reader = XmlReader.Create(xmlFile, settings);
try
{
while (reader.Read()) {}
}
catch (XmlException xmlException)
{
Console.WriteLine(xmlException);
}
return valid;
}
catch
{
return false;
}
}
public static string ReadResourceString(string resource, Assembly asm)
{
try
{
using (var stream = asm.GetManifestResourceStream(resource))
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
catch
{
//ignored
}
return string.Empty;
}
}
} | Lizzaran/LeagueSharp-Standalones | SFXUtility/SFXDestination/Library/Utils.cs | C# | gpl-3.0 | 3,215 |
from lettuce import step, world
from nose.tools import assert_equals, assert_true, assert_false
import utils
import os
import bunch.special
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
utils.init(dir_path)
config_file = os.path.join(dir_path, "config.yaml")
config = utils.load_yaml_config(config_file)
bunch_working_dir = dir_path
def dump(obj):
for attr in dir(obj):
print "obj.%s = %s" % (attr, getattr(obj, attr))
mysql_admin = config['db']['admin']
mysql_admin_pwd = config['db']['admin_pwd']
class step_assert(object):
def __init__(self, step):
self.step = step
def assert_true(self, expr):
msg = 'Step "%s" failed ' % self.step.sentence
assert_true(expr, msg)
def assert_false(self, expr):
msg = 'Step "%s" failed ' % self.step.sentence
assert_false(expr, msg)
@step(u'current user can execute sudo without password')
def check_current_user_sudo_nopwd(step):
step_assert(step).assert_true(utils.misc.can_execute_sudo_without_pwd())
@step(u'every RPM package available:')
def check_rpm_available(step):
for data in step.hashes:
step_assert(step).assert_true(utils.rpm.available(data['PackageName']))
@step(u'I clean yum cached data')
def clean_yum_caches(step):
step_assert(step).assert_true(utils.rpm.clean_all_cached_data())
@step(u'I setup OpenStack repository "(.*)" for environment "(.*)"')
def install_build_env_repo(step, repo, env_name):
step_assert(step).assert_true(utils.misc.install_build_env_repo(repo, env_name))
@step(u'yum repository with id "(.*)" is configured')
def check_yum_repository_with_id_exists(step, id):
step_assert(step).assert_true(utils.rpm.yum_repo_exists(id))
@step(u'I install RPM package\(s\):')
def install_rpm(step):
utils.rpm.clean_all_cached_data()
for data in step.hashes:
step_assert(step).assert_true(utils.rpm.install(data['PackageName']))
@step(u'every RPM package is installed:')
def check_rpm_installed(step):
for data in step.hashes:
step_assert(step).assert_true(utils.rpm.installed(data['PackageName']))
@step(u'I remove RPM package\(s\):')
def remove_rpm(step):
utils.rpm.clean_all_cached_data()
for data in step.hashes:
step_assert(step).assert_true(utils.rpm.remove(data['PackageName']))
@step(u'every RPM package is not installed:')
def check_rpm_not_installed(step):
for data in step.hashes:
step_assert(step).assert_false(utils.rpm.installed(data['PackageName']))
@step(u'I create MySQL database "(.*)"')
def create_mysql_db(step, db_name):
step_assert(step).assert_true(utils.mysql_cli.create_db(db_name, mysql_admin, mysql_admin_pwd))
@step(u'I grant all privileges on database "(.*)" to user "(.*)" identified by password "(.*)" at hosts:')
def setup_mysql_access_for_hosts(step, db_name, db_user, db_pwd):
for data in step.hashes:
step_assert(step).assert_true(utils.mysql_cli.grant_db_access_for_hosts(data['Hostname'],db_name, db_user, db_pwd, mysql_admin, mysql_admin_pwd))
@step(u'I grant all privileges on database "(.*)" to user "(.*)" identified by password "(.*)" locally')
def setup_mysql_access_local(step, db_name, db_user, db_pwd):
step_assert(step).assert_true(utils.mysql_cli.grant_db_access_local(db_name, db_user, db_pwd, mysql_admin, mysql_admin_pwd))
step_assert(step).assert_true(utils.mysql_cli.grant_db_access_local(db_name, mysql_admin, mysql_admin_pwd, mysql_admin, mysql_admin_pwd))
@step(u'every service is running:')
def every_service_is_running(step):
for data in step.hashes:
step_assert(step).assert_true(utils.service(data['ServiceName']).running())
@step(u'I start services:')
def start_services(step):
for data in step.hashes:
step_assert(step).assert_true(utils.service(data['ServiceName']).start())
@step(u'MySQL database "(.*)" exists')
def mysql_db_exists(step, db_name):
step_assert(step).assert_true(utils.mysql_cli.db_exists(db_name, mysql_admin, mysql_admin_pwd))
@step(u'user "(.*)" has all privileges on database "(.*)"')
def mysql_user_has_all_privileges(step, user, db_name):
step_assert(step).assert_true(utils.mysql_cli.user_has_all_privileges_on_db(user, db_name, mysql_admin, mysql_admin_pwd))
@step(u'I perform Nova DB sync')
def perform_nova_db_sync(step):
step_assert(step).assert_true(utils.nova_cli.db_sync())
@step(u'I stop services:')
def stop_services(step):
for data in step.hashes:
step_assert(step).assert_true(utils.service(data['ServiceName']).stop())
@step(u'every service is stopped:')
def every_service_is_stopped(step):
for data in step.hashes:
step_assert(step).assert_true(utils.service(data['ServiceName']).stopped())
@step(u'I clean state files:')
def clean_state_files(step):
for data in step.hashes:
step_assert(step).assert_true(utils.misc.remove_files_recursively_forced(data['PathWildCard']))
@step(u'no files exist:')
def no_files_exist(step):
for data in step.hashes:
step_assert(step).assert_true(utils.misc.no_files_exist(data['PathWildCard']))
@step(u'I change flag file "(.*)" by setting flag values:')
def change_flag_file(step,flag_file):
flags = [(flag['Name'],flag['Value']) for flag in step.hashes ]
step_assert(step).assert_true(utils.FlagFile(flag_file).apply_flags(flags).overwrite(flag_file))
@step(u'the following flags in file "(.*)" are set to:')
def verify_flag_file(step,flag_file):
flags = [(flag['Name'],flag['Value']) for flag in step.hashes ]
step_assert(step).assert_true(utils.FlagFile(flag_file).verify(flags))
@step(u'I create nova admin user "(.*)"')
def create_nova_admin(step, username):
step_assert(step).assert_true(utils.nova_cli.create_admin(username))
@step(u'nova user "(.*)" exists')
def nova_user_exists(step, user):
step_assert(step).assert_true(utils.nova_cli.user_exists(user))
@step(u'I create nova project "(.*)" for user "(.*)"')
def create_nova_project(step, name, user):
step_assert(step).assert_true(utils.nova_cli.create_project(name, user))
@step(u'nova project "(.*)" exists')
def nova_project_exists(step, project):
step_assert(step).assert_true(utils.nova_cli.project_exists(project))
@step(u'nova user "(.*)" is the manager of the nova project "(.*)"')
def nova_user_is_project_manager(step, user, project):
step_assert(step).assert_true(utils.nova_cli.user_is_project_admin(user, project))
@step(u'I create nova network "(.*)" with "(.*)" nets, "(.*)" IPs per network')
def create_nova_network(step, cidr, nets, ips):
step_assert(step).assert_true(utils.nova_cli.create_network(cidr, nets, ips))
@step(u'nova network "(.*)" exists')
def nova_network_exists(step, cidr):
step_assert(step).assert_true(utils.nova_cli.network_exists(cidr))
@step(u'novarc for project "(.*)", user "(.*)" is available')
def novarc_is_available(step, project, user):
utils.nova_cli.set_novarc(project, user, bunch_working_dir)
step_assert(step).assert_true(utils.nova_cli.novarc_available())
@step(u'VM image tarball is available at "(.*)"')
def http_resource_is_availaable(step, url):
step_assert(step).assert_true(utils.networking.http.probe(url))
@step(u'I download VM image tarball at "(.*)" and unpack it')
def download_tarball_then_unpack(step, url):
step_assert(step).assert_true(utils.networking.http.get(url, bunch_working_dir))
file = os.path.join(bunch_working_dir, utils.networking.http.basename(url))
step_assert(step).assert_true(utils.misc.extract_targz(file, bunch_working_dir))
@step(u'I register VM image "(.*)" for owner "(.*)" using disk "(.*)", ram "(.*)", kernel "(.*)"')
def register_all_images(step, name, owner, disk, ram, kernel):
step_assert(step).assert_true(utils.nova_cli.vm_image_register(name, owner,
os.path.join(bunch_working_dir,disk),
os.path.join(bunch_working_dir,ram),
os.path.join(bunch_working_dir, kernel)))
@step(u'VM image "(.*)" is registered')
def image_registered(step, name):
step_assert(step).assert_true(utils.nova_cli.vm_image_registered(name))
@step(u'I add keypair with name "(.*)" from file "(.*)"')
def add_keypair(step, name, file):
key_path = os.path.join(bunch_working_dir,file)
step_assert(step).assert_true(utils.nova_cli.add_keypair(name, key_path))
@step(u'keypair with name "(.*)" exists')
def keypair_exists(step, name):
step_assert(step).assert_true(utils.nova_cli.keypair_exists(name))
@step(u'I start VM instance "(.*)" using image "(.*)", flavor "(.*)" and keypair "(.*)"')
def start_vm_instance(step, name,image, flavor, keyname):
id_image_list = utils.nova_cli.get_image_id_list(image)
assert_equals(len(id_image_list), 1, "There are %s images with name %s: %s" % (len(id_image_list), name, str(id_image_list)))
id_flavor_list = utils.nova_cli.get_flavor_id_list(flavor)
assert_equals(len(id_flavor_list), 1, "There are %s flavors with name %s: %s" % (len(id_flavor_list), name, str(id_flavor_list)))
image_id = id_image_list[0]
flavor_id = id_flavor_list[0]
assert_true(image_id != '', image_id)
assert_true(flavor_id != '', flavor_id)
step_assert(step).assert_true(utils.nova_cli.start_vm_instance(name, image_id, flavor_id, keyname))
@step(u'I kill all processes:')
def kill_all_processes(step):
for data in step.hashes:
step_assert(step).assert_true(utils.misc.kill_process(data['Process']))
@step(u'VM instance "(.*)" comes up within "(.*)" seconds')
def wait_instance_comes_up_within(step, name, timeout):
step_assert(step).assert_true(utils.nova_cli.wait_instance_comes_up(name, int(timeout)))
@step(u'VM instance "(.*)" is pingable within "(.*)" seconds')
def vm_is_pingable(step, name, timeout):
ip = utils.nova_cli.get_instance_ip(name)
assert_true(ip != '', name)
step_assert(step).assert_true(utils.networking.icmp.probe(ip, int(timeout)))
@step(u'I see that "(.*)" port of VM instance "(.*)" is open and serves "(.*)" protocol')
def check_port_protocol(step, port, name, protocol):
ip = utils.nova_cli.get_instance_ip(name)
assert_true(ip != '', name)
step_assert(step).assert_true(utils.networking.nmap.open_port_serves_protocol(ip, port, protocol))
@step(u'I can log into VM "(.*)" via SSH as "(.*)"')
def check_can_log_via_ssh(step, name, user):
ip = utils.nova_cli.get_instance_ip(name)
assert_true(ip != '', name)
step_assert(step).assert_true(utils.ssh(ip, "exit", user).successful()) | griddynamics/bunch | samples/openstack-smoke/__init__.py | Python | gpl-3.0 | 10,675 |
import sys
from PIL import Image, ImageStat
# Covert image to greyscale, return average pixel brightness.
def brightness_method1( im_file ):
im = Image.open(im_file).convert('L')
stat = ImageStat.Stat(im)
return stat.mean[0]
# Covert image to greyscale, return RMS pixel brightness.
def brightness_method2( im_file ):
im = Image.open(im_file).convert('L')
stat = ImageStat.Stat(im)
return stat.rms[0]
# Return results of all methods
def brightness_all_method(im_file):
print(brightness_method1( im_file ))
print(brightness_method2( im_file ))
# Used with arguments
if( len(sys.argv) != 0 ):
brightness_all_method( sys.argv[1])
| mikehankey/fireball_camera | img/get_brightness.py | Python | gpl-3.0 | 669 |
package com.starwars.app.client.pager.presenter;
import com.starwars.app.client.abs.presenter.Presenter;
public interface Holoprojector extends Presenter<Holoprojector.Display> {
interface Display extends com.starwars.app.client.abs.presenter.ADisplay {
}
}
| vmacheret/StarWarsEssential | StarWarsApp/src/main/java/com/starwars/app/client/pager/presenter/Holoprojector.java | Java | gpl-3.0 | 264 |
<?php // phpcs:disable -- Maybe later.
/*
\defined( 'TSF_EXTENSION_MANAGER_PRESENT' ) or die;
// Remove WebEngine headers.
@header_remove();
// Send 202 and cache control.
@http_response_code( 202 );
// session_cache_limiter( 'nocache' ); :
@header( 'Expires: Thu, 19 Nov 1981 08:52:00 GMT' );
@header( 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' );
@header( 'Pragma: no-cache' );
@header( 'Date: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
// Deliver a little bit of content.
echo "\n";
// Done.
exit;
*/
| sybrew/The-SEO-Framework-Extension-Manager | extensions/premium/monitor/trunk/ping.php | PHP | gpl-3.0 | 546 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr" xml:lang="fr">
<head>
<title> Pointage </title>
<?PHP
include_once("../header.php");
include_once("../sql/files.php");
include_once("../sql/project_db.php");
include_once("../sql/cout_project_db.php");
include_once("../sql/previsionnel_cegid_db.php");
include_once("../sql/member_db.php");// lien croisé avec tool_db.php
include_once("../js/date_calendar.js"); // affichage calebdrier pour saisie date
include_once("../js/form_db.js"); // affichage calebdrier pour saisie date
?>
</head>
<body>
<div id="header">
<h1>Serveur Web Pointage : Validation Pointage depuis ETAP (Bac a Sable)</h1>
</div>
<div id="contenu">
<?PHP
showBandeauHeaderPage("Validation Pointage depuis ETAP( Bac a Sable)");
?>
<div class="article">
<div class="section">
<?php
showTracePOST();
echo "<p>
Gestion Pointage Import CEGID provenant de ETAP (Bac a Sable).<br/><br/>
[update] va mettre à jour la table de pointage à partir de la table d'import du bac à sable.<br/>
le bac à sable est alimenté par Autre\Pointage Import.<br/>
</p>";
$multiselection = blockCondition("multiselection_pointage", "<h4>multi-selection [<value>]</h4>", false);
$exec = applyNextPreviousSelectPointage();
echo"<p>";
global $SQL_TABLE_CEGID_POINTAGE;
global $urlPointage;
showProjectSelection(""/*url*/,""/*form*/,"yes"/*year*/,
LabelAction::ActionExport.",pointage;formaction='$urlPointage'",
"yes"/*user*/, "yes"/*previous*/, "yes"/*next*/,
$multiselection);
echo"<br/></p>";
$idBalise = "import_ETAP";
createHeaderBaliseDiv($idBalise, "<h3>Import depuis ETAP </h3>");
{
global $SQL_TABLE_CEGID_POINTAGE_IMPORT;
$FORM_NAME_LOAD="form_load_ETAP";
$formName = getURLVariable(PARAM_TABLE_FORM::TABLE_FORM_NAME_INSERT);
$res=0;
//excecution insert/update/truncate des données importées
if ($formName == $FORM_NAME_LOAD) {
//showError("apply Pointage Brut CEGID table import : $SQL_TABLE_CEGID_POINTAGE_IMPORT");
$res = applyPointageBrutCegid($SQL_TABLE_CEGID_POINTAGE_IMPORT);
}
$infoformLoad="<button type=\"button\"><a href=\"#openModalTruncate\">".LabelAction::ActionTruncate."</a></button>";
showLoadFile(
""/*url*/,""/*choose*/,""/*load*/,
//array(LabelAction::ActionImport,"insert_update",LabelAction::ActionTruncate)/*action*/,
array(LabelAction::ActionImport,"insert_update")/*action*/,
$infoformLoad,""/*file size*/,$FORM_NAME_LOAD/*form name*/);
}
endHeaderBaliseDiv($idBalise);
//Modal dialog pour le truncate
//attention on precise bien la table du truncate
$infoformTruncate = streamFormHidden(PARAM_TABLE_FORM::TABLE_FORM_NAME_INSERT,$FORM_NAME_LOAD);
echoComment("$ infoformTruncate : $infoformTruncate" );
echo"
<div id=\"openModalTruncate\" class=\"modalDialog\">
<div>
<a href=\"#close\" title=\"Close\" class=\"close\">X</a>
<h2>Validation</h2>
<p>Est vous sure de vouloir vider la table d'import?</p>
<div align=center > <button type=\"button\">";
showMiniForm(""/*url*/, "form_validation_ETAP_truncate"/*form name*/,
LabelAction::ActionTruncate/*action*/, LabelAction::ActionTruncate/*label action*/,
""/*id form*/, "no"/*useTD*/,$infoformTruncate/*infoForm*/);
echo" </button></div>
</div>
</div>";
//actions
if ($res<=0){
$res = applyGestionOneProject();
}
if ($res<=0){
$res = applyGestionCoutOneProjectForm();
}
if ($res <=0){
$res = applyGestionTablePointageProjetCegid($SQL_TABLE_CEGID_POINTAGE);
}
// if ($res <=0){
// $res = applySynchronizePrevisionnel();
// }
beginTable();
beginTableRow( getVAlign("top") );
beginTableCell();
showGestionOneProject();
endTableCell();
beginTableCell();
//showTableCoutOneProject();
showTableCoutOneProjectImport();
endTableCell();
endTableRow();
endTable();
//permet d'ajout un pointage pour un utilisateur
//showInsertTablePointageCegid();
//pour la resynchronisation
//showSynchronizePrevisionnel();
echo"<br>";
//legend
$txt = "Legende : <br>
- import sur vide : couleur bleu <br>
- import valeur existante differente : couleur rouge [pointage/import]<br>
- import valeur equivalente : couleur verte <br>
- valeur hors import : couleur noire <br>"
;
echo "".getActionMessage($txt,"#FFFFFF");
//show tableau fusion pointage & import
showTableImportPointageCegid();
$txt="[update] va mettre à jour la table de pointage à partir de la table d'import du bac à sable";
echo "".getActionMessage($txt,"#FFBBBB");
?>
<br/><br/><br/>
</div> <!-- section -->
</div> <!-- article -->
</div> <!-- contenu -->
<?PHP include("../menu.php"); ?>
<?PHP include("../sql/deconnection_db.php"); ?>
<?PHP include("../footer.php"); ?>
</body>
</html> | selleron/pointageWebCEGID | user/validation_import_ETAP_cegid.php | PHP | gpl-3.0 | 5,336 |
namespace Trezorix.Sparql.Api.Admin.Controllers.Api {
using System.Net;
using System.Web.Http;
using Trezorix.Sparql.Api.Admin.Controllers.Attributes;
using Trezorix.Sparql.Api.Application.Attributes;
using Trezorix.Sparql.Api.Core.Configuration;
[RoutePrefix("Api/Settings")]
[NLogWebApi]
[AuthenticateUser]
[Authorize]
public class SettingsController : ApiController
{
[HttpGet]
public dynamic Get()
{
return ApiConfiguration.Current;
}
[HttpGet]
public dynamic Get(string id)
{
return ApiConfiguration.Current;
}
[HttpPost]
public dynamic Post(string id, ApiConfiguration model)
{
ApiConfiguration.Save(model);
var webclient = new WebClient();
webclient.OpenRead(ApiConfiguration.Current.QueryApiUrl + "/Home/Reload");
return Ok();
}
[HttpPost]
[Route("ClearCache")]
public dynamic ClearCache()
{
var webclient = new WebClient();
webclient.OpenRead(ApiConfiguration.Current.QueryApiUrl + "/Home/ClearCache");
return Ok();
}
}
} | kennisnet/Sparql-Query-Api | src/Admin/Controllers/Api/SettingsController.cs | C# | gpl-3.0 | 1,058 |
//
// X-RunUO - Ultima Online Server Emulator
// Copyright (C) 2015 Pedro Pardal
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Collections.Generic;
using System.Text;
using Server.Network;
namespace Server.Gumps
{
public abstract class Gump
{
private List<GumpEntry> m_Entries;
private List<string> m_Strings;
internal int m_TextEntries, m_Switches;
private static int m_NextSerial = 1;
private int m_Serial;
private int m_TypeID;
private int m_X, m_Y;
private bool m_Dragable = true;
private bool m_Closable = true;
private bool m_Resizable = true;
private bool m_Disposable = true;
public virtual int TypeID { get { return m_TypeID; } }
public Gump( int x, int y )
{
do
{
m_Serial = m_NextSerial++;
} while ( m_Serial == 0 ); // standard client apparently doesn't send a gump response packet if serial == 0
m_TypeID = GetType().FullName.GetHashCode();
m_X = x;
m_Y = y;
m_Entries = new List<GumpEntry>();
m_Strings = new List<string>();
}
public List<GumpEntry> Entries
{
get { return m_Entries; }
}
public int Serial
{
get
{
return m_Serial;
}
set
{
if ( m_Serial != value )
m_Serial = value;
}
}
public int X
{
get
{
return m_X;
}
set
{
if ( m_X != value )
m_X = value;
}
}
public int Y
{
get
{
return m_Y;
}
set
{
if ( m_Y != value )
m_Y = value;
}
}
public bool Disposable
{
get
{
return m_Disposable;
}
set
{
if ( m_Disposable != value )
m_Disposable = value;
}
}
public bool Resizable
{
get
{
return m_Resizable;
}
set
{
if ( m_Resizable != value )
m_Resizable = value;
}
}
public bool Dragable
{
get
{
return m_Dragable;
}
set
{
if ( m_Dragable != value )
m_Dragable = value;
}
}
public bool Closable
{
get
{
return m_Closable;
}
set
{
if ( m_Closable != value )
m_Closable = value;
}
}
#region Add[...]
public void AddPage( int page )
{
Add( new GumpPage( page ) );
}
public void AddAlphaRegion( int x, int y, int width, int height )
{
Add( new GumpAlphaRegion( x, y, width, height ) );
}
public void AddBackground( int x, int y, int width, int height, int gumpID )
{
Add( new GumpBackground( x, y, width, height, gumpID ) );
}
public void AddKRButton( int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param )
{
Add( new KRGumpButton( x, y, normalID, pressedID, buttonID, type, param ) );
}
public void AddButton( int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param )
{
Add( new GumpButton( x, y, normalID, pressedID, buttonID, type, param ) );
}
public void AddCheck( int x, int y, int inactiveID, int activeID, bool initialState, int switchID )
{
Add( new GumpCheck( x, y, inactiveID, activeID, initialState, switchID ) );
}
public void AddGroup( int group )
{
Add( new GumpGroup( group ) );
}
public void AddHtml( int x, int y, int width, int height, string text, bool background, bool scrollbar )
{
Add( new GumpHtml( x, y, width, height, text, background, scrollbar ) );
}
public void AddHtmlIntern( int x, int y, int width, int height, int textid, bool background, bool scrollbar )
{
Add( new GumpHtml( x, y, width, height, textid, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, int color, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, color, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, string args, int color, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, args, color, background, scrollbar ) );
}
public void AddKRHtmlLocalized( int x, int y, int width, int height, int number, bool background, bool scrollbar )
{
Add( new KRGumpHtmlLocalized( x, y, width, height, number, background, scrollbar ) );
}
public void AddKRHtmlLocalized( int x, int y, int width, int height, int number, int color, bool background, bool scrollbar )
{
Add( new KRGumpHtmlLocalized( x, y, width, height, number, color, background, scrollbar ) );
}
public void AddKRLabel( int x, int y, int width, int height, int number, bool background, bool scrollbar )
{
Add( new KRGumpLabel( x, y, width, height, number, background, scrollbar ) );
}
public void AddKRImage( int x, int y, int gumpID )
{
Add( new KRGumpImage( x, y, gumpID ) );
}
public void AddImage( int x, int y, int gumpID )
{
Add( new GumpImage( x, y, gumpID ) );
}
public void AddImage( int x, int y, int gumpID, int hue )
{
Add( new GumpImage( x, y, gumpID, hue ) );
}
public void AddImageTiled( int x, int y, int width, int height, int gumpID )
{
Add( new GumpImageTiled( x, y, width, height, gumpID ) );
}
public void AddItem( int x, int y, int itemID )
{
Add( new GumpItem( x, y, itemID ) );
}
public void AddItem( int x, int y, int itemID, int hue )
{
Add( new GumpItem( x, y, itemID, hue ) );
}
public void AddLabel( int x, int y, int hue, string text )
{
Add( new GumpLabel( x, y, hue, text ) );
}
public void AddLabelIntern( int x, int y, int hue, int textid )
{
Add( new GumpLabel( x, y, hue, textid ) );
}
public void AddLabelCropped( int x, int y, int width, int height, int hue, string text )
{
Add( new GumpLabelCropped( x, y, width, height, hue, text ) );
}
public void AddRadio( int x, int y, int inactiveID, int activeID, bool initialState, int switchID )
{
Add( new GumpRadio( x, y, inactiveID, activeID, initialState, switchID ) );
}
public void AddTextEntry( int x, int y, int width, int height, int hue, int entryID, string initialText )
{
Add( new GumpTextEntry( x, y, width, height, hue, entryID, initialText ) );
}
public void AddTextEntry( int x, int y, int width, int height, int hue, int entryID, string initialText, int size )
{
Add( new GumpTextEntryLimited( x, y, width, height, hue, entryID, initialText, size ) );
}
public void AddTextEntryIntern( int x, int y, int width, int height, int hue, int entryID, int initialTextID )
{
Add( new GumpTextEntry( x, y, width, height, hue, entryID, initialTextID ) );
}
public void AddTooltip( int number )
{
Add( new GumpTooltip( number ) );
}
public void AddTooltip( int number, string args )
{
Add( new GumpTooltip( number, args ) );
}
public void AddButtonTileArt( int x, int y, int normalID, int pressedID, GumpButtonType type, int param, int buttonID, int itemid, int hue, int width, int height )
{
Add( new GumpButtonTileArt( x, y, normalID, pressedID, type, param, buttonID, itemid, hue, width, height ) );
}
public void AddItemProperty( Item item )
{
Add( new GumpItemProperty( item.Serial.Value ) );
}
#endregion
public void Add( GumpEntry g )
{
if ( g.Parent != this )
{
g.Parent = this;
}
else if ( !m_Entries.Contains( g ) )
{
m_Entries.Add( g );
}
}
public void Remove( GumpEntry g )
{
m_Entries.Remove( g );
g.Parent = null;
}
public int Intern( string value, bool enforceUnique )
{
if ( enforceUnique )
{
int indexOf = m_Strings.IndexOf( value );
if ( indexOf >= 0 )
return indexOf;
}
m_Strings.Add( value );
return m_Strings.Count - 1;
}
public int Intern( string value )
{
return Intern( value, false );
}
public void SendTo( GameClient state )
{
state.AddGump( this );
state.Send( Compile() );
}
public static byte[] StringToBuffer( string str )
{
return Encoding.ASCII.GetBytes( str );
}
private static byte[] m_BeginLayout = StringToBuffer( "{ " );
private static byte[] m_EndLayout = StringToBuffer( " }" );
private static byte[] m_NoMove = StringToBuffer( "{ nomove }" );
private static byte[] m_NoClose = StringToBuffer( "{ noclose }" );
private static byte[] m_NoDispose = StringToBuffer( "{ nodispose }" );
private static byte[] m_NoResize = StringToBuffer( "{ noresize }" );
protected Packet Compile()
{
IGumpWriter disp = new DisplayGumpPacked( this );
if ( !m_Dragable )
disp.AppendLayout( m_NoMove );
if ( !m_Closable )
disp.AppendLayout( m_NoClose );
if ( !m_Disposable )
disp.AppendLayout( m_NoDispose );
if ( !m_Resizable )
disp.AppendLayout( m_NoResize );
int count = m_Entries.Count;
GumpEntry e;
for ( int i = 0; i < count; ++i )
{
e = m_Entries[i];
disp.AppendLayout( m_BeginLayout );
e.AppendTo( disp );
disp.AppendLayout( m_EndLayout );
}
disp.WriteStrings( m_Strings );
disp.Flush();
m_TextEntries = disp.TextEntries;
m_Switches = disp.Switches;
return disp as Packet;
}
public virtual void OnResponse( GameClient sender, RelayInfo info )
{
}
public virtual void OnServerClose( GameClient owner )
{
}
}
} | greeduomacro/xrunuo | Server/Gumps/Gump.cs | C# | gpl-3.0 | 10,433 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WindowsPortableDevicesLib.Domain;
using WindowsPortableDevicesLib;
namespace AndroSyncTunes {
/// <summary>
/// This class is an abstraction for connected MTP devices
/// </summary>
class Devices {
private StandardWindowsPortableDeviceService devices_service;
/// <summary>
/// Array of devices, created when object is created
/// </summary>
public IList<WindowsPortableDevice> DevicesList { get; }
/// <summary>
/// List of list of key pair (string, string) = (Name, PersistentID) of the main resources for a device
/// </summary>
public IList<IList<KeyValuePair<String, PortableDeviceObject>>> DevicesResourcesList { get; }
public Devices() {
this.devices_service = new StandardWindowsPortableDeviceService();
this.DevicesList = devices_service.Devices;
this.DevicesResourcesList = new List<IList<KeyValuePair<String, PortableDeviceObject>>>();
if (DevicesList.Count != 0) {
int i = 0;
foreach (WindowsPortableDevice device in DevicesList) {
device.Connect();
this.DevicesResourcesList.Add(new List<KeyValuePair<String, PortableDeviceObject>>());
foreach (PortableDeviceFolder item in device.GetContents().Files) {
DevicesResourcesList[i].Add(new KeyValuePair<string, PortableDeviceObject>(item.Name, item));
}
device.Disconnect();
}
}
}
}
}
| gabry3795/androsynctunes | AndroSyncTunes/Devices.cs | C# | gpl-3.0 | 1,683 |
var spa = "spa/scripts/";
require.config({
jsx: {
fileExtension: '.jsx'
},
paths: {
'spa': "spa/scripts",
'underscore': "spa/scripts/vendor/underscore",
'jquery': "spa/scripts/vendor/jquery",
'Q': 'spa/scripts/vendor/q',
'marked': 'spa/scripts/vendor/marked',
'backbone': 'spa/scripts/vendor/backbone',
'react': "spa/scripts/vendor/react-dev",
'immutable': "spa/scripts/vendor/immutable",
'JSXTransformer': "spa/scripts/vendor/JSXTransformer",
'PDFJS': "spa/scripts/vendor/pdfjs/pdf"
},
shim: {
'PDFJS': {
exports: 'PDFJS',
deps: ['spa/vendor/pdfjs/generic/web/compatibility',
'spa/vendor/ui_utils'] }
}
});
define(function (require) {
window.React = require('react'); // for pref tools
require("app");
});
| vortext/vortext-demo | resources/public/scripts/main.js | JavaScript | gpl-3.0 | 804 |
package ubu.digit.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* Clase para la obtención de los valores de las propiedades.
*
* @author Beatriz Zurera Martínez-Acitores.
* @since 3.0
*/
public class ExternalProperties {
/**
* Logger de la clase.
*/
private static final Logger LOGGER = Logger.getLogger(ExternalProperties.class);
/**
* Propiedad.
*/
private static final Properties PROPERTIES = new Properties();
/**
* Fichero del que leeremos las propiedades.
*/
private static String FILE;
/**
* Instancia que tendrá la propiedad.
*/
private static ExternalProperties instance;
/**
* Constructor.
*/
private ExternalProperties() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(FILE);
PROPERTIES.load(inputStream);
} catch (IOException e) {
LOGGER.error("", e);
}
}
/**
* Método singleton para obtener la instancia de la clase fachada.
*/
public static ExternalProperties getInstance(String propFileName) {
if (instance == null) {
FILE = propFileName;
instance = new ExternalProperties();
}
return instance;
}
/**
* Método que obtiene el valor de la propiedad que se pasa.
*
* @param key
* Propiedad de la cual queremos conocer el valor.
* @return El valor de la propiedad.
*/
public String getSetting(String key) {
return PROPERTIES.getProperty(key).trim();
}
} | mdg1001/GESPRO_GESTIONVERSIONES | SistInfGenWeb_4.0_src/src/main/ubu/digit/util/ExternalProperties.java | Java | gpl-3.0 | 1,720 |
/* text-grid-view.cpp
*
* Copyright(C) 2017 Tony Houghton
*
* 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 "defns.h"
#include "app.h"
#include "text-grid-view.h"
#include "text-grid-widget.h"
namespace Gnvim
{
TextGridView::TextGridView(int columns, int lines,
const std::string &font_name)
: grid_(columns, lines),
columns_(columns), lines_(lines),
font_(font_name.length() ? font_name : DEFAULT_FONT)
{
auto settings = Application::sys_gsettings();
cursor_blinks_ = settings->get_boolean("cursor-blink");
cursor_blink_cx_ = settings->signal_changed("cursor-blink").connect
(sigc::mem_fun(*this, &TextGridView::on_cursor_gsetting_changed));
cursor_interval_ = settings->get_int("cursor-blink-time") / 2;
cursor_blink_time_cx_ = settings->signal_changed
("cursor-blink-time").connect
(sigc::mem_fun(*this, &TextGridView::on_cursor_gsetting_changed));
cursor_timeout_ = settings->get_int("cursor-blink-timeout") * 1000000;
cursor_blink_timeout_cx_ = settings->signal_changed
("cursor-blink-timeout").connect
(sigc::mem_fun(*this, &TextGridView::on_cursor_gsetting_changed));
cursor_attr_.set_background_rgb(grid_.get_default_foreground_rgb());
cursor_attr_.set_foreground_rgb(grid_.get_default_background_rgb());
show_cursor();
}
TextGridView::~TextGridView()
{
cursor_blink_cx_.disconnect();
cursor_blink_time_cx_.disconnect();
cursor_blink_timeout_cx_.disconnect();
if (cursor_cx_.connected())
cursor_cx_.disconnect();
}
void TextGridView::set_current_widget(Gtk::Widget *w)
{
current_widget_ = static_cast<TextGridWidget *>(w);
}
void TextGridView::show_cursor()
{
cursor_idle_at_ = g_get_monotonic_time() + cursor_timeout_;
cursor_visible_ = false;
on_cursor_blink();
if (cursor_cx_.connected())
cursor_cx_.disconnect();
if (cursor_blinks_ && current_widget_ && current_widget_->has_focus())
{
cursor_cx_ = Glib::signal_timeout().connect
(sigc::mem_fun(*this, &TextGridView::on_cursor_blink),
cursor_interval_);
}
}
bool TextGridView::on_cursor_blink()
{
bool no_blink = (g_get_monotonic_time() - cursor_idle_at_ > 0)
|| !cursor_blinks_ || !current_widget_ || !current_widget_->has_focus();
cursor_visible_ = no_blink ? true : !cursor_visible_;
if (current_widget_)
{
current_widget_->queue_draw_area(cursor_col_ * cell_width_px_,
cursor_line_ * cell_height_px_,
cell_width_px_, cell_height_px_);
}
return !no_blink;
}
void TextGridView::on_cursor_gsetting_changed(const Glib::ustring &key)
{
auto settings = Application::sys_gsettings();
if (key == "cursor-blink")
cursor_blinks_ = settings->get_int("cursor-blink");
else if (key == "cursor-blink-time")
cursor_interval_ = settings->get_int("cursor-blink-time") / 2;
else if (key == "cursor-blink-timeout")
{
cursor_timeout_ = settings->get_int("cursor-blink-timeout") * 1000000;
return;
}
show_cursor();
}
void TextGridView::set_font(RefPtr<Pango::Context> pc,
const Glib::ustring &desc, bool resize)
{
font_ = Pango::FontDescription(desc.length() ? desc : DEFAULT_FONT);
calculate_metrics(pc);
if (resize)
{
resize_surface();
redraw_view();
}
}
void TextGridView::resize_surface()
{
grid_surface_ = Cairo::Surface::create(grid_surface_, Cairo::CONTENT_COLOR,
cell_width_px_ * columns_,
cell_height_px_ * lines_);
grid_cr_ = Cairo::Context::create(grid_surface_);
}
void TextGridView::on_size_allocate(Gtk::Allocation &allocation)
{
int w = allocation.get_width();
int h = allocation.get_height();
//g_debug("TextGridView size_allocate %d x %d", w, h);
// Size requests and allocations appear not to include margins
columns_ = w / cell_width_px_;
lines_ = h / cell_height_px_;
if (grid_.get_columns() != columns_ || grid_.get_lines() != lines_)
{
grid_.resize(columns_, lines_);
if (grid_surface_)
resize_surface();
}
}
void TextGridView::create_cairo_surface(Gtk::Widget *w)
{
if (!grid_cr_)
{
auto gwin = w->get_window();
if (gwin)
{
calculate_metrics(w->get_pango_context());
grid_surface_ = gwin->create_similar_surface
(Cairo::CONTENT_COLOR,
cell_width_px_ * columns_,
cell_height_px_ * lines_);
grid_cr_ = Cairo::Context::create(grid_surface_);
redraw_view();
}
else
{
g_warning("No GdkWindow to create cairo surface");
}
}
/*
else
{
g_debug("Already have a cairo surface");
}
*/
}
void TextGridView::redraw_view()
{
clear_view();
for (int line = 0; line < lines_; ++line)
grid_.draw_line(grid_cr_, line, 0, columns_ - 1);
}
void TextGridView::scroll(int left, int top, int right, int bottom, int count)
{
grid_.scroll(left, top, right, bottom, count);
if (global_redraw_pending_)
return;
int src_top, dest_top, clear_top, copy_height;
int left_px = left * cell_width_px_;
int width_px = (right - left + 1) * cell_width_px_;
if (count > 0)
{
dest_top = top;
src_top = top + count;
copy_height = bottom - top + 1 - count;
clear_top = bottom + 1 - count;
}
else
{
src_top = top;
dest_top = top - count;
copy_height = bottom - top + 1 + count;
clear_top = top;
}
src_top *= cell_height_px_;
dest_top *= cell_height_px_;
copy_height *= cell_height_px_;
// Create a surface which is a copy of the region to be moved.
auto copy_surf = Cairo::Surface::create(grid_surface_,
Cairo::CONTENT_COLOR, width_px, copy_height);
auto copy_cr = Cairo::Context::create(copy_surf);
copy_cr->set_source(grid_surface_, -left_px, -src_top);
copy_cr->paint();
// Paint the movable surface to its new position
grid_cr_->save();
grid_cr_->rectangle(left_px, dest_top, width_px, copy_height);
grid_cr_->clip();
grid_cr_->set_source(copy_surf, left_px, dest_top);
grid_cr_->paint();
grid_cr_->restore();
// Clear the area "uncovered" by the moved region
if (count < 0)
count = -count;
//g_debug("Scroll filling background");
fill_background(grid_cr_, left, clear_top, right, clear_top + count - 1);
}
void TextGridView::fill_background(Cairo::RefPtr<Cairo::Context> cr,
int left, int top, int right, int bottom, guint32 rgb)
{
fill_background_px(cr,
left * cell_width_px_, top * cell_height_px_,
(right - left + 1) * cell_width_px_,
(bottom - top + 1) * cell_height_px_, rgb);
}
void TextGridView::fill_background_px(Cairo::RefPtr<Cairo::Context> cr,
int left, int top, int width, int height, guint32 rgb)
{
float r, g, b;
CellAttributes::decompose_colour_float(rgb, r, g, b);
cr->set_source_rgb(r, g, b);
cr->rectangle(left, top, width, height);
cr->fill();
}
void TextGridView::calculate_metrics(RefPtr<Pango::Context> pc)
{
auto metrics = pc->get_metrics(font_);
// digit_width and char_width should be the same for monospace, but
// digit_width might be slightly more useful in case we accidentally use
// a proportional font
cell_width_px_ = metrics.get_approximate_digit_width() / PANGO_SCALE;
cell_height_px_ = (metrics.get_ascent() + metrics.get_descent())
/ PANGO_SCALE;
//g_debug("calculate_metrics: %d x %d", cell_width_px_, cell_height_px_);
grid_.set_cell_size(cell_width_px_, cell_height_px_);
grid_.set_font(font_);
}
void TextGridView::get_preferred_width(int &minimum, int &natural) const
{
auto cols = grid_.get_columns();
minimum = 5 * cell_width_px_;
natural = cols * cell_width_px_;
//g_debug("Preferred width %d columns * %dpx = %d",
// cols, cell_width_px_, natural);
}
void TextGridView::get_preferred_height(int &minimum, int &natural) const
{
auto lines = grid_.get_lines();
minimum = 5 * cell_height_px_;
natural = lines * cell_height_px_;
//g_debug("Preferred height %d lines * %dpx = %d",
// lines, cell_height_px_, natural);
}
void TextGridView::draw_cursor(Cairo::RefPtr<Cairo::Context> cr)
{
if (cursor_visible_)
{
guint32 curs_colour = cursor_attr_.get_background_rgb();
if (current_widget_->has_focus())
{
if (cursor_width_)
{
fill_background_px(cr,
cursor_col_ * cell_width_px_,
cursor_line_ * cell_height_px_,
cursor_width_, cell_height_px_,
curs_colour);
}
else
{
fill_background(cr,
cursor_col_, cursor_line_, cursor_col_, cursor_line_,
curs_colour);
grid_.draw_line(cr, cursor_line_, cursor_col_, cursor_col_,
&cursor_attr_);
}
}
else
{
float r, g, b;
CellAttributes::decompose_colour_float(curs_colour, r, g, b);
cr->begin_new_path();
cr->set_source_rgb(r, g, b);
cr->rectangle(cursor_col_ * cell_width_px_,
cursor_line_ * cell_height_px_,
cell_width_px_, cell_height_px_);
cr->set_line_width(1);
cr->stroke();
}
}
}
}
| realh/gnvim | src/text-grid-view.cpp | C++ | gpl-3.0 | 10,307 |
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
HttpClient,
HttpParams,
HttpEvent,
HttpHeaders,
HttpRequest,
HttpEventType,
HttpErrorResponse
} from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { CommonService } from '@geonature_common/service/common.service';
export const FormatMapMime = new Map([
['csv', 'text/csv'],
['json', 'application/json'],
['shp', 'application/zip']
]);
@Component({
selector: 'pnx-modal-download',
templateUrl: 'modal-download.component.html',
styleUrls: ['./modal-download.component.scss']
})
export class ModalDownloadComponent implements OnInit {
@Input() pathDownload: string;
@Input() queryString: HttpParams;
@Input() exportFormat: Array<string>;
@Input() labelButton: string;
@Input() downloadMessage: string;
@Output() buttonClicked = new EventEmitter<any>();
public downloadProgress$: BehaviorSubject<number>;
public isDownloading: boolean = false;
private _blob: Blob;
public message = 'Téléchargement en cours';
public type = 'info';
public animated = true;
public endLoad: boolean = false;
constructor(
private _modalService: NgbModal,
private _api: HttpClient,
private _commonService: CommonService
) {
this.downloadProgress$ = <BehaviorSubject<number>>new BehaviorSubject(0.0);
this.downloadProgress$.subscribe(state => {
if (state === 100) {
this.done();
this.endLoad = true;
}
});
}
ngOnInit() {
this.labelButton = this.labelButton || 'Télécharger';
this.queryString = this.queryString || new HttpParams();
}
loadData(format) {
this.isDownloading = true;
this.progress();
this.queryString = this.queryString.set('export_format', format);
document.location.href = `${this.pathDownload}?${this.queryString.toString()}`;
this.donwloadStatus(this.pathDownload, format, this.queryString);
}
openModal(content) {
this._modalService.open(content);
this.buttonClicked.emit();
}
donwloadStatus(url: string, format: string, queryString: HttpParams) {
this.isDownloading = true;
const source = this._api.get(`${url}?${queryString.toString()}`, {
headers: new HttpHeaders().set('Content-Type', `${FormatMapMime.get(format)}`),
observe: 'events',
responseType: 'blob',
reportProgress: true
});
const subscription = source.subscribe(
event => {
switch (event.type) {
case HttpEventType.DownloadProgress:
if (event.hasOwnProperty('total')) {
const percentage = Math.round((100 / event.total) * event.loaded);
this.downloadProgress$.next(percentage);
} else {
const kb = (event.loaded / 1024).toFixed(2);
this.downloadProgress$.next(parseFloat(kb));
}
break;
case HttpEventType.Response:
this._blob = new Blob([event.body], { type: event.headers.get('Content-Type') });
break;
}
},
(e: HttpErrorResponse) => {
this._commonService.translateToaster('error', 'ErrorMessage');
this.isDownloading = false;
},
() => {
this.isDownloading = false;
subscription.unsubscribe();
}
);
}
progress() {
this.downloadProgress$.next(0.0);
this.message = 'Téléchargement en cours';
this.type = 'info';
this.animated = true;
}
done() {
this.message = 'Export téléchargé avec succès ! Veuillez patienter ... ';
this.type = 'success';
this.animated = false;
}
}
| PnX-SI/GeoNature | frontend/src/app/GN2CommonModule/others/modal-download/modal-download.component.ts | TypeScript | gpl-3.0 | 3,686 |
package me.winter.trapgame.util;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
/**
*
* Created by Alexander Winter on 2016-01-12.
*/
public class StringUtil
{
private StringUtil() {}
public static String join(List<?> list)
{
return join(list.toArray());
}
public static String join(List<?> list, String separator)
{
return join(list.toArray(), separator);
}
public static String join(Object[] array)
{
return join(array, ", ");
}
public static String join(Object[] array, String separator)
{
if(array.length == 0)
return "";
String result = array[0].toString();
for(int index = 1; index < array.length; index++)
result += separator + array[index];
return result;
}
public static String getStackTrace(Throwable throwable)
{
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
public static String capitalize(String string)
{
char[] letters = string.toCharArray();
for(int index = 0; index < letters.length; index++)
{
if(index != 0 && !Character.isWhitespace(letters[index - 1]))
continue;
if(!Character.isLowerCase(letters[index]))
continue;
letters[index] = Character.toUpperCase(letters[index]);
}
return new String(letters);
}
public static String getLastPart(String toSplit, String regex)
{
String[] parts = toSplit.split(regex);
return parts[parts.length - 1];
}
public static String backspace(String string, int index)
{
if(index <= 0 || index > string.length())
return string;
if(index == 1)
return string.substring(index);
if(index == string.length())
return string.substring(0, index - 1);
return string.substring(0, index - 1) + string.substring(index);
}
public static String insert(String string, int index, char input)
{
return insert(string, index, input + "");
}
public static String insert(String string, int index, String input)
{
if(index <= 0)
return input + string;
if(index >= string.length())
return string + input;
return string.substring(0, index) + input + string.substring(index);
}
public static String getClipboardContent()
{
try
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return clipboard.getContents(null) == null ? "" : clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor).toString();
}
catch(Exception e)
{
e.printStackTrace();
return "";
}
}
public static void setClipboardContent(String content)
{
try
{
StringSelection stringSelection = new StringSelection(content);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static boolean isInt(String string)
{
try
{
Integer.parseInt(string);
return true;
}
catch(Exception e)
{
return false;
}
}
public static boolean isLong(String string)
{
try
{
Long.parseLong(string);
return true;
}
catch(Exception e)
{
return false;
}
}
public static boolean isDouble(String string)
{
try
{
Double.parseDouble(string);
return true;
}
catch(Exception e)
{
return false;
}
}
public static boolean isFloat(String string)
{
try
{
Float.parseFloat(string);
return true;
}
catch(Exception e)
{
return false;
}
}
public static String htmlSpecialChars(String html)
{
StringBuilder builder = new StringBuilder(html);
for(int index = 0; index < builder.length(); index++)
{
String toInsert;
switch(builder.charAt(index))
{
case '<':
toInsert = "<";
break;
case '>':
toInsert = ">";
break;
case '\'':
toInsert = "'";
break;
case '"':
toInsert = """;
break;
case '&':
toInsert = "&";
break;
default:
continue;
}
builder.deleteCharAt(index);
builder.insert(index, toInsert);
index += toInsert.length() - 1;
}
return builder.toString();
}
public static String toCSS(Color color)
{
return "rgb(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ")";
}
public static String noHTML(String html)
{
return html.replaceAll("\n|\r", "").replaceAll("<br\\s*/?>", "\n").replaceAll("<[^<>]+>", "");
}
}
| WinterGuardian/TrapGame | src/me/winter/trapgame/util/StringUtil.java | Java | gpl-3.0 | 4,804 |
'use strict';
angular.module('risevision.editorApp.directives')
.directive('resolutionSelector', [
function () {
return {
restrict: 'E',
scope: false,
templateUrl: 'partials/resolution-selector.html',
link: function (scope) {
// view will show resolutions on the same order from this object declaration
scope.resolutionOptions = {
'1024x768': '1024 x 768',
'1280x1024': '1280 x 1024',
'1600x1200': '1600 x 1200',
'1280x720': '1280 x 720 Wide',
'1280x768': '1280 x 768 Wide',
'1360x768': '1360 x 768 Wide',
'1366x768': '1366 x 768 Wide',
'1440x900': '1440 x 900 Wide',
'1680x1050': '1680 x 1050 Wide',
'1920x1080': '1920 x 1080 Wide',
'720x1280': '720 x 1280 Portrait',
'768x1280': '768 x 1280 Portrait',
'768x1360': '768 x 1360 Portrait',
'768x1366': '768 x 1366 Portrait',
'1080x1920': '1080 x 1920 Portrait',
'custom': 'Custom'
};
if (scope.presentationProperties.width && scope.presentationProperties
.height) {
scope.resolutionOption = scope.presentationProperties.width +
'x' + scope.presentationProperties.height;
if (!(scope.resolutionOption in scope.resolutionOptions)) {
scope.resolutionOption = 'custom';
}
}
scope.updateResolution = function () {
if (scope.resolutionOption !== 'custom') {
var sizes = scope.resolutionOption.split('x');
scope.presentationProperties.width = parseInt(sizes[0]);
scope.presentationProperties.height = parseInt(sizes[1]);
}
};
scope.objectKeys = function (obj) {
return Object.keys(obj);
};
} //link()
};
}
]);
| Rise-Vision/editor-app | js/directives/dtv-resolution-selector.js | JavaScript | gpl-3.0 | 2,034 |
Simpla CMS 2.3.8 = e6bad03ff13cc2b915136d66efa673fb
| gohdan/DFC | known_files/hashes/api/Users.php | PHP | gpl-3.0 | 52 |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import backtrader as bt
class DataFilter(bt.AbstractDataBase):
'''
This class filters out bars from a given data source. In addition to the
standard parameters of a DataBase it takes a ``funcfilter`` parameter which
can be any callable
Logic:
- ``funcfilter`` will be called with the underlying data source
It can be any callable
- Return value ``True``: current data source bar values will used
- Return value ``False``: current data source bar values will discarded
'''
params = (('funcfilter', None),)
def preload(self):
if len(self.p.dataname) == self.p.dataname.buflen():
# if data is not preloaded .... do it
self.p.dataname.start()
self.p.dataname.preload()
self.p.dataname.home()
# Copy timeframe from data after start (some sources do autodetection)
self.p.timeframe = self._timeframe = self.p.dataname._timeframe
self.p.compression = self._compression = self.p.dataname._compression
super(DataFilter, self).preload()
def _load(self):
if not len(self.p.dataname):
self.p.dataname.start() # start data if not done somewhere else
# Tell underlying source to get next data
while self.p.dataname.next():
# Try to load the data from the underlying source
if not self.p.funcfilter(self.p.dataname):
continue
# Data is allowed - Copy size which is "number of lines"
for i in range(self.p.dataname.size()):
self.lines[i][0] = self.p.dataname.lines[i][0]
return True
return False # no more data from underlying source
| mementum/backtrader | backtrader/filters/datafilter.py | Python | gpl-3.0 | 2,743 |
import React from 'react';
import Select from 'react-select';
import axios from 'axios';
export default class RuleTypeSelector extends React.Component {
constructor() {
super();
this.state = {
ruleTypes: []
};
}
componentDidMount() {
axios.get('/rule-types').then((response) => {
this.setState({ruleTypes: response.data.map((ruleType) => {
return { typeName: ruleType }
})});
});
}
render() {
return (
<Select options={this.state.ruleTypes}
value={this.props.value}
onChange={this.props.onChange}
labelKey="typeName"
valueKey="typeName" />
);
}
}
| kfirprods/tpp | client/src/components/atomic/RuleTypeSelector.js | JavaScript | gpl-3.0 | 776 |
var assert = require('assert');
var expect = require('chai').expect;
var rds = require('./rdsEncryptionEnabled');
const listKeys = [
{
KeyId: '60c4f21b-e271-4e97-86ae-6403618a9467',
KeyArn: 'arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467'
}
];
const describeKey = [
{
"KeyMetadata": {
"AWSAccountId": "112233445566",
"KeyId": "60c4f21b-e271-4e97-86ae-6403618a9467",
"Arn": "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467",
"CreationDate": "2020-03-25T14:05:09.299Z",
"Enabled": true,
"Description": "Used for S3 encryption",
"KeyUsage": "ENCRYPT_DECRYPT",
"KeyState": "Enabled",
"Origin": "AWS_KMS",
"KeyManager": "CUSTOMER",
"CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
"EncryptionAlgorithms": [
"SYMMETRIC_DEFAULT"
]
}
}
];
const createCache = (rdsData, kmsData, listKeys, describeKey) => {
var keyId = (listKeys && listKeys.length) ? listKeys[0].KeyId : null;
return {
rds: {
describeDBInstances: {
'us-east-1': {
err: null,
data: rdsData
}
}
},
kms: {
listAliases: {
'us-east-1': {
err: null,
data: kmsData
}
},
listKeys: {
'us-east-1': {
data: listKeys
}
},
describeKey: {
'us-east-1': {
[keyId]: {
data: describeKey
}
}
}
}
}
};
describe('rdsEncryptionEnabled', function () {
describe('run', function () {
it('should give passing result if no RDS instances are found', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(0)
expect(results[0].message).to.include('No RDS instances found')
done()
};
const cache = createCache(
[], []
);
rds.run(cache, {}, callback);
})
it('should give passing result if encrypted RDS instance is found', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(0)
expect(results[0].message).to.include('Encryption at rest is enabled via KMS key')
done()
};
const cache = createCache(
[
{
Engine: 'mysql',
StorageEncrypted: true,
KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467",
}
],
[],
listKeys,
describeKey[0]
);
rds.run(cache, {}, callback);
})
it('should give failing result if non-encrypted RDS instance is found', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(2)
expect(results[0].message).to.include('Encryption at rest is not enabled')
done()
};
const cache = createCache(
[
{
Engine: 'mysql',
StorageEncrypted: false
}
],
[]
);
rds.run(cache, {}, callback);
})
it('should give failing result if encrypted RDS instance is found with no KMS aliases', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(2)
expect(results[0].message).to.include('RDS KMS alias setting is configured but there are no KMS aliases')
done()
};
const cache = createCache(
[
{
Engine: 'mysql',
StorageEncrypted: true,
KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/abcdef10-1517-49d8-b085-77c50b904149",
}
],
[],
listKeys,
describeKey[0]
);
rds.run(cache, {
rds_encryption_kms_alias: 'alias/example1'
}, callback);
})
it('should give failing result if encrypted RDS instance is found with wrong KMS aliases', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(2)
expect(results[0].message).to.include('Encryption at rest is enabled, but is not using expected KMS key')
done()
};
const cache = createCache(
[
{
Engine: 'mysql',
StorageEncrypted: true,
KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467",
}
],
[
{
AliasArn: "arn:aws:kms:us-east-1:112233445566:alias/example1",
AliasName: "alias/example1",
TargetKeyId: "def1234a-62d0-46c5-a7c0-5f3a3d2f8046"
}
],
listKeys,
describeKey[0]
);
rds.run(cache, {
rds_encryption_kms_alias: 'alias/example1'
}, callback);
})
it('should give passing result if encrypted RDS instance is found with correct KMS aliases', function (done) {
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(0)
expect(results[0].message).to.include('Encryption at rest is enabled via expected KMS key')
done()
};
const cache = createCache(
[
{
Engine: 'mysql',
StorageEncrypted: true,
KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467",
}
],
[
{
AliasArn: "arn:aws:kms:us-east-1:112233445566:alias/example1",
AliasName: "alias/example1",
TargetKeyId: "60c4f21b-e271-4e97-86ae-6403618a9467"
}
],
listKeys,
describeKey[0]
);
rds.run(cache, {
rds_encryption_kms_alias: 'alias/example1'
}, callback);
})
})
}) | cloudsploit/scans | plugins/aws/rds/rdsEncryptionEnabled.spec.js | JavaScript | gpl-3.0 | 7,430 |