repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
matteosecli/QMC
|
src/Potential.h
|
1316
|
#ifndef POTENTIAL_H
#define POTENTIAL_H
using namespace arma;
namespace QMC2
{
struct GeneralParams;
class Potential {
protected:
int n_p;
int dim;
std::string name;
public:
Potential ( int number_particles , int dimension, std::string name = "Potential" );
Potential();
// Pure virtual function
virtual double get_pot_E ( const mat& r ) const = 0;
std::string get_name(){return name;}
};
// Harmonic oscillator potential
class Harmonic_osc : public Potential {
protected:
double w;
public:
Harmonic_osc (GeneralParams &) ; // Here, 'frequency' is the 'omega'
double get_pot_E (const mat &r ) const ;
};
// Coulomb potential in an atom
class Coulomb : public Potential {
protected :
int Z;
public :
Coulomb (GeneralParams &) ; // Remember that charge is in natural units: e=1
double get_pot_E ( const mat& r ) const ;
};
// Repulsion potential between electrons
class eRepulsion : public Potential {
public :
eRepulsion (GeneralParams &) ;
double get_pot_E ( const mat& r ) const ;
};
}
#endif //POTENTIAL_H
|
gpl-3.0
|
kernsuite-debian/lofar
|
RTCP/Cobalt/GPUProc/src/Kernels/BeamFormerKernel.h
|
2911
|
//# BeamFormerKernel.h
//# Copyright (C) 2012-2013 ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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 LOFAR software suite is distributed in the hope that it will be useful,
//# but WITHOUT ANY WARRANTY; without even the implied warranty of
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//# GNU General Public License for more details.
//#
//# You should have received a copy of the GNU General Public License along
//# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
#ifndef LOFAR_GPUPROC_CUDA_BEAM_FORMER_KERNEL_H
#define LOFAR_GPUPROC_CUDA_BEAM_FORMER_KERNEL_H
#include <CoInterface/Parset.h>
#include <GPUProc/Kernels/Kernel.h>
#include <GPUProc/KernelFactory.h>
#include <GPUProc/gpu_wrapper.h>
#include <string>
#include <vector>
namespace LOFAR
{
namespace Cobalt
{
class BeamFormerKernel : public CompiledKernel
{
public:
static std::string theirSourceFile;
static std::string theirFunction;
enum BufferType
{
INPUT_DATA,
OUTPUT_DATA,
DELAY_INDICES,
BEAM_FORMER_DELAYS
};
// Parameters that must be passed to the constructor of the
// BeamFormerKernel class.
struct Parameters : Kernel::Parameters
{
Parameters(const Parset& ps);
// The beam-former delays are indexed by their station number
// in the observation, so we need to map them to beam-former
// station numbers.
std::vector<unsigned> delayIndices;
// Width of th observation's delay array, in stations
unsigned nrDelays;
unsigned nrChannels;
unsigned nrSamplesPerChannel;
unsigned nrSAPs;
unsigned nrTABs;
double subbandBandwidth;
bool doFlysEye;
size_t bufferSize(BufferType bufferType) const;
size_t nrStations() const { return delayIndices.size(); }
};
BeamFormerKernel(const gpu::Stream &stream,
const gpu::Module &module,
const Buffers &buffers,
const Parameters ¶m);
void enqueue(const BlockID &blockId,
double subbandFrequency, unsigned SAP);
gpu::DeviceMemory delayIndices;
gpu::DeviceMemory beamFormerDelays;
};
//# -------- Template specializations for KernelFactory -------- #//
template<> CompileDefinitions
KernelFactory<BeamFormerKernel>::compileDefinitions() const;
}
}
#endif
|
gpl-3.0
|
skurski/know-how
|
src/main/java/know/how/designpatterns/abstractfactory/AbstractAddress.java
|
354
|
package know.how.designpatterns.abstractfactory;
public abstract class AbstractAddress {
private String street;
public AbstractAddress(String street){
this.street = street;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public abstract String fullAddress();
}
|
gpl-3.0
|
dongweiming/web_develop
|
chapter13/section5/use_yield.py
|
462
|
# coding=utf-8
import random
def consumer():
r = None
while 1:
data = yield r
print 'Consuming: {}'.format(data)
r = data + 1
def producer(consumer):
n = 3
consumer.send(None)
while n:
data = random.choice(range(10))
print('Producing: {}'.format(data))
rs = consumer.send(data)
print 'Consumer return: {}'.format(rs)
n -= 1
consumer.close()
c = consumer()
producer(c)
|
gpl-3.0
|
msocha/BRMS
|
brms/brms-web/src/main/java/eu/ocomp/brms/web/utils/AbstractScr.java
|
1084
|
package eu.ocomp.brms.web.utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.primefaces.context.RequestContext;
public abstract class AbstractScr implements Serializable {
private static final long serialVersionUID = 1L;
public AbstractScr() {
// TODO Auto-generated constructor stub
}
public void openDialog(String dialog, String recordId, Boolean recordUpdate) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("modal", true);
options.put("draggable", true);
options.put("resizable", false);
options.put("closable", true);
Map<String, List<String>> params = new HashMap<String, List<String>>();
List<String> id = new ArrayList<String>();
id.add(recordId.toString());
params.put("id", id);
List<String> update = new ArrayList<String>();
update.add(recordUpdate.toString());
params.put("update", update);
RequestContext.getCurrentInstance().openDialog(dialog, options, params);
}
}
|
gpl-3.0
|
drazisil/cpanel-ddns
|
docs/cpanel-ddns/_functions.php.html
|
4939
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page functions.php</title>
<link rel="stylesheet" href="../media/stylesheet.css" />
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>
</head>
<body>
<div class="page-body">
<h2 class="file-name">/functions.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
<span class="disabled">Description</span> |
<a href="#sec-functions">Functions</a>
</div>
<div class="info-box-body">
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">cpanel-ddns</p>
<ul class="tags">
<li><span class="field">author:</span> Joseph W. Becher <<a href="mailto:jwbecher@gmail.com">jwbecher@gmail.com</a>></li>
</ul>
</div>
</div>
<a name="sec-functions"></a>
<div class="info-box">
<div class="info-box-title">Functions</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<span class="disabled">Functions</span>
</div>
<div class="info-box-body">
<a name="functioncpanel_ddns_CheckClientACL" id="functioncpanel_ddns_CheckClientACL"><!-- --></a>
<div class="evenrow">
<div>
<span class="method-title">cpanel_ddns_CheckClientACL</span> (line <span class="line-number">16</span>)
</div>
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Checks an IP against an ACL</p>
<div class="method-signature">
<span class="method-result">boolean</span>
<span class="method-name">
cpanel_ddns_CheckClientACL
</span>
(<span class="var-type">string</span> <span class="var-name">$ip</span>)
</div>
<ul class="parameters">
<li>
<span class="var-type">string</span>
<span class="var-name">$ip</span> </li>
</ul>
</div>
<a name="functioncpanel_ddns_FetchDNSZoneFile" id="functioncpanel_ddns_FetchDNSZoneFile"><!-- --></a>
<div class="oddrow">
<div>
<span class="method-title">cpanel_ddns_FetchDNSZoneFile</span> (line <span class="line-number">33</span>)
</div>
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Uses CURL to query the XML API of cpanel for the DNS zone records</p>
<div class="method-signature">
<span class="method-result">xml</span>
<span class="method-name">
cpanel_ddns_FetchDNSZoneFile
</span>
()
</div>
</div>
<a name="functioncpanel_ddns_FetchRecordFromXMLByNumber" id="functioncpanel_ddns_FetchRecordFromXMLByNumber"><!-- --></a>
<div class="evenrow">
<div>
<span class="method-title">cpanel_ddns_FetchRecordFromXMLByNumber</span> (line <span class="line-number">105</span>)
</div>
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Retrieves a single DNS record from the zone file XML</p>
<div class="method-signature">
<span class="method-result">array</span>
<span class="method-name">
cpanel_ddns_FetchRecordFromXMLByNumber
</span>
(<span class="var-type">xml</span> <span class="var-name">$zoneXML</span>, <span class="var-type">int</span> <span class="var-name">$recordNumber</span>)
</div>
<ul class="parameters">
<li>
<span class="var-type">xml</span>
<span class="var-name">$zoneXML</span> </li>
<li>
<span class="var-type">int</span>
<span class="var-name">$recordNumber</span> </li>
</ul>
</div>
<a name="functioncpanel_ddns_SearchForHostInZoneFile" id="functioncpanel_ddns_SearchForHostInZoneFile"><!-- --></a>
<div class="oddrow">
<div>
<span class="method-title">cpanel_ddns_SearchForHostInZoneFile</span> (line <span class="line-number">60</span>)
</div>
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Search for a hoset in the DNS Zone file and return the details in an array</p>
<div class="method-signature">
<span class="method-result">array</span>
<span class="method-name">
cpanel_ddns_SearchForHostInZoneFile
</span>
(<span class="var-type">xml</span> <span class="var-name">$zoneXML</span>, <span class="var-type">string</span> <span class="var-name">$host</span>)
</div>
<ul class="parameters">
<li>
<span class="var-type">xml</span>
<span class="var-name">$zoneXML</span> </li>
<li>
<span class="var-type">string</span>
<span class="var-name">$host</span> </li>
</ul>
</div>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Wed, 22 Aug 2012 21:10:53 -0400 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.4</a>
</p>
</div></body>
</html>
|
gpl-3.0
|
anoidgit/padavan
|
trunk/user/openvpn/openvpn-2.4.x/src/openvpn/packet_id.c
|
18724
|
/*
* OpenVPN -- An application to securely tunnel IP networks
* over a single TCP/UDP port, with support for SSL/TLS-based
* session authentication and key exchange,
* packet encryption, packet authentication, and
* packet compression.
*
* Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* These routines are designed to catch replay attacks,
* where a man-in-the-middle captures packets and then
* attempts to replay them back later.
*
* We use the "sliding-window" algorithm, similar
* to IPSec.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_MSC_VER)
#include "config-msvc.h"
#endif
#include "syshead.h"
#ifdef ENABLE_CRYPTO
#include "packet_id.h"
#include "misc.h"
#include "integer.h"
#include "memdbg.h"
/* #define PID_SIMULATE_BACKTRACK */
/*
* Special time_t value that indicates that
* sequence number has expired.
*/
#define SEQ_UNSEEN ((time_t)0)
#define SEQ_EXPIRED ((time_t)1)
static void packet_id_debug_print(int msglevel,
const struct packet_id_rec *p,
const struct packet_id_net *pin,
const char *message,
int value);
static inline void
packet_id_debug(int msglevel,
const struct packet_id_rec *p,
const struct packet_id_net *pin,
const char *message,
int value)
{
#ifdef ENABLE_DEBUG
if (unlikely(check_debug_level(msglevel)))
{
packet_id_debug_print(msglevel, p, pin, message, value);
}
#endif
}
void
packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
{
dmsg(D_PID_DEBUG, "PID packet_id_init seq_backtrack=%d time_backtrack=%d",
seq_backtrack,
time_backtrack);
ASSERT(p);
CLEAR(*p);
p->rec.name = name;
p->rec.unit = unit;
if (seq_backtrack)
{
ASSERT(MIN_SEQ_BACKTRACK <= seq_backtrack && seq_backtrack <= MAX_SEQ_BACKTRACK);
ASSERT(MIN_TIME_BACKTRACK <= time_backtrack && time_backtrack <= MAX_TIME_BACKTRACK);
CIRC_LIST_ALLOC(p->rec.seq_list, struct seq_list, seq_backtrack);
p->rec.seq_backtrack = seq_backtrack;
p->rec.time_backtrack = time_backtrack;
}
p->rec.initialized = true;
}
void
packet_id_free(struct packet_id *p)
{
if (p)
{
dmsg(D_PID_DEBUG, "PID packet_id_free");
if (p->rec.seq_list)
{
free(p->rec.seq_list);
}
CLEAR(*p);
}
}
void
packet_id_add(struct packet_id_rec *p, const struct packet_id_net *pin)
{
const time_t local_now = now;
if (p->seq_list)
{
packet_id_type diff;
/*
* If time value increases, start a new
* sequence number sequence.
*/
if (!CIRC_LIST_SIZE(p->seq_list)
|| pin->time > p->time
|| (pin->id >= (packet_id_type)p->seq_backtrack
&& pin->id - (packet_id_type)p->seq_backtrack > p->id))
{
p->time = pin->time;
p->id = 0;
if (pin->id > (packet_id_type)p->seq_backtrack)
{
p->id = pin->id - (packet_id_type)p->seq_backtrack;
}
CIRC_LIST_RESET(p->seq_list);
}
while (p->id < pin->id
#ifdef PID_SIMULATE_BACKTRACK
|| (get_random() % 64) < 31
#endif
)
{
CIRC_LIST_PUSH(p->seq_list, SEQ_UNSEEN);
++p->id;
}
diff = p->id - pin->id;
if (diff < (packet_id_type) CIRC_LIST_SIZE(p->seq_list)
&& local_now > SEQ_EXPIRED)
{
CIRC_LIST_ITEM(p->seq_list, diff) = local_now;
}
}
else
{
p->time = pin->time;
p->id = pin->id;
}
}
/*
* Expire sequence numbers which can no longer
* be accepted because they would violate
* time_backtrack.
*/
void
packet_id_reap(struct packet_id_rec *p)
{
const time_t local_now = now;
if (p->time_backtrack)
{
int i;
bool expire = false;
for (i = 0; i < CIRC_LIST_SIZE(p->seq_list); ++i)
{
const time_t t = CIRC_LIST_ITEM(p->seq_list, i);
if (t == SEQ_EXPIRED)
{
break;
}
if (!expire && t && t + p->time_backtrack < local_now)
{
expire = true;
}
if (expire)
{
CIRC_LIST_ITEM(p->seq_list, i) = SEQ_EXPIRED;
}
}
}
p->last_reap = local_now;
}
/*
* Return true if packet id is ok, or false if
* it is a replay.
*/
bool
packet_id_test(struct packet_id_rec *p,
const struct packet_id_net *pin)
{
packet_id_type diff;
packet_id_debug(D_PID_DEBUG, p, pin, "PID_TEST", 0);
ASSERT(p->initialized);
if (!pin->id)
{
return false;
}
if (p->seq_backtrack)
{
/*
* In backtrack mode, we allow packet reordering subject
* to the seq_backtrack and time_backtrack constraints.
*
* This mode is used with UDP.
*/
if (pin->time == p->time)
{
/* is packet-id greater than any one we've seen yet? */
if (pin->id > p->id)
{
return true;
}
/* check packet-id sliding window for original/replay status */
diff = p->id - pin->id;
/* keep track of maximum backtrack seen for debugging purposes */
if ((int)diff > p->max_backtrack_stat)
{
p->max_backtrack_stat = (int)diff;
packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR replay-window backtrack occurred", p->max_backtrack_stat);
}
if (diff >= (packet_id_type) CIRC_LIST_SIZE(p->seq_list))
{
packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR large diff", diff);
return false;
}
{
const time_t v = CIRC_LIST_ITEM(p->seq_list, diff);
if (v == 0)
{
return true;
}
else
{
/* raised from D_PID_DEBUG_LOW to reduce verbosity */
packet_id_debug(D_PID_DEBUG_MEDIUM, p, pin, "PID_ERR replay", diff);
return false;
}
}
}
else if (pin->time < p->time) /* if time goes back, reject */
{
packet_id_debug(D_PID_DEBUG_LOW, p, pin, "PID_ERR time backtrack", 0);
return false;
}
else /* time moved forward */
{
return true;
}
}
else
{
/*
* In non-backtrack mode, all sequence number series must
* begin at some number n > 0 and must increment linearly without gaps.
*
* This mode is used with TCP.
*/
if (pin->time == p->time)
{
return !p->id || pin->id == p->id + 1;
}
else if (pin->time < p->time) /* if time goes back, reject */
{
return false;
}
else /* time moved forward */
{
return pin->id == 1;
}
}
}
/*
* Read/write a packet ID to/from the buffer. Short form is sequence number
* only. Long form is sequence number and timestamp.
*/
bool
packet_id_read(struct packet_id_net *pin, struct buffer *buf, bool long_form)
{
packet_id_type net_id;
net_time_t net_time;
pin->id = 0;
pin->time = 0;
if (!buf_read(buf, &net_id, sizeof(net_id)))
{
return false;
}
pin->id = ntohpid(net_id);
if (long_form)
{
if (!buf_read(buf, &net_time, sizeof(net_time)))
{
return false;
}
pin->time = ntohtime(net_time);
}
return true;
}
static bool
packet_id_send_update(struct packet_id_send *p, bool long_form)
{
if (!p->time)
{
p->time = now;
}
if (p->id == PACKET_ID_MAX)
{
/* Packet ID only allowed to roll over if using long form and time has
* moved forward since last roll over.
*/
if (!long_form || now <= p->time)
{
return false;
}
p->time = now;
p->id = 0;
}
p->id++;
return true;
}
bool
packet_id_write(struct packet_id_send *p, struct buffer *buf, bool long_form,
bool prepend)
{
if (!packet_id_send_update(p, long_form))
{
return false;
}
const packet_id_type net_id = htonpid(p->id);
const net_time_t net_time = htontime(p->time);
if (prepend)
{
if (long_form)
{
if (!buf_write_prepend(buf, &net_time, sizeof(net_time)))
{
return false;
}
}
if (!buf_write_prepend(buf, &net_id, sizeof(net_id)))
{
return false;
}
}
else
{
if (!buf_write(buf, &net_id, sizeof(net_id)))
{
return false;
}
if (long_form)
{
if (!buf_write(buf, &net_time, sizeof(net_time)))
{
return false;
}
}
}
return true;
}
const char *
packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp, struct gc_arena *gc)
{
struct buffer out = alloc_buf_gc(256, gc);
buf_printf(&out, "[ #" packet_id_format, (packet_id_print_type)pin->id);
if (print_timestamp && pin->time)
{
buf_printf(&out, " / time = (" packet_id_format ") %s",
(packet_id_print_type)pin->time,
time_string(pin->time, 0, false, gc));
}
buf_printf(&out, " ]");
return BSTR(&out);
}
/* initialize the packet_id_persist structure in a disabled state */
void
packet_id_persist_init(struct packet_id_persist *p)
{
p->filename = NULL;
p->fd = -1;
p->time = p->time_last_written = 0;
p->id = p->id_last_written = 0;
}
/* close the file descriptor if it is open, and switch to disabled state */
void
packet_id_persist_close(struct packet_id_persist *p)
{
if (packet_id_persist_enabled(p))
{
if (close(p->fd))
{
msg(D_PID_PERSIST | M_ERRNO, "Close error on --replay-persist file %s", p->filename);
}
packet_id_persist_init(p);
}
}
/* load persisted rec packet_id (time and id) only once from file, and set state to enabled */
void
packet_id_persist_load(struct packet_id_persist *p, const char *filename)
{
struct gc_arena gc = gc_new();
if (!packet_id_persist_enabled(p))
{
/* open packet-id persist file for both read and write */
p->fd = platform_open(filename,
O_CREAT | O_RDWR | O_BINARY,
S_IRUSR | S_IWUSR);
if (p->fd == -1)
{
msg(D_PID_PERSIST | M_ERRNO,
"Cannot open --replay-persist file %s for read/write",
filename);
}
else
{
struct packet_id_persist_file_image image;
ssize_t n;
#if defined(HAVE_FLOCK) && defined(LOCK_EX) && defined(LOCK_NB)
if (flock(p->fd, LOCK_EX | LOCK_NB))
{
msg(M_ERR, "Cannot obtain exclusive lock on --replay-persist file %s", filename);
}
#endif
p->filename = filename;
n = read(p->fd, &image, sizeof(image));
if (n == sizeof(image))
{
p->time = p->time_last_written = image.time;
p->id = p->id_last_written = image.id;
dmsg(D_PID_PERSIST_DEBUG, "PID Persist Read from %s: %s",
p->filename, packet_id_persist_print(p, &gc));
}
else if (n == -1)
{
msg(D_PID_PERSIST | M_ERRNO,
"Read error on --replay-persist file %s",
p->filename);
}
}
}
gc_free(&gc);
}
/* save persisted rec packet_id (time and id) to file (only if enabled state) */
void
packet_id_persist_save(struct packet_id_persist *p)
{
if (packet_id_persist_enabled(p) && p->time && (p->time != p->time_last_written
|| p->id != p->id_last_written))
{
struct packet_id_persist_file_image image;
ssize_t n;
off_t seek_ret;
struct gc_arena gc = gc_new();
image.time = p->time;
image.id = p->id;
seek_ret = lseek(p->fd, (off_t)0, SEEK_SET);
if (seek_ret == (off_t)0)
{
n = write(p->fd, &image, sizeof(image));
if (n == sizeof(image))
{
p->time_last_written = p->time;
p->id_last_written = p->id;
dmsg(D_PID_PERSIST_DEBUG, "PID Persist Write to %s: %s",
p->filename, packet_id_persist_print(p, &gc));
}
else
{
msg(D_PID_PERSIST | M_ERRNO,
"Cannot write to --replay-persist file %s",
p->filename);
}
}
else
{
msg(D_PID_PERSIST | M_ERRNO,
"Cannot seek to beginning of --replay-persist file %s",
p->filename);
}
gc_free(&gc);
}
}
/* transfer packet_id_persist -> packet_id */
void
packet_id_persist_load_obj(const struct packet_id_persist *p, struct packet_id *pid)
{
if (p && pid && packet_id_persist_enabled(p) && p->time)
{
pid->rec.time = p->time;
pid->rec.id = p->id;
}
}
const char *
packet_id_persist_print(const struct packet_id_persist *p, struct gc_arena *gc)
{
struct buffer out = alloc_buf_gc(256, gc);
buf_printf(&out, "[");
if (packet_id_persist_enabled(p))
{
buf_printf(&out, " #" packet_id_format, (packet_id_print_type)p->id);
if (p->time)
{
buf_printf(&out, " / time = (" packet_id_format ") %s",
(packet_id_print_type)p->time,
time_string(p->time, 0, false, gc));
}
}
buf_printf(&out, " ]");
return (char *)out.data;
}
#ifdef ENABLE_DEBUG
static void
packet_id_debug_print(int msglevel,
const struct packet_id_rec *p,
const struct packet_id_net *pin,
const char *message,
int value)
{
struct gc_arena gc = gc_new();
struct buffer out = alloc_buf_gc(256, &gc);
struct timeval tv;
const time_t prev_now = now;
const struct seq_list *sl = p->seq_list;
int i;
CLEAR(tv);
gettimeofday(&tv, NULL);
buf_printf(&out, "%s [%d]", message, value);
buf_printf(&out, " [%s-%d] [", p->name, p->unit);
for (i = 0; sl != NULL && i < sl->x_size; ++i)
{
char c;
time_t v;
int diff;
v = CIRC_LIST_ITEM(sl, i);
if (v == SEQ_UNSEEN)
{
c = '_';
}
else if (v == SEQ_EXPIRED)
{
c = 'E';
}
else
{
diff = (int) prev_now - v;
if (diff < 0)
{
c = 'N';
}
else if (diff < 10)
{
c = '0' + diff;
}
else
{
c = '>';
}
}
buf_printf(&out, "%c", c);
}
buf_printf(&out, "] " time_format ":" packet_id_format, (time_type)p->time, (packet_id_print_type)p->id);
if (pin)
{
buf_printf(&out, " " time_format ":" packet_id_format, (time_type)pin->time, (packet_id_print_type)pin->id);
}
buf_printf(&out, " t=" time_format "[%d]",
(time_type)prev_now,
(int)(prev_now - tv.tv_sec));
buf_printf(&out, " r=[%d,%d,%d,%d,%d]",
(int)(p->last_reap - tv.tv_sec),
p->seq_backtrack,
p->time_backtrack,
p->max_backtrack_stat,
(int)p->initialized);
if (sl != NULL)
{
buf_printf(&out, " sl=[%d,%d,%d,%d]",
sl->x_head,
sl->x_size,
sl->x_cap,
sl->x_sizeof);
}
msg(msglevel, "%s", BSTR(&out));
gc_free(&gc);
}
#endif /* ifdef ENABLE_DEBUG */
#ifdef PID_TEST
void
packet_id_interactive_test(void)
{
struct packet_id pid;
struct packet_id_net pin;
bool long_form;
bool count = 0;
bool test;
const int seq_backtrack = 10;
const int time_backtrack = 10;
packet_id_init(&pid, seq_backtrack, time_backtrack);
while (true)
{
char buf[80];
if (!fgets(buf, sizeof(buf), stdin))
{
break;
}
update_time();
if (sscanf(buf, "%lu,%u", &pin.time, &pin.id) == 2)
{
packet_id_reap_test(&pid.rec);
test = packet_id_test(&pid.rec, &pin);
printf("packet_id_test (" time_format ", " packet_id_format ") returned %d\n",
(time_type)pin.time,
(packet_id_print_type)pin.id,
test);
if (test)
{
packet_id_add(&pid.rec, &pin);
}
}
else
{
long_form = (count < 20);
packet_id_alloc_outgoing(&pid.send, &pin, long_form);
printf("(" time_format "(" packet_id_format "), %d)\n",
(time_type)pin.time,
(packet_id_print_type)pin.id,
long_form);
if (pid.send.id == 10)
{
pid.send.id = 0xFFFFFFF8;
}
++count;
}
}
packet_id_free(&pid);
}
#endif /* ifdef PID_TEST */
#endif /* ENABLE_CRYPTO */
|
gpl-3.0
|
duenti/PFstats
|
Pfstats/pdbatom.cpp
|
10564
|
#include "pdbatom.h"
PdbAtom::PdbAtom(bool win)
{
windows = win;
}
PdbAtom::PdbAtom(string line, bool win){
windows = win;
char c = ' ';
string temp = "";
//Atom Number
for(int i = 6; i <= 10; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->atomNumber = stoi(temp);
//Atom Name
temp = "";
for(int i = 12; i <= 15; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->atomName = temp;
//Alternate Location Indicator
this->alternateLocation = line[16];
//Residue
//temp = line[17] + line[18] + line[19];
temp = line.substr(17,3);
this->residue = temp;
this->residueCode = aa3lto1l(temp);
//Chain
this->chain = line[21];
//Residue Number
temp = "";
for(int i = 22; i <= 25; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->residueNumber = stoi(temp);
//Code for insertion of residues
this->insertionResiduesCode = line[26];
//Position X
temp = "";
for(int i = 30; i <= 37; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->x = atof(temp.c_str());
//Position Y
temp = "";
for(int i = 38; i <= 45; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->y = atof(temp.c_str());
//Position Z
temp = "";
for(int i = 46; i <= 53; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->z = atof(temp.c_str());
//Occupancy
temp = "";
for(int i = 54; i <= 59; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->occ = atof(temp.c_str());
//B-factor
temp = "";
for(int i = 60; i <= 65; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->bfactor = atof(temp.c_str());
//Segment Identifier
temp = "";
for(int i = 72; i <= 75; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->segmentIdentifier = temp;
//Element
temp = "";
for(int i = 76; i <= 77; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->element = temp;
//Charge
temp = "";
for(int i = 78; i <= 79; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->charge = temp;
//this->seqnumber = 0;
//printf("%d %s %c %s %c %d %c %f %f %f %f %f %s %s %s\n",atomNumber,atomName.c_str(),alternateLocation,residue.c_str(),chain,residueNumber,insertionResiduesCode,x,y,z,occ,bfactor,segmentIdentifier.c_str(),element.c_str(),charge.c_str());
}
PdbAtom::PdbAtom(int atomNb, string atomNm, string residue, char chain, int resNum, float x, float y, float z, float occ, float b, string element, string charge, bool win){
windows = win;
this->atomNumber = atomNb;
this->atomName = atomNm;
this->residue = residue;
this->chain = chain;
this->residueNumber = resNum;
this->x = x;
this->y = y;
this->z = z;
this->occ = occ;
this->bfactor = b;
this->element = element;
this->charge = charge;
}
PdbAtom::~PdbAtom()
{
}
char PdbAtom::aa3lto1l(string res){
if(res == "ARG") return 'R';
else if(res == "HIS") return 'H';
else if(res == "LYS") return 'K';
else if(res == "ASP") return 'D';
else if(res == "GLU") return 'E';
else if(res == "SER") return 'S';
else if(res == "THR") return 'T';
else if(res == "ASN") return 'N';
else if(res == "GLN") return 'Q';
else if(res == "CYS") return 'C';
else if(res == "SEC") return 'U';
else if(res == "GLY") return 'G';
else if(res == "PRO") return 'P';
else if(res == "ALA") return 'A';
else if(res == "VAL") return 'V';
else if(res == "ILE") return 'I';
else if(res == "LEU") return 'L';
else if(res == "MET") return 'M';
else if(res == "PHE") return 'F';
else if(res == "TYR") return 'Y';
else if(res == "TRP") return 'W';
}
int PdbAtom::getAtomNumber(){
return this->atomNumber;
}
void PdbAtom::setAtomNumber(int n){
this->atomNumber = n;
}
string PdbAtom::getAtomName(){
return this->atomName;
}
void PdbAtom::setAtomName(string name){
this->atomName = name;
}
string PdbAtom::getResidue(){
return this->residue;
}
void PdbAtom::setResidue(string aa){
this->residue = aa;
}
char PdbAtom::getChain(){
return this->chain;
}
void PdbAtom::setChain(char c){
this->chain = c;
}
int PdbAtom::getResidueNumber(){
return this->residueNumber;
}
void PdbAtom::setResidueNumber(int n){
this->residueNumber = n;
}
float PdbAtom::getX(){
return this->x;
}
void PdbAtom::setX(float x){
this->x = x;
}
float PdbAtom::getY(){
return this->y;
}
void PdbAtom::setY(float y){
this->y = y;
}
float PdbAtom::getZ(){
return this->z;
}
void PdbAtom::setZ(float z){
this->z = z;
}
float PdbAtom::getOcc(){
return this->occ;
}
void PdbAtom::setOcc(float occ){
this->occ = occ;
}
float PdbAtom::getBfactor(){
return this->bfactor;
}
void PdbAtom::setBfactor(float bf){
this->bfactor = bf;
}
string PdbAtom::getElement(){
return this->element;
}
void PdbAtom::setElement(string ele){
this->element = ele;
}
string PdbAtom::getCharge(){
return this->charge;
}
void PdbAtom::setCharge(string c){
this->charge = c;
}
char PdbAtom::getResidueCode(){
return this->residueCode;
}
void PdbAtom::setResidueCode(char r){
this->residueCode = r;
}
string PdbAtom::to_string(float bf){
string line = "ATOM ";
string temp;
//ATOM NUMBER
temp = std::to_string(this->atomNumber);
switch(temp.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + temp;
break;
}
case 2:
{
line += " " + temp;
break;
}
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += temp;
break;
}
}
line += " ";
//ATOM NAME
switch(this->atomName.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += this->atomName + " ";
break;
}
case 2:
{
line += this->atomName + " ";
break;
}
case 3:
{
line += this->atomName + " ";
break;
}
case 4:
{
line += this->atomName;
break;
}
}
//ALTERNATE LOCATION INDICATOR
line += this->alternateLocation;
//RESIDUE NAME
line += this->residue;
line += " ";
//CHAIN
line += this->chain;
//RESIDUE SEQUENCE NUMBER
temp = std::to_string(this->residueNumber);
switch(temp.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + temp;
break;
}
case 2:
{
line += " " + temp;
break;
}
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += temp;
break;
}
}
//CODE FOR INSERTION OF RESIDUES
line += this->insertionResiduesCode;
line += " ";
//X
stringstream stream;
stream << fixed << setprecision(3) << this->x;
temp = stream.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//Y
stringstream stream2;
stream2 << fixed << setprecision(3) << this->y;
temp = stream2.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//Z
stringstream stream3;
stream3 << fixed << setprecision(3) << this->z;
temp = stream3.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//OCCUPANCY
stringstream stream4;
stream4 << fixed << setprecision(2) << this->occ;
temp = stream4.str();
switch(temp.size()){
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += temp;
break;
}
}
//B-FACTOR (SUBSTITUTE)
stringstream stream5;
stream5 << fixed << setprecision(1) << bf;
temp = stream5.str();
switch(temp.size()){
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += temp;
break;
}
}
line += " ";
//SEGMENT IDENTIFIER
switch(this->segmentIdentifier.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += this->segmentIdentifier + " ";
break;
}
case 2:
{
line += this->segmentIdentifier + " ";
break;
}
case 3:
{
line += this->segmentIdentifier + " ";
break;
}
case 4:
{
line += this->segmentIdentifier;
break;
}
}
//ELEMENT SYMBOL
switch(this->element.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + this->element;
break;
}
case 2:
{
line += this->element;
break;
}
}
//CHARGE OF ELEMENT
switch(this->charge.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + this->charge;
break;
}
case 2:
{
line += this->charge;
break;
}
}
return line;
}
|
gpl-3.0
|
cundd/Dive
|
CunddDiveMasterQCPatchController.h
|
2282
|
//
// CunddDiveMasterQCPatchController.h
//
// Created by Daniel Corn on 11.05.10.
//
// Copyright © 2010-2012 Corn Daniel
//
// This file is part of Dive.
//
// Dive is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Foobar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Foobar. If not, see <http://www.gnu.org/licenses/>.
//
//
#import <Cocoa/Cocoa.h>
#import "CunddDiveQCPatchController.h"
#import "CunddDiveMasterSettings.h"
#import "CunddDiveVideoChainCollectionController.h"
#import "CunddDiveMasterQCView.h"
@interface CunddDiveMasterQCPatchController : CunddDiveQCPatchController {
IBOutlet CunddDiveMasterSettings * patch;
IBOutlet NSView * targetView;
CunddDiveVideoChainCollectionController * vcCollectionController;
NSMutableArray * _videoChains;
NSMutableArray * _outputVideoChainStreams;
IBOutlet NSTextField * text;
IBOutlet NSImageView * outputView;
/*
// Data per VC
NSImage * image;
NSNumber * screen;
NSNumber * width;
NSNumber * height;
NSNumber * x;
NSNumber * y;
NSNumber * alpha;
NSNumber * mode;
// */
}
/*!
@method
@abstract Finish the init script when the VideoChains are ready
@discussion Finish the init script when the VideoChains are ready
*/
-(void)finishInitialisationAndSetVcCollectionController:(CunddDiveVideoChainCollectionController *)theCollectionController;
/*!
@method
@abstract Add observers to the given VC
@discussion Add observers to the given VC
*/
-(void)registerVideoChain:(CunddDiveVideoChain *)aVc;
@property (retain) CunddDiveMasterSettings * patch;
@property (retain) CunddDiveVideoChainCollectionController * vcCollectionController;
@property (retain) NSTextField * text;
@property (retain) NSImageView * outputView;
@property (retain) NSView * targetView;
@end
|
gpl-3.0
|
maths/moodle-qtype_stack
|
adminui/caschat.php
|
5572
|
<?php
// This file is part of Stack - http://stack.maths.ed.ac.uk/
//
// Stack 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.
//
// Stack 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 Stack. If not, see <http://www.gnu.org/licenses/>.
/**
* This script lets the user send commands to the Maxima, and see the response.
* This can be useful for learning about the CAS syntax, and also for testing
* that maxima is working correctly.
*
* @copyright 2012 University of Birmingham
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__.'/../../../../config.php');
require_once($CFG->libdir . '/questionlib.php');
require_once(__DIR__ . '/../locallib.php');
require_once(__DIR__ . '/../stack/utils.class.php');
require_once(__DIR__ . '/../stack/options.class.php');
require_once(__DIR__ . '/../stack/cas/castext.class.php');
require_once(__DIR__ . '/../stack/cas/keyval.class.php');
require_login();
// Get the parameters from the URL.
$questionid = optional_param('questionid', null, PARAM_INT);
if (!$questionid) {
$context = context_system::instance();
require_capability('qtype/stack:usediagnostictools', $context);
$urlparams = array();
} else {
// Load the necessary data.
$questiondata = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
$question = question_bank::load_question($questionid);
// Process any other URL parameters, and do require_login.
list($context, $seed, $urlparams) = qtype_stack_setup_question_test_page($question);
// Check permissions.
question_require_capability_on($questiondata, 'view');
}
$context = context_system::instance();
$PAGE->set_context($context);
$PAGE->set_url('/question/type/stack/adminui/caschat.php', $urlparams);
$title = stack_string('chattitle');
$PAGE->set_title($title);
$debuginfo = '';
$errs = '';
$varerrs = array();
$vars = optional_param('vars', '', PARAM_RAW);
$string = optional_param('cas', '', PARAM_RAW);
$simp = optional_param('simp', '', PARAM_RAW);
// Always fix dollars in this script.
// Very useful for converting existing text for use elswhere in Moodle, such as in pages of text.
$string = stack_maths::replace_dollars($string);
// Sort out simplification.
if ('on' == $simp) {
$simp = true;
} else {
$simp = false;
}
// Initially simplification should be on.
if (!$vars and !$string) {
$simp = true;
}
if ($string) {
$options = new stack_options();
$options->set_site_defaults();
$options->set_option('simplify', $simp);
$session = new stack_cas_session2(array(), $options);
if ($vars) {
$keyvals = new stack_cas_keyval($vars, $options, 0);
$session = $keyvals->get_session();
$varerrs = $keyvals->get_errors();
}
if (!$varerrs) {
$ct = new stack_cas_text($string, $session, 0);
$displaytext = $ct->get_display_castext();
$errs = $ct->get_errors();
$debuginfo = $ct->get_debuginfo();
}
}
echo $OUTPUT->header();
echo $OUTPUT->heading($title);
echo html_writer::tag('p', stack_string('chatintro'));
// If we are editing the General Feedback from a question it is very helpful to see the question text.
if ($questionid) {
echo $OUTPUT->heading(stack_string('questiontext'), 3);
echo html_writer::tag('pre', $question->questiontext, array('class' => 'questiontext'));
}
if (!$varerrs) {
if ($string) {
echo $OUTPUT->box(stack_ouput_castext($displaytext));
}
}
if ($simp) {
$simp = stack_string('autosimplify').' '.
html_writer::empty_tag('input', array('type' => 'checkbox', 'checked' => $simp, 'name' => 'simp'));
} else {
$simp = stack_string('autosimplify').' '.html_writer::empty_tag('input', array('type' => 'checkbox', 'name' => 'simp'));
}
$varlen = substr_count($vars, "\n") + 3;
$stringlen = max(substr_count($string, "\n") + 3, 8);
echo html_writer::tag('form',
html_writer::tag('h2', stack_string('questionvariables')) .
html_writer::tag('p', implode($varerrs)) .
html_writer::tag('p', html_writer::tag('textarea', $vars,
array('cols' => 100, 'rows' => $varlen, 'name' => 'vars'))) .
html_writer::tag('p', $simp) .
html_writer::tag('h2', stack_string('castext')) .
html_writer::tag('p', $errs) .
html_writer::tag('p', html_writer::tag('textarea', $string,
array('cols' => 100, 'rows' => $stringlen, 'name' => 'cas'))) .
html_writer::tag('p', html_writer::empty_tag('input',
array('type' => 'submit', 'value' => stack_string('chat')))),
array('action' => $PAGE->url, 'method' => 'post'));
if ($string) {
echo $OUTPUT->heading(stack_string('questionvariablevalues'), 3);
echo html_writer::start_tag('div', array('class' => 'questionvariables'));
echo html_writer::tag('pre', $session->get_keyval_representation(true));
echo html_writer::end_tag('div');
}
if ('' != trim($debuginfo)) {
echo $OUTPUT->box($debuginfo);
}
echo $OUTPUT->footer();
|
gpl-3.0
|
doczine/Feeds
|
pdf_ad.php
|
141
|
<?php
$url = $_SERVER['REQUEST_URI'];
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>
|
gpl-3.0
|
dovier/coj-web
|
src/main/java/cu/uci/coj/restapi/controller/RestScoreboardsController.java
|
22868
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cu.uci.coj.restapi.controller;
import com.mangofactory.swagger.annotations.ApiIgnore;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import cu.uci.coj.dao.ContestDAO;
import cu.uci.coj.dao.CountryDAO;
import cu.uci.coj.dao.InstitutionDAO;
import cu.uci.coj.dao.UserDAO;
import cu.uci.coj.model.Country;
import cu.uci.coj.model.Institution;
import cu.uci.coj.model.User;
import cu.uci.coj.restapi.templates.CountryDescriptionRest;
import cu.uci.coj.restapi.templates.CountryRest;
import cu.uci.coj.restapi.templates.InstitutionDescriptionRest;
import cu.uci.coj.restapi.templates.InstitutionRest;
import cu.uci.coj.restapi.templates.UserRest;
import cu.uci.coj.restapi.utils.ErrorUtils;
import cu.uci.coj.utils.paging.IPaginatedList;
import cu.uci.coj.utils.paging.PagingOptions;
import java.security.Principal;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author lucy
*/
@Controller
@RequestMapping("/ranking")
public class RestScoreboardsController{
@Resource
private UserDAO userDAO;
@Resource
private InstitutionDAO institutionDAO;
@Resource
private CountryDAO countryDAO;
@Resource
private ContestDAO contestDAO;
@ApiOperation(value = "Obtener tabla de posiciones por usuarios",
notes = "Devuelve las posiciones de todos los usuarios del COJ.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/byuser", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<UserRest> getRankingByUser(
@ApiParam(value = "Filtrar por nombre de usuario") @RequestParam(required = false, value = "pattern") String pattern,
@ApiParam(value = "Filtrar por seguidos") @RequestParam(required = false, defaultValue = "false", value = "following") Boolean following,
@ApiParam(value = "Filtrar por conectados") @RequestParam(required = false, defaultValue = "false", value = "online") Boolean online) {
Integer uid = null;
int found = userDAO.countEnabledUsersForScoreboard(pattern, online, uid);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getUserRanking(pattern, found, online, uid, options);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return listUsersRest;
}
@ApiOperation(value = "Obtener tabla de posiciones por instituciones",
notes = "Devuelve las posiciones de todos las instituciones registradas en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/byinstitution", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<InstitutionRest> getRankingByInstitucions(
@RequestParam(required = false, value = "pattern") String pattern) {
int found = institutionDAO.countEnabledInstitutions(pattern);
if(found>400)
found = 400;
List<Institution> listInstitution = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutions(pattern, found, options);
listInstitution.addAll(pages.getList());
}
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:listInstitution){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip() ,i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return listInstitucionRest;
}
@ApiOperation(value = "Obtener tabla de posiciones por países",
notes = "Devuelve las posiciones de todos los países registrados en el COJ.",
response = CountryRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/bycountry", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<CountryRest> getRankingByCountry(@RequestParam(required = false, value = "pattern") String pattern) {
int found = countryDAO.countEnabledCountries(pattern);
if(found>400)
found = 400;
List<Country> listCountry = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Country> pages = countryDAO.getEnabledCountries(pattern, found, options);
listCountry.addAll(pages.getList());
}
List<CountryRest> listCountryRest = new LinkedList();
for(Country c:listCountry){
CountryRest cr = new CountryRest(c.getId(),c.getRank(), c.getZip(), c.getName(),c.getInstitutions(),c.getUsers(), c.getAcc(), c.getPoints());
listCountryRest.add(cr);
}
return listCountryRest;
}
@ApiOperation(value = "Obtener tabla de posiciones de las instituciones por país",
notes = "Dado el identificador de un país, devuelve las posiciones de todas sus instituciones registradas en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/institutionbycountry/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingInstitutionByCountry(
@ApiParam(value = "Identificador del pais") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
int found = institutionDAO.countEnabledInstitutionsByCountry("", country_id);
if(found>400)
found = 400;
List<Institution> listInstitution = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutionsByCountry("", found, options, country_id);
listInstitution.addAll(pages.getList());
}
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:listInstitution){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip(), i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return new ResponseEntity<>(listInstitucionRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por país",
notes = "Dado el identificador de un país, devuelve las posiciones de todos sus usuarios registrados en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/usersbycountry/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingUsersByCountry(
@ApiParam(value = "Identificador del pais") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
int found = userDAO.countEnabledUsersByCountry("",false, country_id);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getCountryUsersRanking("", found, false, options, country_id);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por institución",
notes = "Dado el identificador de una institución, devuelve las posiciones de todos sus usuarios registrados en el COJ.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad institution id") })
@RequestMapping(value = "/usersbyinstitution/{inst_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingUsersByInstitution(
@PathVariable int inst_id) {
Institution ins = institutionDAO.object("institution.id", Institution.class, inst_id);
if(ins == null)
return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND);
int found = userDAO.countEnabledUsersByInstitutions("", false, inst_id);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getInstitutionUsersRanking("", found, false, options, inst_id);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios en las competencias",
notes = "Devuelve las posiciones de todos los usuarios en las competencias.",
response = UserRest.class,
responseContainer = "List")
@RequestMapping(value = "/bycontest", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<UserRest> getRankingByContest(
@ApiIgnore Principal principal,
@ApiParam(value = "Filtrar por nombre de usuario") @RequestParam(required = false, value = "pattern") String pattern) {
int found = contestDAO.countContestGeneralScoreboard(pattern);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = contestDAO.getContestGeneralScoreboard(found, pattern, options);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return listUsersRest;
}
@ApiOperation(value = "Obtener la descripción de una institución",
notes = "Dado el identificador de una institución, devuelve las descripción asociada a la misma.",
response = InstitutionDescriptionRest.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad institution id") })
@RequestMapping(value = "/description/institution/{inst_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getDescriptionInstitutionByInstID(@PathVariable int inst_id) {
Institution i = institutionDAO.object("institution.id", Institution.class, inst_id);
if(i == null)
return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND);
i.setCount(institutionDAO.integer("institution.profile.count.users", inst_id));
i.setPoints(institutionDAO.real(0.0,"user.score.enabled.inst", inst_id));
i.setRank(institutionDAO.integer(-1,"insitutions.rank", inst_id));
i.setRankincountry(institutionDAO.integer(-1,"institution.rank.incountry" , i.getCountry_id(),inst_id));
Country c = countryDAO.object("country.by.id", Country.class, i.getCountry_id());
String logo = "http://coj.uci.cu/images/school/"+i.getZip()+".png";
InstitutionDescriptionRest idescrip = new InstitutionDescriptionRest(i.getName(),i.getZip(), logo, i.getWebsite(), c.getZip(), c.getName(), i.getCount(), i.getPoints(),i.getRank(), i.getRankincountry());
return new ResponseEntity<>(idescrip, HttpStatus.OK);
}
@ApiOperation(value = "Obtener la descripción de un país",
notes = "Dado el identificador de un país, devuelve las descripción asociada a este.",
response = CountryDescriptionRest.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/description/country/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getDescriptionCountryByCountryID(
@ApiParam(value = "Identificador de País") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
c.setInstitutions(countryDAO.integer("count.institutions", country_id));
c.setPoints(countryDAO.real("user.score", country_id));
c.setRank(countryDAO.integer("country.rank", country_id));
c.setUsers(countryDAO.integer("count.users", country_id));
String flag = "http://coj.uci.cu/images/countries/"+c.getZip()+".png";
CountryDescriptionRest cdescrip = new CountryDescriptionRest(c.getName(),c.getZip_two(), c.getZip(), flag, c.getWebsite(), c.getInstitutions(), c.getUsers(), c.getPoints(), c.getRank());
return new ResponseEntity<>(cdescrip, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones por usuarios (Paginados)",
notes = "Devuelve las posiciones de todos los usuarios del COJ por páginas.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/byuser/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByUserFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
Integer uid = null;
int found = userDAO.countEnabledUsersForScoreboard("", false, uid);
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<User> pages = userDAO.getUserRanking("", found, false, uid, options);
List<UserRest> listUsersRest = new LinkedList();
for(User u:pages.getList()){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones por instituciones (Paginados)",
notes = "Devuelve las posiciones de todos las instituciones del COJ por páginas.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/byinstitution/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByInstitutionFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = institutionDAO.countEnabledInstitutions("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutions("", found, options);
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:pages.getList()){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip(), i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return new ResponseEntity<>(listInstitucionRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones por países (Paginados)",
notes = "Devuelve las posiciones de todos los países del COJ por páginas.",
response = CountryRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/bycountry/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByCountryFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = countryDAO.countEnabledCountries("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<Country> pages = countryDAO.getEnabledCountries("", found, options);
List<CountryRest> listCountryRest = new LinkedList();
for(Country c:pages.getList()){
CountryRest cr = new CountryRest(c.getId(),c.getRank(), c.getZip(), c.getName(),c.getInstitutions(),c.getUsers(), c.getAcc(), c.getPoints());
listCountryRest.add(cr);
}
return new ResponseEntity<>(listCountryRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por competencias (Paginados)",
notes = "Devuelve las posiciones de todos los usuarios del COJ en las competencias por páginas.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/bycontest/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingBybycontestFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = contestDAO.countContestGeneralScoreboard("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<User> pages = contestDAO.getContestGeneralScoreboard(found, "", options);
List<UserRest> listUsersRest = new LinkedList();
for(User u:pages.getList()){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
private int end(int found){
if(found%30==0)
return found/30;
else
return (found/30)+1;
}
}
|
gpl-3.0
|
foundersandcoders/clerk
|
views/maintenance.html
|
325
|
<div class="container-large">
<div class="inner-section-divider-small"></div>
<div style="maring:auto;text-align:center;"
class="section-label">
<h1>Upload</h1>
</div>
<div class="inner-section-divider-medium"></div>
<div>
<div class="upload-container"></div>
</div>
</div>
|
gpl-3.0
|
cinemaouvert/OCT
|
src/View/SubtitlePane.h
|
1776
|
#ifndef SUBTITLEPANE_H
#define SUBTITLEPANE_H
#include <AVPlayer.h>
#include <QtAV/SubtitleFilter.h>
#include <QtAV/Subtitle.h>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QWidget>
#include "src/Model/File.h"
#include "src/Model/Stream.h"
#include "src/Controller/OCTDispatcher.h"
#include "MyModel.h"
namespace Ui {
class SubtitlePane;
}
class SubtitlePane : public QWidget
{
Q_OBJECT
public:
explicit SubtitlePane(QWidget *parent = 0);
explicit SubtitlePane(Model::File *file,Model::Stream *stream,QWidget *parent = 0);
~SubtitlePane();
void setDispatcher(Controller::OCTDispatcher *dispatcher);
void applyReco();
public slots:
void seek(int);
void videoStreamAdded(Model::File*,Model::Stream*);
private slots:
void on_playButton_clicked();
void on_stopButton_clicked();
void updateSlider();
void on_lineEdit_Name_textChanged(const QString &name);
void on_comboBox_Langage_activated(const QString &langage);
void on_comboBox_Encode_activated(const QString &encode);
void on_videoVisualisationComboBox_currentIndexChanged(const QString &arg1);
private:
Ui::SubtitlePane *ui;
Model::File *m_file;
Model::Stream *m_stream;
QtAV::AVPlayer *m_player;
QStandardItemModel *m_model;
QtAV::SubtitleFilter *m_pS;
Controller::OCTDispatcher *m_dispatcher;
void loadFile(QString filepath);
void initPane();
QString videoPath;
void connectInterface();
void parseSubtitleFile();
QMap<QString,QString> m_languageMap;
QMap<QString,QString> m_formatMap;
QMap<QString,QString> m_encodingMap;
void initLists();
signals:
void subtitleChanged( Model::File *, Model::Stream *, QString, QString );
};
#endif // SUBTITLEPANE_H
|
gpl-3.0
|
BayMinimum/Hacktoberfest-Mathematics
|
calculus/riemann_sum/python/riemann_sum_test.py
|
2960
|
import unittest
from decimal import Decimal
from itertools import product
from .riemann import riemann_sum as riemann, RiemannMethod
# Test functions
# lowercase are functions, uppercase are their antiderivatives assuming C = 0.
def f1(x):
return 0
def F1(x):
return 0
def f2(x):
return 3
def F2(x):
return 3 * x
def f3(x):
return x
def F3(x):
return x ** 2 / 2
def f4(x):
return 8 * x
def F4(x):
return 4 * x ** 2
def f5(x):
return 6 * x ** 2
def F5(x):
return 2 * x ** 3
class RiemannTests(unittest.TestCase):
tolerance = Decimal('0.005')
dx = Decimal('0.00001')
functions = [(f1, F1), (f2, F2), (f3, F3), (f4, F4), (f5, F5)]
test_points = [
(0, 1), # Simplest case for most functions
(0, 3), # From zero
(-2, 0), # To zero
(4, 10), # Detatched from zero, positive
(-10, -4), # Detatched from zero, negative
(-5, 7) # Across zero
]
test_points.extend([tuple(reversed(bounds)) for bounds in test_points]) # List, not generator, to evaluate everything before appending
def test_riemann_sum(self):
"""
Test the riemann_sum function by ensuring its results are within a certain small tolerance of the actual value.
The tolerance is set above, and used as `self._tolerance`.
Every function above is tested for every method and every pair of test points, as well as for each pair reversed.
"""
for (func, antiderivative), method, (x1, x2) in product(self.functions, RiemannMethod, self.test_points):
with self.subTest(function=func.__name__, x1=x1, x2=x2, method=method):
estimate = riemann(func, x1, x2, self.dx, method)
actual = Decimal(antiderivative(x2) - antiderivative(x1))
self.assertAlmostEqual(estimate, actual, delta=self.tolerance)
def test_methods(self):
"""
Test the different methods of Riemann summing to ensure they exhibit the known errors/biases.
For example, a left-hand Riemann sum underestimates increasing functions and overestimates decreasing ones.
"""
def func(x):
return x ** 3
def antiderivative(x):
return x ** 4 / 4
x1, x2, dx = map(Decimal, (-10, 10, '0.5')) # Intentionally large dx to exacerbate over/under-estimation
actual = Decimal(antiderivative(x2) - antiderivative(x1))
# Because x^3 is always increasing, left-hand should underestimate it.
estimate_left = riemann(func, x1, x2, dx, RiemannMethod.left)
self.assertLess(estimate_left, actual)
# Because x^3 is always increasing, right-hand should overestimate it.
estimate_right = riemann(func, x1, x2, dx, RiemannMethod.right)
self.assertGreater(estimate_right, actual)
# Because x^3 is rotationally symmetrical about the origin and the input range is symmetrical about the origin, middle and trapezoid should be dead-on.
estimate_middle = riemann(func, x1, x2, dx, RiemannMethod.middle)
estimate_trapezoid = riemann(func, x1, x2, dx, RiemannMethod.trapezoid)
self.assertEqual(estimate_middle, actual)
self.assertEqual(estimate_trapezoid, actual)
|
gpl-3.0
|
frichote/replop
|
CL_code/code/test/io/test_io_error/Makefile
|
606
|
## OPTIONS ####
CFLAGS = -lm -lpthread -Wall -Wextra
LDFLAGS = -g -O3 -Wall -Wextra
CC = colorgcc
## CC = gcc
# src obj
SRC = test_io_error.c
OBJ = $(patsubst %.c,%.o,$(SRC))
EXEC = test_io_error
all: $(SRC) $(EXEC)
$%.o: $%.c
$(CC) $(LDFLAGS) -c $< -o $@
test_io_error : $(OBJ)
$(CC) $(OBJ) -o $@ ../../../obj/bituint/*.o ../../../obj/convert/*.o ../../../obj/createDataSet/*.o ../../../obj/crossEntropy/*.o ../../../obj/io/*.o ../../../obj/lapack/*.o ../../../obj/LFMM/*.o ../../../obj/matrix/*.o ../../../obj/nnlsm/*.o ../../../obj/sNMF/*.o $(CFLAGS) $(LDFLAGS)
clean:
rm -f *.o test_io_error
|
gpl-3.0
|
illim/freespectrogdx
|
core/src/main/scala/priv/sp/house/Limbo.scala
|
6659
|
package priv.sp.house
import priv.sp.GameCardEffect._
import priv.sp._
import priv.sp.update.{SlotUpdate, PlayerUpdate, HouseEventListener}
import priv.util.FuncDecorators
import scala.util.Random
object Limbo {
import CardSpec._
val heavenKeeper = new Creature("limbo.heaven", Attack(3), 7,
I18n("limbo.heaven.description"),
reaction = new HeavenKeeperReaction)
val hellKeeper = new Creature("limbo.hell", Attack(3), 10,
I18n("limbo.hell.description"),
reaction = new HellKeeperReaction)
val baron = new Creature("limbo.baron", Attack(6), 36,
I18n("limbo.baron.description"))
val wraith = new Creature("limbo.wraith", Attack(1) add new WraithAttack, 14,
I18n("limbo.wraith.description"),
runAttack = MultiTargetAttack)
val Limbo: House = House("limbo", List(
heavenKeeper,
hellKeeper,
wraith,
new Creature("limbo.tower", Attack(0), 21,
I18n("limbo.tower.description"),
reaction = new TowerReaction),
Spell("limbo.nether", I18n("limbo.nether.description"),
effects = effects(Direct -> netherGrasp)),
new Creature("limbo.adjudicator", Attack(3), 21,
I18n("limbo.adjudicator.description"),
reaction = new SoulReaction),
Spell("limbo.redemption", I18n("limbo.redemption.description"),
inputSpec = Some(SelectOwnerCreature),
effects = effects(Direct -> redeem)),
baron),
description = I18n("limbo.description"),
effects = List(OnEndTurn -> cleanLimbo),
eventListener = Some(new CustomListener(new LimboEventListener)))
Limbo initCards Houses.basicCostFunc
class HeavenKeeperReaction extends Reaction with LimboReaction {
def onLimbo(s : SlotUpdate): Unit = {
val p = selected.player
p heal 2
p.slots healCreatures 2
selected.focus()
}
}
class HellKeeperReaction extends Reaction with LimboReaction {
def onLimbo(s : SlotUpdate): Unit = {
val p = selected.player.otherPlayer
p heal 2
p.slots inflictCreatures Damage(2, Context(selected.playerId, Some(hellKeeper), selected.num), isAbility = true)
selected.focus()
}
}
class TowerReaction extends Reaction with LimboReaction {
def onLimbo(s : SlotUpdate): Unit = {
s.value foreach { slotState =>
val houseIndex = slotState.card.houseIndex
selected.player.houses.incrMana(1, houseIndex)
selected.player.otherPlayer.houses.incrMana(-1, houseIndex)
selected.focus()
}
}
}
class SoulReaction extends Reaction with LimboReaction {
val possibleCards = Set(heavenKeeper, hellKeeper)
def onLimbo(s : SlotUpdate): Unit = {
selected.player.pstate.desc.get.houses(4).cards.headOption.foreach { c =>
c.card match {
case creature : Creature if possibleCards contains creature =>
val emptyAdjs = selected.adjacentSlots filter (_.value.isEmpty)
(Random shuffle emptyAdjs).headOption foreach { s =>
s add creature
s setData NoLimbo
selected.focus()
}
case _ =>
}
}
}
}
def netherGrasp = { env : Env =>
val amount = env.player.slots.foldl(0) { (i, s) =>
s inflict Damage(100, env) // HACK
i + 3
}
env.player.otherPlayer.slots inflictCreatures Damage(amount, env, isSpell = true)
}
def redeem = { env : Env =>
val slot = env.getOwnerSelectedSlot()
if (slot.get.data == LimboState) {
val card = slot.get.card
slot.destroy()
slot add card
}
}
def cleanLimbo = { env : Env =>
env.player.slots foreach{ s =>
if (s.get.data == LimboState) {
s setData NoLimbo
s inflict Damage(100, env) // !! HACK for phoenix (can't destroy)
}
}
if (env.player.pstate.data == LimboState) {
env.player setData NoLimbo
env.player inflict Damage(0, env)
}
}
trait LimboReaction {
def onLimbo(s : SlotUpdate)
}
class LimboEventListener extends HouseEventListener {
def setLimbo(s : SlotUpdate) = {
s.write(s.value.map(_.copy(life = 0)))
s setData LimboState
player.slots foreach { slot =>
if (slot.get.card == wraith) {
slot.attack.setDirty()
}
slot.get.reaction match {
case reaction : LimboReaction => reaction onLimbo s
case _ =>
}
}
}
override def onDeath() = {
player.pstate.data == NoLimbo || {
if (hasBaron(player)) {
player setData LimboState
player write player.pstate.copy(life = 0)
false
} else {
player.pstate.data != LimboState
}
}
}
def hasBaron( p : PlayerUpdate) = {
p.slots.slots.exists(s => s.value.isDefined && s.get.card == baron)
}
override def init(p: PlayerUpdate) = {
super.init(p)
p.slots.slots foreach { slot =>
slot.delayedDestroy = (FuncDecorators decorate slot.delayedDestroy) update { f =>
{ d: Damage =>
if (slot.value.isDefined){
val slotState = slot.get
if ((slotState.card == baron || !(d.isSpell || d.isAbility))
&& slotState.data != NoLimbo) {
setLimbo(slot)
if (slotState.card == baron && slotState.data != LimboState) {
slot.attack add DoubleAttackSource
}
} else {
f(d)
}
}
}
}
slot.overridableDestroy = (FuncDecorators decorate slot.overridableDestroy) update { f =>
{ () =>
if (slot.value.isDefined){
val slotState = slot.get
if (slotState.card == baron && slotState.data != LimboState) {
setLimbo(slot)
slot.attack add DoubleAttackSource
} else {
f()
}
}
}
}
}
p.slots.onDead = (FuncDecorators decorate p.slots.onDead) after { dead ⇒
player.slots foreach { slot =>
if (slot.get.card == wraith) {
slot.attack.setDirty()
}
}
}
}
}
class WraithAttack extends AttackStateFunc {
def apply(attack: Int, player: PlayerUpdate): Int = {
(attack
+ player.slots.slots.count(s => s.value.isDefined && s.get.data == LimboState)
+ (if (player.pstate.data == LimboState) 1 else 0))
}
}
case object DoubleAttackSource extends AttackSlotStateFunc {
def apply(attack: Int, slot: SlotUpdate) = {
attack * 2
}
}
case object LimboState
case object NoLimbo
}
|
gpl-3.0
|
Pringlez/Reviewer-App
|
app_api/models/locations.js
|
1099
|
var mongoose = require('mongoose');
/** The review document schema */
var reviewSchema = new mongoose.Schema({
author: String,
rating: {
type: Number,
required: true,
min: 0,
max: 5
},
reviewText: String,
createdOn: {
type: Date,
"default": Date.now
}
});
/** The opening time document schema */
var openingTimeSchema = new mongoose.Schema({
days: {
type: String,
required: true
},
opening: String,
closing: String,
closed: {
type: Boolean,
required: true
}
});
/** The location document schema */
var locationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: String,
rating: {
type: Number,
"default": 0,
min: 0,
max: 5
},
facilities: [String],
coords: {
type: [Number],
index: '2dsphere'
},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
/** Defining 'Location' model */
mongoose.model('Location', locationSchema);
|
gpl-3.0
|
niklasf/agentspirit
|
src/runtime/interpreter.h
|
1295
|
// This file is part of the AgentSpirit AgentSpeak interpreter.
// Copyright (C) 2015 Niklas Fiekas <niklas.fiekas@tu-clausthal.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/>.
#ifndef AS_RUNTIME_INTERPRETER_H_
#define AS_RUNTIME_INTERPRETER_H_
#include "../agent.h"
#include "environment.h"
namespace as {
namespace runtime {
/**
* \brief The AgentSpeak interpreter.
*/
class Interpreter {
public:
/**
* \brief Runs one execution step of the given agent in the environment.
*
* \return true, if there is more work to do.
*/
bool Run(Environment *env, as::Agent *agent);
};
} // namespace runtime
} // namespace as
#endif // AS_RUNTIME_INTERPRETER_H_
|
gpl-3.0
|
EvgenijM86/emercoin
|
src/qt/locale/bitcoin_fa_IR.ts
|
35898
|
<TS language="fa_IR" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>گشایش حسابی جدید</translation>
</message>
<message>
<source>&New</source>
<translation>جدید</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>کپی کردن حساب انتخاب شده به حافظه سیستم - کلیپ بورد</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>و کپی آدرس</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<source>&Delete</source>
<translation>و حذف</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>کپی و برچسب</translation>
</message>
<message>
<source>&Edit</source>
<translation>و ویرایش</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>رمز/پَس فرِیز را وارد کنید</translation>
</message>
<message>
<source>New passphrase</source>
<translation>رمز/پَس فرِیز جدید را وارد کنید</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>رمز/پَس فرِیز را دوباره وارد کنید</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>wallet را رمزگذاری کنید</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>باز کردن قفل wallet </translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>کشف رمز wallet</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>رمزگذاری wallet را تایید کنید</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>تایید رمزگذاری</translation>
</message>
<message>
<source>Emercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your emercoins from being stolen by malware infecting your computer.</source>
<translation>Emercoin برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>رمزگذاری تایید نشد</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>قفل wallet باز نشد</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>کشف رمز wallet انجام نشد</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>به روز رسانی با شبکه...</translation>
</message>
<message>
<source>&Overview</source>
<translation>و بازبینی</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>نمای کلی از wallet را نشان بده</translation>
</message>
<message>
<source>&Transactions</source>
<translation>و تراکنش</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>تاریخچه تراکنش را باز کن</translation>
</message>
<message>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<source>Quit application</source>
<translation>از "درخواست نامه"/ application خارج شو</translation>
</message>
<message>
<source>About &Qt</source>
<translation>درباره و QT</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره QT</translation>
</message>
<message>
<source>&Options...</source>
<translation>و انتخابها</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>و رمزگذاری wallet</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>و گرفتن نسخه پیشتیبان از wallet</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<source>Modify configuration options for Emercoin</source>
<translation>اصلاح انتخابها برای پیکربندی Emercoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation>
</message>
<message>
<source>Emercoin</source>
<translation>Emercoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<source>&Send</source>
<translation>و ارسال</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش و</translation>
</message>
<message>
<source>&File</source>
<translation>و فایل</translation>
</message>
<message>
<source>&Settings</source>
<translation>و تنظیمات</translation>
</message>
<message>
<source>&Help</source>
<translation>و راهنما</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>نوار ابزار</translation>
</message>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<source>Up to date</source>
<translation>روزآمد</translation>
</message>
<message>
<source>Catching up...</source>
<translation>در حال روزآمد سازی..</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>ارسال تراکنش</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>تراکنش دریافتی</translation>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎
</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation>هشدار شبکه</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>ویرایش حساب</translation>
</message>
<message>
<source>&Label</source>
<translation>و برچسب</translation>
</message>
<message>
<source>&Address</source>
<translation>حساب&</translation>
</message>
<message>
<source>New receiving address</source>
<translation>حساب دریافت کننده جدید
</translation>
</message>
<message>
<source>New sending address</source>
<translation>حساب ارسال کننده جدید</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>ویرایش حساب دریافت کننده</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>ویرایش حساب ارسال کننده</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Emercoin address.</source>
<translation>آدرس وارد شده "%1" یک آدرس صحیح برای emercoin نسشت</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>عدم توانیی برای قفل گشایی wallet</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>عدم توانیی در ایجاد کلید جدید</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>انتخاب/آپشن</translation>
</message>
<message>
<source>&OK</source>
<translation>و تایید</translation>
</message>
<message>
<source>&Cancel</source>
<translation>و رد</translation>
</message>
<message>
<source>default</source>
<translation>پیش فرض</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Emercoin network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه emercoin به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation>
</message>
<message>
<source>out of sync</source>
<translation>خارج از روزآمد سازی</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation>نام کنسول RPC</translation>
</message>
<message>
<source>Client version</source>
<translation>ویرایش کنسول RPC</translation>
</message>
<message>
<source>Network</source>
<translation>شبکه</translation>
</message>
<message>
<source>Number of connections</source>
<translation>تعداد اتصال</translation>
</message>
<message>
<source>Block chain</source>
<translation>زنجیره مجموعه تراکنش ها</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>تعداد زنجیره های حاضر</translation>
</message>
<message>
<source>Welcome to the Emercoin RPC console.</source>
<translation>به کنسول آر.پی.سی. EMERCOIN خوش آمدید</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>خطای تبدیل URI به کد QR</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
<message>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>ارسال همزمان به گیرنده های متعدد</translation>
</message>
<message>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>تایید عملیات ارسال </translation>
</message>
<message>
<source>S&end</source>
<translation>و ارسال</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>تایید ارسال بیت کوین ها</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>میزان پرداخت باید بیشتر از 0 باشد</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>مقدار مورد نظر از مانده حساب بیشتر است.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>و میزان وجه</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>پرداخت و به چه کسی</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation>
</message>
<message>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt و P</translation>
</message>
<message>
<source>Message:</source>
<translation>پیام:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>&Sign Message</source>
<translation>و امضای پیام </translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt و P</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1 / تایید نشده</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 تایید</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>، هنوز با موفقیت ارسال نگردیده است</translation>
</message>
<message>
<source>unknown</source>
<translation>ناشناس</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>جزئیات تراکنش</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>این بخش جزئیات تراکنش را نشان می دهد</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Type</source>
<translation>گونه</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1 تاییدها)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>تولید شده اما قبول نشده است</translation>
</message>
<message>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<source>Received from</source>
<translation>دریافت شده از</translation>
</message>
<message>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>وجه برای شما </translation>
</message>
<message>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<source>(n/a)</source>
<translation>خالی</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>زمان و تاریخی که تراکنش دریافت شده است</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>نوع تراکنش</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>آدرس مقصد در تراکنش</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>میزان وجه کم شده یا اضافه شده به حساب</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<source>This year</source>
<translation>این سال</translation>
</message>
<message>
<source>Range...</source>
<translation>حدود..</translation>
</message>
<message>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<source>To yourself</source>
<translation>به شما</translation>
</message>
<message>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<source>Other</source>
<translation>دیگر</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>آدرس یا برچسب را برای جستجو وارد کنید</translation>
</message>
<message>
<source>Min amount</source>
<translation>حداقل میزان وجه</translation>
</message>
<message>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>Edit label</source>
<translation>برچسب را ویرایش کنید</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
<message>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Type</source>
<translation>گونه</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<source>Range:</source>
<translation>دامنه:</translation>
</message>
<message>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>گرفتن نسخه پیشتیبان از Wallet</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>داده های Wallet
(*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>عملیات گرفتن نسخه پیشتیبان انجام نشد</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>انتخابها:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>دایرکتوری داده را مشخص کن</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>command line و JSON-RPC commands را قبول کنید</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation>
</message>
<message>
<source>Use the test network</source>
<translation>از تستِ شبکه استفاده نمایید</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>رمز برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین نسخه روزآمد کنید</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation>
</message>
<message>
<source>This help message</source>
<translation>این پیام راهنما</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>لود شدن آدرسها..</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>خطا در هنگام لود شدن wallet.dat</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان اشتباه است for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>وجوه ناکافی</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>لود شدن نمایه بلاکها..</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>wallet در حال لود شدن است...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>اسکنِ دوباره...</translation>
</message>
<message>
<source>Done loading</source>
<translation>اتمام لود شدن</translation>
</message>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
</context>
</TS>
|
gpl-3.0
|
t123/ReadingTool.Win
|
RTWin/Properties/Annotations.cs
|
23764
|
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedParameter.Local
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace RTWin.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example><code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example><code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method,
AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>
/// </summary>
/// <example><code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <see cref="System.ComponentModel.INotifyPropertyChanged"/> interface
/// and this method is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null, and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class |
AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly
/// when marked with <see cref="MeansImplicitUseAttribute"/>
/// or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[NotNull] public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example><code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder
/// within a web project. Path can be relative or absolute,
/// starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
[NotNull] public string BasePath { get; private set; }
}
// ASP.NET MVC attributes
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format) { }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC controller. If applied to a method,
/// the MVC controller name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC partial view. If applied to a method,
/// the MVC partial view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling all inspections
/// for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Field, Inherited = true)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Field |
AttributeTargets.Property, Inherited = true)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
// Razor attributes
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)]
public sealed class RazorSectionAttribute : Attribute { }
}
|
gpl-3.0
|
GizMecano/opencart-2-fr
|
admin/language/fr-FR/extension/dashboard/sale.php
|
1202
|
<?php
/*
* Copyright (C) 2015-2018 P. Mergey
* 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/>.
*/
// Heading
$_['heading_title'] = 'Total des ventes';
// Text
$_['text_extension'] = 'Extensions';
$_['text_success'] = 'Vous venez de modifier le tableau de bord des ventes !';
$_['text_edit'] = 'Modifier le tableau de bord des ventes';
$_['text_view'] = 'Voir plus...';
// Entry
$_['entry_status'] = 'Statut';
$_['entry_sort_order'] = 'Classement';
$_['entry_width'] = 'Largeur';
// Error
$_['error_permission'] = 'Attention : vous n’avez pas l’autorisation de modifier le tableau de bord des ventes !';
|
gpl-3.0
|
tryton/webdav
|
tests/test_webdav.py
|
504
|
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import unittest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import ModuleTestCase
class WebdavTestCase(ModuleTestCase):
'Test Webdav module'
module = 'webdav'
def suite():
suite = trytond.tests.test_tryton.suite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(
WebdavTestCase))
return suite
|
gpl-3.0
|
sdemingo/makeo
|
README.md
|
1356
|
# What is Makeo
It's a really simple stack-based virtual machine and a intermediate
language interpreter named IL. Now, I'm preparing a reference of this
intermediate language and working on a compiler to get IL code from a
high-level language called MK.
This work was inspired by reading "The Elements of Computing Systems:
Building a Modern Computer from First Principles" and It has not a
particular target and I have made it, just for fun. If you want to
help me and learn some things about compilers, of course, you are
invited ;-)
# Install
To install Makeo properly you only need to use the followings
commands:
```
git clone https://github.com/sdemingo/makeo.git
cd makeo
make
make clean
MKPATH=`pwd`
export MKPATH
```
# Executing MK programs
MK is a simple high-level programing language. Before you can execute
a program, you must compile it. To compile a MK program you have to
use the mkc tool. This tool compile your MK code into a IL or
intermediate code based on commands to a stack-based virtual machine.
To compile a MK code use mkc tool:
```
$ mkc examples/program.mk -o /tmp/program.il
```
Now, you can run your program with mkm tool:
```
$ mkm /tmp/program.il
```
You can use the following flags with mkm:
-v: print all line read from the input
-m: print all symbols on the symbol table with theirs values
|
gpl-3.0
|
kyro46/assMxGraphQuestion
|
README.md
|
1117
|
# assMxGraphQuestion
mxGraph-Questiontypeplugin for ILIAS 5.4
For ILIAS 5.2 to 5.3 see the [**Releases**](https://github.com/kyro46/assMxGraphQuestion/releases)
### Questiontype that allows the creation of EPC-diagrams via drag&drop editor ###
This plugin will add a questiontype, that allows creation of Event-driven process chain diagramms.
Examiners can create:
* Sample solution
* Initial graph for the examinee to extend
### Installation ###
* Customizing/global/plugins/Modules/TestQuestionPool/Questions
```bash
mkdir -p Customizing/global/plugins/Modules/TestQuestionPool/Questions
cd Customizing/global/plugins/Modules/TestQuestionPool/Questions
git clone https://github.com/kyro46/assMxGraphQuestion.git
```
and activate it in the ILIAS-Admin-GUI. Manual correction has to be enabled for this question type.
### Known Problems ###
* PDF-generation for the "Test Archive File" does not support Scalable Vector Graphics yet, so the solution is not shown.
### Credits ###
* Development by Christoph Jobst, University Leipzig, 2017
* The plugin utilises [mxgraph](https://github.com/jgraph/mxgraph)
|
gpl-3.0
|
NJU-HouseWang/nju-eas-client
|
src/main/java/NJU/HouseWang/nju_eas_client/net/ClientPool.java
|
2651
|
package NJU.HouseWang.nju_eas_client.net;
import java.io.IOException;
import java.util.Stack;
/**
* 网络连接池
*
* @author Xin
* @version 2013-12-12
*/
public class ClientPool {
/**
* 连接池单件
*/
private static ClientPool cPool = null;
/**
* 存放连接的栈
*/
private Stack<Client> clientStack = new Stack<Client>();
/**
* 默认最大连接数
*/
private static final int DEFAULT_MAX_SIZE = 32;
/**
* 默认最小连接数
*/
private static final int DEFAULT_MIN_SIZE = 16;
/**
* 默认IP
*/
private static final String DEFAULT_IP = "localhost";
/**
* 默认端口
*/
private static final int DEFAULT_PORT = 9100;
/**
* 最大连接数
*/
private int maxSize;
/**
* 最小连接数
*/
private int minSize;
/**
* 当前连接数
*/
private int linkNum = 0;
/**
* 当前IP
*/
private String ip;
/**
* 当前端口
*/
private int port;
/**
* 以默认配置构造
*/
private ClientPool() {
maxSize = DEFAULT_MAX_SIZE;
minSize = DEFAULT_MIN_SIZE;
ip = DEFAULT_IP;
port = DEFAULT_PORT;
}
/**
* 以默认配置取得单件
*
* @return ClientPool单件
*/
public static ClientPool getInstance() {
if (cPool != null) {
return cPool;
} else {
cPool = new ClientPool();
try {
cPool.initialize();
} catch (Exception e) {
e.printStackTrace();
}
return cPool;
}
}
/**
* 自定义构造
*
* @param ip
* @param port
* @param maxSize
* @param minSize
*/
private ClientPool(String ip, int port, int maxSize, int minSize) {
this.maxSize = maxSize;
this.minSize = minSize;
this.ip = ip;
this.port = port;
}
/**
* 得到自定义构造的单件
*
* @param ip
* @param port
* @param max
* @param min
* @return
*/
public static ClientPool getInstance(String ip, int port, int max, int min) {
if (cPool != null) {
return cPool;
} else {
cPool = new ClientPool(ip, port, max, min);
return cPool;
}
}
/**
* 初始化连接数
*/
private void initialize() {
for (int i = 0; i < maxSize; i++) {
Client c = new Client(ip, port);
try {
c.createConnection();
} catch (IOException e) {
break;
}
clientStack.push(c);
linkNum++;
}
}
/**
* 关闭连接池
*/
public void shutdown() {
while (clientStack.isEmpty()) {
clientStack.pop().shutDownConnection();
}
}
/**
* 得到连接
*
* @return 连接
*/
public Client getClient() {
if (linkNum < minSize) {
new Thread(new Runnable() {
public void run() {
initialize();
}
}).start();
}
linkNum--;
return clientStack.pop();
}
}
|
gpl-3.0
|
gaiusm/pge
|
c/foo.c
|
8494
|
/* do not edit automatically generated by mc from foo. */
/*
projectVector - returns the vector, onto, after it has been
projected by, project.
*/
# if !defined (PROC_D)
# define PROC_D
typedef void (*PROC_t) (void);
typedef struct { PROC_t proc; } PROC;
# endif
# if !defined (TRUE)
# define TRUE (1==1)
# endif
# if !defined (FALSE)
# define FALSE (1==0)
# endif
# include "GpopWorld.h"
# include "GtwoDsim.h"
# include "GdeviceIf.h"
# include "GFractions.h"
# include "GPoints.h"
# include "GmacroObjects.h"
# define testCorner FALSE
# define testRight FALSE
# define useGroff FALSE
static deviceIf_Colour light;
static deviceIf_Colour dark;
/*
placeFixed -
*/
static void placeFixed (void);
/*
placeNonFixed -
*/
static void placeNonFixed (void);
/*
placeFixed -
*/
static void placeFixed (void);
/*
placeNonFixed -
*/
static void placeNonFixed (void);
/*
placeFixed -
*/
static void placeFixed (void)
{
macroObjects_Macro m;
m = macroObjects_initMacro ();
m = macroObjects_moveTo (m, Points_initPoint (Fractions_zero (), Fractions_initFract (0, 98, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), light, Points_initPoint (Fractions_initFract (0, 97, 100), Fractions_zero ()), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 2, 100))));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 2, 100), Fractions_initFract (0, 3, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_blue (), Points_initPoint (Fractions_initFract (0, 97, 100), Fractions_zero ()), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 2, 100))));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_one (), Fractions_initFract (0, 98, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_red (), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 97, 100))), Points_initPoint (Fractions_negate (Fractions_initFract (0, 3, 100)), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 3, 100), Fractions_initFract (0, 98, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_green (), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 97, 100))), Points_initPoint (Fractions_negate (Fractions_initFract (0, 3, 100)), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 4, 100), Fractions_initFract (0, 83, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_purple (), Points_initPoint (Fractions_initFract (0, 76, 100), Fractions_negate (Fractions_initFract (0, 2, 100))), Points_initPoint (Fractions_negate (Fractions_initFract (0, 3, 100)), Fractions_negate (Fractions_initFract (0, 2, 100))));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 15, 100), Fractions_initFract (0, 63, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), light, Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 2, 100))), Points_initPoint (Fractions_initFract (0, 79, 100), Fractions_initFract (0, 6, 100)));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 47, 100), Fractions_initFract (0, 14, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_blue (), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 10, 100))), Points_initPoint (Fractions_initFract (0, 5, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 50, 100), Fractions_initFract (0, 24, 100)));
m = macroObjects_triangle (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_red (), Points_initPoint (Fractions_negate (Fractions_initFract (0, 8, 100)), Fractions_negate (Fractions_initFract (0, 7, 100))), Points_initPoint (Fractions_initFract (0, 15, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 17, 100), Fractions_initFract (0, 15, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_green (), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 10, 100))), Points_initPoint (Fractions_initFract (0, 5, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 77, 100), Fractions_initFract (0, 15, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_purple (), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 10, 100))), Points_initPoint (Fractions_initFract (0, 5, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 20, 100), Fractions_initFract (0, 25, 100)));
m = macroObjects_triangle (m, TRUE, Fractions_zero (), light, Points_initPoint (Fractions_negate (Fractions_initFract (0, 8, 100)), Fractions_negate (Fractions_initFract (0, 7, 100))), Points_initPoint (Fractions_initFract (0, 15, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 80, 100), Fractions_initFract (0, 25, 100)));
m = macroObjects_triangle (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_blue (), Points_initPoint (Fractions_negate (Fractions_initFract (0, 8, 100)), Fractions_negate (Fractions_initFract (0, 7, 100))), Points_initPoint (Fractions_initFract (0, 15, 100), Fractions_zero ()));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 5, 100), Fractions_initFract (0, 49, 100)));
m = macroObjects_angledRect (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_red (), Points_initPoint (Fractions_initFract (0, 51, 100), Fractions_negate (Fractions_initFract (0, 2, 100))), Points_initPoint (Fractions_zero (), Fractions_negate (Fractions_initFract (0, 2, 100))));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 82, 100), Fractions_initFract (0, 42, 100)));
m = macroObjects_triangle (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_green (), Points_initPoint (Fractions_negate (Fractions_initFract (0, 6, 100)), Fractions_negate (Fractions_initFract (0, 5, 100))), Points_initPoint (Fractions_initFract (0, 10, 100), Fractions_zero ()));
m = macroObjects_rootMacro (m);
popWorld_populate (m, TRUE, TRUE);
}
/*
placeNonFixed -
*/
static void placeNonFixed (void)
{
macroObjects_Macro m;
m = macroObjects_initMacro ();
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 9, 100), Fractions_initFract (0, 91, 100)));
m = macroObjects_circle (m, TRUE, Fractions_zero (), dark, Fractions_initFract (0, 3, 100));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 85, 100), Fractions_initFract (0, 90, 100)));
m = macroObjects_circle (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_yellow (), Fractions_initFract (0, 3, 100));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 75, 100), Fractions_initFract (0, 73, 100)));
m = macroObjects_circle (m, TRUE, Fractions_zero (), (deviceIf_Colour) deviceIf_blue (), Fractions_initFract (0, 3, 100));
m = macroObjects_moveTo (m, Points_initPoint (Fractions_initFract (0, 20, 100), Fractions_initFract (0, 89, 100)));
m = macroObjects_circle (m, TRUE, Fractions_zero (), dark, Fractions_initFract (0, 3, 100));
m = macroObjects_rootMacro (m);
popWorld_mass (Fractions_cardinal (1));
popWorld_velocity (Points_initPoint (Fractions_mult (Fractions_initFract (10, 0, 1), Fractions_zero ()), Fractions_mult (Fractions_initFract (10, 0, 1), Fractions_initFract (0, 11, 100))));
popWorld_populate (m, FALSE, TRUE);
}
void _M2_foo_init (__attribute__((unused)) int argc, __attribute__((unused)) char *argv[])
{
popWorld_init (useGroff);
light = deviceIf_defineColour (Fractions_initFract (0, 166, 256), Fractions_initFract (0, 124, 256), Fractions_initFract (0, 54, 256));
dark = deviceIf_defineColour (Fractions_initFract (0, 76, 256), Fractions_initFract (0, 47, 256), Fractions_zero ());
placeFixed ();
twoDsim_gravity (-9.81);
placeNonFixed ();
twoDsim_simulateFor (25.0);
}
void _M2_foo_finish (__attribute__((unused)) int argc, __attribute__((unused)) char *argv[])
{
}
|
gpl-3.0
|
centaurialpha/edis
|
src/ui/editor/minimap.py
|
3836
|
# -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.QtGui import (
QGraphicsOpacityEffect,
QFrame
)
from PyQt4.QtCore import (
QPropertyAnimation,
Qt
)
from PyQt4.Qsci import QsciScintilla
class Minimap(QsciScintilla):
def __init__(self, weditor):
QsciScintilla.__init__(self, weditor)
self._weditor = weditor
self._indentation = self._weditor._indentation
self.setLexer(self._weditor.lexer())
# Configuración Scintilla
self.setMouseTracking(True)
self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, False)
self.SendScintilla(QsciScintilla.SCI_HIDESELECTION, True)
self.setFolding(QsciScintilla.NoFoldStyle, 1)
self.setReadOnly(True)
self.setCaretWidth(0)
self.setStyleSheet("background: transparent; border: 0px;")
# Opacity
self.effect = QGraphicsOpacityEffect()
self.setGraphicsEffect(self.effect)
self.effect.setOpacity(0.5)
# Deslizador
self.slider = Slider(self)
self.slider.hide()
def resizeEvent(self, event):
super(Minimap, self).resizeEvent(event)
self.slider.setFixedWidth(self.width())
lines_on_screen = self._weditor.SendScintilla(
QsciScintilla.SCI_LINESONSCREEN)
self.slider.setFixedHeight(lines_on_screen * 4)
def update_geometry(self):
self.setFixedHeight(self._weditor.height())
self.setFixedWidth(self._weditor.width() * 0.13)
x = self._weditor.width() - self.width()
self.move(x, 0)
self.zoomIn(-3)
def update_code(self):
text = self._weditor.text().replace('\t', ' ' * self._indentation)
self.setText(text)
def leaveEvent(self, event):
super(Minimap, self).leaveEvent(event)
self.slider.animation.setStartValue(0.2)
self.slider.animation.setEndValue(0)
self.slider.animation.start()
def enterEvent(self, event):
super(Minimap, self).enterEvent(event)
if not self.slider.isVisible():
self.slider.show()
else:
self.slider.animation.setStartValue(0)
self.slider.animation.setEndValue(0.2)
self.slider.animation.start()
class Slider(QFrame):
def __init__(self, minimap):
QFrame.__init__(self, minimap)
self._minimap = minimap
self.setStyleSheet("background: gray; border-radius: 3px;")
# Opacity
self.effect = QGraphicsOpacityEffect()
self.setGraphicsEffect(self.effect)
self.effect.setOpacity(0.2)
# Animación
self.animation = QPropertyAnimation(self.effect, "opacity")
self.animation.setDuration(150)
# Cursor
self.setCursor(Qt.OpenHandCursor)
def mouseMoveEvent(self, event):
super(Slider, self).mouseMoveEvent(event)
#FIXME: funciona algo loco
pos = self.mapToParent(event.pos())
dy = pos.y() - (self.height() / 2)
if dy < 0:
dy = 0
self.move(0, dy)
pos.setY(pos.y() - event.pos().y())
self._minimap._weditor.verticalScrollBar().setValue(pos.y())
self._minimap.verticalScrollBar().setSliderPosition(
self._minimap.verticalScrollBar().sliderPosition() + 2)
self._minimap.verticalScrollBar().setValue(pos.y() - event.pos().y())
def mousePressEvent(self, event):
super(Slider, self).mousePressEvent(event)
self.setCursor(Qt.ClosedHandCursor)
def mouseReleaseEvent(self, event):
super(Slider, self).mouseReleaseEvent(event)
self.setCursor(Qt.OpenHandCursor)
|
gpl-3.0
|
tnodir/fort
|
src/ui/util/conf/addressrange.h
|
1275
|
#ifndef ADDRESSRANGE_H
#define ADDRESSRANGE_H
#include <QObject>
#include <QVariant>
#include <util/net/ip4range.h>
class AddressRange
{
public:
explicit AddressRange();
bool includeAll() const { return m_includeAll; }
void setIncludeAll(bool includeAll) { m_includeAll = includeAll; }
bool excludeAll() const { return m_excludeAll; }
void setExcludeAll(bool excludeAll) { m_excludeAll = excludeAll; }
bool includeIsEmpty() const { return includeRange().isEmpty(); }
bool excludeIsEmpty() const { return excludeRange().isEmpty(); }
quint32 includeZones() const { return m_includeZones; }
void setIncludeZones(quint32 v) { m_includeZones = v; }
quint32 excludeZones() const { return m_excludeZones; }
void setExcludeZones(quint32 v) { m_excludeZones = v; }
Ip4Range &includeRange() { return m_includeRange; }
Ip4Range &excludeRange() { return m_excludeRange; }
const Ip4Range &includeRange() const { return m_includeRange; }
const Ip4Range &excludeRange() const { return m_excludeRange; }
private:
bool m_includeAll : 1;
bool m_excludeAll : 1;
quint32 m_includeZones = 0;
quint32 m_excludeZones = 0;
Ip4Range m_includeRange;
Ip4Range m_excludeRange;
};
#endif // ADDRESSRANGE_H
|
gpl-3.0
|
fearless359/simpleinvoices
|
library/pdf/output._interface.class.php
|
2855
|
<?php
// $Header: /cvsroot/html2ps/output._interface.class.php,v 1.8 2007/01/09 20:13:48 Konstantin Exp $
class OutputDriver {
function add_link($x, $y, $w, $h, $target) { }
function add_local_link($left, $top, $width, $height, $anchor) { }
function circle($x, $y, $r) { }
function clip() {}
function close() { die("Unoverridden 'close' method called in ".get_class($this)); }
function closepath() {}
function content_type() { die("Unoverridden 'content_type' method called in ".get_class($this)); }
function dash($x, $y) { }
function decoration($underline, $overline, $strikeout) { }
function error_message() { die("Unoverridden 'error_message' method called in ".get_class($this)); }
function new_form($name) {}
function field_multiline_text($x, $y, $w, $h, $value, $field_name) { }
function field_text($x, $y, $w, $h, $value, $field_name) { }
function field_password($x, $y, $w, $h, $value, $field_name) { }
function field_pushbutton($x, $y, $w, $h) { }
function field_pushbuttonimage($x, $y, $w, $h, $field_name, $value, $actionURL) { }
function field_pushbuttonreset($x, $y, $w, $h) { }
function field_pushbuttonsubmit($x, $y, $w, $h, $field_name, $value, $actionURL) { }
function field_checkbox($x, $y, $w, $h, $name, $value, $checked) { }
function field_radio($x, $y, $w, $h, $groupname, $value, $checked) { }
function field_select($x, $y, $w, $h, $name, $value, $options) { }
function fill() { }
function font_ascender($name, $encoding) {}
/**
* Note that positive value returned by this function
* means offset to the BOTTOM!
*/
function font_descender($name, $encoding) {}
function get_bottom() {}
function image($image, $x, $y, $scale) {}
function image_scaled($image, $x, $y, $scale_x, $scale_y) { }
function image_ry($image, $x, $y, $height, $bottom, $ox, $oy, $scale) { }
function image_rx($image, $x, $y, $width, $right, $ox, $oy, $scale) { }
function image_rx_ry($image, $x, $y, $width, $height, $right, $bottom, $ox, $oy, $scale) { }
function lineto($x, $y) { }
function moveto($x, $y) { }
function next_page($height) { }
function release() { }
function restore() { }
function save() { }
// Note that there's no functions for setting bold/italic style of the fonts;
// you must keep in mind that roman/bold/italic font variations are, in fact, different
// fonts stored in different files and it is the business of the font resolver object to
// find the appropriate font name. Here we just re-use it.
//
function setfont($name, $encoding, $size) {}
// function setfontcore($name, $size) {}
function setlinewidth($x) { }
function setrgbcolor($r, $g, $b) { }
function set_watermark($text) { }
function show_xy($text, $x, $y) {}
function stringwidth($string, $name, $encoding, $size) { }
function stroke() { }
}
?>
|
gpl-3.0
|
CCAFS/MARLO
|
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionDictionaryManagerImpl.java
|
1922
|
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO 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.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
/**************
* @author Diego Perez - CIAT/CCAFS
**************/
package org.cgiar.ccafs.marlo.data.manager.impl;
import org.cgiar.ccafs.marlo.data.dao.InstitutionDictionaryDAO;
import org.cgiar.ccafs.marlo.data.manager.InstitutionDictionaryManager;
import org.cgiar.ccafs.marlo.data.model.InstitutionDictionary;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class InstitutionDictionaryManagerImpl implements InstitutionDictionaryManager {
private InstitutionDictionaryDAO institutionDictionaryDAO;
@Inject
public InstitutionDictionaryManagerImpl(InstitutionDictionaryDAO institutionDictionaryDAO) {
super();
this.institutionDictionaryDAO = institutionDictionaryDAO;
}
@Override
public List<InstitutionDictionary> getAll() {
return institutionDictionaryDAO.getAll();
}
@Override
public InstitutionDictionary getInstitutionDictionaryById(long id) {
return institutionDictionaryDAO.getInstitutionDictionaryById(id);
}
}
|
gpl-3.0
|
fireball-QMD/progs
|
SOLVESH_ORDERN/set_maxdimension.f90
|
9919
|
! copyright info:
!
! @Copyright 2001
! Fireball Committee
! Brigham Young University - James P. Lewis, Chair
! Arizona State University - Otto F. Sankey
! University of Regensburg - Juergen Fritsch
! Universidad de Madrid - Jose Ortega
! Other contributors, past and present:
! Auburn University - Jian Jun Dong
! Arizona State University - Gary B. Adams
! Arizona State University - Kevin Schmidt
! Arizona State University - John Tomfohr
! Lawrence Livermore National Laboratory - Kurt Glaesemann
! Motorola, Physical Sciences Research Labs - Alex Demkov
! Motorola, Physical Sciences Research Labs - Jun Wang
! Ohio University - Dave Drabold
!
! fireball-qmd is a free (GPLv3) open 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/>.
! set_maxdimensions.f90
! Program Description
! ===========================================================================
! This routine determines the maximum dimension for a given parameter.
! This maximum is the ultimate maximum having considered the information
! from all processors. Information for a set of indices must be communicated
! to the processor myrank. This information is then used locally to
! evaluate a local maximum. The ultimate maximum is the maximum of all
! local maximums.
!
! ===========================================================================
! Code written by:
! James P. Lewis
! Department of Physics and Astronomy
! Brigham Young University
! N233 ESC P.O. Box 24658
! Provo, UT 84602-4658
! FAX (801) 422-2265
! Office Telephone (801) 422-7444
! ===========================================================================
!
! Program Declaration
! ===========================================================================
subroutine set_maxdimension (nactualprocs, myrank, nprows, nAmax, &
& nBmax, ncolsAmax, ncolsB, ncolsBmax, &
& numA, listA, istartrowA, numB, listB, &
& istartrowB, ioption, nCmax)
use interactions
implicit none
include 'mpif.h'
! Argument Declaration and Description
! ===========================================================================
! Input
integer, intent (in) :: ioption
integer, intent (in) :: istartrowA
integer, intent (in) :: istartrowB
integer, intent (in) :: myrank
integer, intent (in) :: nactualprocs
integer, intent (in) :: nprows
integer, intent (in) :: nAmax
integer, intent (in) :: nBmax
integer, intent (in) :: ncolsAmax
integer, intent (in) :: ncolsB
integer, intent (in) :: ncolsBmax
integer, intent (in), dimension (ncolsAmax) :: numA
integer, intent (in), dimension (ncolsBmax) :: numB
integer, intent (in), dimension (nAmax, ncolsAmax) :: listA
integer, intent (in), dimension (nBmax, ncolsBmax) :: listB
! Output
integer, intent (out) :: nCmax
! Local Parameters and Data Declaration
! ===========================================================================
! Local Variable Declaration and Description
! ===========================================================================
integer ierror, request
integer imu, inu
integer index, blockno
integer iproc
integer irecrows
integer irecstart
integer packpos_sparse
integer packsize_sparse
integer ndiv, nmod
integer isendproc, irecproc
logical more_sendrecv
integer sendsize
integer*1, dimension (:,:), allocatable :: packarray_sparse
integer, dimension (MPI_STATUS_SIZE) :: status
integer, dimension (:),allocatable :: numC
integer, dimension (:,:),allocatable :: listC
! Temporary array communicated from neighboring processor.
integer, dimension (:),allocatable :: numT
integer, dimension (:,:),allocatable :: listT
! Bit matrix indicating which blocks of a product matrix are nonzero.
logical, dimension (:, :), allocatable :: bit_matrix
logical, dimension (:), allocatable :: bit_column
! BTN communication domain
integer MPI_BTN_WORLD, MPI_OPT_WORLD, MPI_BTN_WORLD_SAVE
common /btnmpi/ MPI_BTN_WORLD, MPI_OPT_WORLD, MPI_BTN_WORLD_SAVE
! Allocate Arrays
! ===========================================================================
! Procedure
! ===========================================================================
! Processor 0:
allocate(numC(nprows))
allocate(listC(norbitals,nprows))
allocate(numT(ncolsBmax))
allocate(listT(nBmax,ncolsBmax))
numC = 0
call sparse_getdimension (nprows, nAmax, nBmax, norbitals, ncolsAmax,&
& ncolsB, ncolsBmax, numA, listA, istartrowA,&
& numB, listB, istartrowB, .false., numC, &
& listC, nCmax)
! Local section sizes
if (ioption .eq. 0) then
ndiv = norbitals / nactualprocs
nmod = mod(norbitals,nactualprocs)
else
ndiv = nbands / nactualprocs
nmod = mod(nbands,nactualprocs)
end if
! Send local coefficients to the next processor.
if (nactualprocs .gt. 1) then
! Allocate the bit matrix.
! FIXME: Can we reuse this bit matrix in the code following the
! set_maxdimension call?
allocate (bit_matrix (nactualprocs, nactualprocs))
allocate (bit_column (nactualprocs))
bit_column = .false.
do imu = 1, nprows
do inu = 1, numA(imu)
index = listA(inu,imu)
if (index .gt. (ndiv+1) * nmod) then
blockno = (index - (ndiv+1) * nmod - 1) / ndiv + nmod + 1
else
blockno = (index - 1) / (ndiv + 1) + 1
end if
bit_column (blockno) = .true.
end do
end do
! Communicate the bit vector over all processors.
call MPI_ALLGATHER (bit_column, nactualprocs, MPI_LOGICAL, &
& bit_matrix, nactualprocs, MPI_LOGICAL, &
& MPI_BTN_WORLD, ierror)
deallocate (bit_column)
! Allocates space for packed sparse matrices.
call sparse_getpacksize (nBmax, ncolsBmax, packsize_sparse)
allocate (packarray_sparse (packsize_sparse,2))
! FIXME We may want to check if these elements need to be sent at all.
packpos_sparse = 0
call sparse_pack_indices (packsize_sparse, ncolsB, nBmax, ncolsBmax,&
& numB, listB, packarray_sparse, &
& packpos_sparse)
! Now determine nCmax based on each of the products from the other processors.
! Thus the value of nCmax may increase as more products are considered.
! Repeatedly call getsendrecv to get a processor to send to and a processor
! to receive from, until everything has been sent and received.
sendsize = packpos_sparse
do
call getsendrecv (myrank, .false., bit_matrix, &
& isendproc, irecproc, more_sendrecv)
if (.not. more_sendrecv) exit
! Send to the processor returned by getsendrecv.
if (isendproc .ne. myrank) then
call MPI_ISEND (packarray_sparse, sendsize, MPI_PACKED, &
& isendproc, 0, MPI_BTN_WORLD, request, ierror)
end if
! Receive from the processor returned by getsendrecv.
if (irecproc .ne. myrank) then
call MPI_RECV (packarray_sparse (:,2), packsize_sparse, &
& MPI_PACKED, irecproc, 0, MPI_BTN_WORLD, status, &
& ierror)
end if
if (isendproc .ne. myrank) call MPI_WAIT (request, status, ierror)
if (irecproc .ne. myrank) then
irecrows = ndiv
if (irecproc .lt. nmod) then
irecrows = irecrows + 1
irecstart = irecrows*irecproc + 1
else
irecstart = (irecrows + 1)*nmod + irecrows*(irecproc - nmod) + 1
end if
! Now unpack the packet containing the indices that were received.
packpos_sparse = 0
call sparse_unpack_indices (packarray_sparse (:,2), &
& packsize_sparse, nBmax, ncolsBmax, &
& numT, listT, packpos_sparse)
call sparse_getdimension (nprows, nAmax, nBmax, norbitals, &
& ncolsAmax, irecrows, ncolsBmax, numA, &
& listA, istartrowA, numT, listT, &
& irecstart, .true., numC, listC, nCmax)
end if
end do
deallocate (packarray_sparse)
deallocate (bit_matrix)
end if
! Deallocate Arrays
! ===========================================================================
deallocate(numC,listC,numT,listT)
! Format Statements
! ===========================================================================
return
end
|
gpl-3.0
|
SpoinkyNL/Artemis
|
src/Artemis.Core/Exceptions/ArtemisCoreException.cs
|
413
|
using System;
namespace Artemis.Core
{
/// <summary>
/// Represents errors that occur within the Artemis Core
/// </summary>
public class ArtemisCoreException : Exception
{
internal ArtemisCoreException(string message) : base(message)
{
}
internal ArtemisCoreException(string message, Exception inner) : base(message, inner)
{
}
}
}
|
gpl-3.0
|
r78v10a07/gTools
|
gTools/src/berror.c
|
1741
|
/*
* File: error.c
* Author: roberto
*
* Created on April 14, 2014, 11:52 AM
*/
#include <stdio.h>
#include <stdlib.h>
/**
* Print a message in the file and exit if the exit_status is different of zero
*
* @param out the file to printout the message
* @param msg the message to be printed out
* @param file the source code file (__FILE__) or NULL to not print this info
* @param line the source code line (__LINE__) or 0
* @param exit_status the exit status (Exit the program is this number is different of zero)
*/
void printLog(FILE *out, char *msg, char *file, int line, int exit_status) {
if (file) {
fprintf(out, "%s. File: %s Line: %d\t", msg, file, line);
} else {
fprintf(out, "%s", msg);
}
if (exit_status != 0) {
fprintf(out, "\n");
exit(exit_status);
}
}
/**
* Check if the void pointer is NULL and print out a message. If the exit_status
* is different of zero it exit the program
*
* @param data the pointer to check
* @param msg the message to be printed out
* @param file the source code file (__FILE__) or NULL to not print this info
* @param line the source code line (__LINE__) or 0
* @param exit_status the exit status (Exit the program is this number is different of zero)
* @return the same pointer if everything is fine
*/
void *checkPointerError(void *data, char *msg, char *file, int line, int exit_status) {
if (!data) {
printLog(stderr, msg, file, line, exit_status);
}
return data;
}
/**
* Print the FILE and LINE info
*
* @param file the file name (__FILE__)
* @param line the line name (__LINE__)
*/
void printFileLine(char *file, int line) {
printf("%s %d\n", file, line);
fflush(stdout);
}
|
gpl-3.0
|
sidben/VillagerTweaks
|
src/main/java/sidben/villagertweaks/network/NetworkHelper.java
|
7380
|
package sidben.villagertweaks.network;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import sidben.villagertweaks.ModVillagerTweaks;
import sidben.villagertweaks.common.ExtendedGolem;
import sidben.villagertweaks.common.ExtendedVillagerZombie;
import sidben.villagertweaks.helper.GolemEnchantment;
import sidben.villagertweaks.helper.LogHelper;
import sidben.villagertweaks.tracker.ClientInfoTracker;
/*
* NOTE:
*
* One problem I have with this class is that sending messages to client when the player reaches the "PlayerEvent.StartTracking"
* event causes the client to receive the pack BEFORE the client loads any entities, so I have to store the message locally and
* check again on the "EntityJoinWorld" event for the client-side.
*
* One way I could prevent this is, instead of sending the messages instantly, I can store them in a list on the server and send
* all at once at a later event, when I expect the client to have all entities loaded.
*
* Would that cause too much network traffic at once? How risky is the desync? Isn't y current method better, since
* it uses the client memory instead of server's memory? Need future tests.
*
*/
/**
* Responsible for sending and receiving packets / messages between client and server.
*
*/
public class NetworkHelper
{
//---------------------------------------------------------------------
// Message Dispatch
//---------------------------------------------------------------------
/**
* Send custom info from zombies villagers when the player starts to track them.
* Mainly used to notify the client of the zombie villager profession, so it
* can render the correct skin.
*
* Server -> Client
*/
public static void sendVillagerProfessionMessage(int zombieId, ExtendedVillagerZombie properties, EntityPlayer target) {
if (zombieId > 0 && properties != null && properties.getProfession() >= 0)
{
MessageZombieVillagerProfession message = new MessageZombieVillagerProfession(zombieId, properties.getProfession());
// Debug
LogHelper.info("~~Sending Message - Zombie Profession~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the zombie extra info
ModVillagerTweaks.NetworkWrapper.sendTo(message, (EntityPlayerMP)target);
}
}
/**
* Send custom info about golems (iron and snow) when the player starts to track them.
* Mainly used to notify the client of the golem special enchantments, so it
* can render the correct particles / overlay.
*
* Server -> Client
*
*/
public static void sendEnchantedGolemInfoMessage(int golemId, ExtendedGolem properties, EntityPlayer target) {
if (golemId > 0 && properties != null) {
int[] ids = GolemEnchantment.convert(properties.getEnchantments());
if (ids.length > 0) {
MessageGolemEnchantments message = new MessageGolemEnchantments(golemId, ids);
// Debug
LogHelper.info("~~Sending Message - Enchanted Iron Golem info~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the golem extra info
ModVillagerTweaks.NetworkWrapper.sendTo(message, (EntityPlayerMP)target);
}
}
}
/**
* Send info about the golems (iron and snow) to all players around a certain radius of them.
*
* Server -> Client
*
*/
public static void sendEnchantedGolemInfoMessage(EntityLiving golem, ExtendedGolem properties) {
if (golem != null && properties != null) {
int[] ids = GolemEnchantment.convert(properties.getEnchantments());
if (ids.length > 0) {
MessageGolemEnchantments message = new MessageGolemEnchantments(golem.getEntityId(), ids);
TargetPoint target = new TargetPoint(golem.dimension, golem.posX, golem.posY, golem.posZ, 64.0D);
// Debug
LogHelper.info("~~Sending Message - Enchanted Iron Golem info~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the golem extra info
ModVillagerTweaks.NetworkWrapper.sendToAllAround(message, target);
}
}
}
//---------------------------------------------------------------------
// Message Receival
//---------------------------------------------------------------------
public static class VillagerProfessionHandler implements IMessageHandler<MessageZombieVillagerProfession, IMessage> {
@Override
public IMessage onMessage(MessageZombieVillagerProfession message, MessageContext ctx) {
// Debug
LogHelper.info("~~Receiving Message - Zombie Profession~~");
LogHelper.info(" " + message.toString());
if (message.getEntityID() > 0 && message.getProfession() >= 0) {
// Saves the info to be used later, when the entity actually loads
ClientInfoTracker.addZombieMessage(message);
// Attempts to sync the entity. Most of the times the entity won't be found
// when this code execute, but on some cases the entity can join the world
// before the packet is received (e.g. villager gets zombified).
ClientInfoTracker.SyncZombieMessage(message.getEntityID());
}
return null;
}
}
public static class GolemEnchantmentHandler implements IMessageHandler<MessageGolemEnchantments, IMessage> {
@Override
public IMessage onMessage(MessageGolemEnchantments message, MessageContext ctx)
{
// Debug
LogHelper.info("~~Receiving Message - Enchanted Iron Golem info~~");
LogHelper.info(" " + message.toString());
if (message.getEntityID() > 0) {
// Saves the info to be used later, when the entity actually loads
ClientInfoTracker.addGolemMessage(message);
// Attempts to sync the entity. Most of the times the entity won't be found
// when this code execute, but on some cases the entity can join the world
// before the packet is received (e.g. villager gets zombified).
ClientInfoTracker.SyncGolemMessage(message.getEntityID());
}
return null;
}
}
}
|
gpl-3.0
|
glamprou/bookings
|
lib/Database/Commands/TableNames.php
|
285
|
<?php
class TableNames
{
const RESERVATION_SERIES_ALIAS = 'rs';
const ACCESSORIES = 'accessories';
const GROUPS_ALIAS = 'g';
const RESERVATION_ACCESSORIES_ALIAS = 'ra';
const RESOURCES = 'resources';
const SCHEDULES = 'schedules';
const USERS = 'users';
}
?>
|
gpl-3.0
|
iomad/iomad
|
local/iomad_track/lib.php
|
3966
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package local_iomad_signup
* @copyright 2021 Derick Turner
* @author Derick Turner
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** Include required files */
require_once($CFG->libdir.'/filelib.php');
/**
* Form for editing HTML block instances.
*
* @copyright 2010 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package block_html
* @category files
* @param stdClass $course course object
* @param stdClass $birecord_or_cm block instance record
* @param stdClass $context context object
* @param string $filearea file area
* @param array $args extra arguments
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
* @return bool
* @todo MDL-36050 improve capability check on stick blocks, so we can check user capability before sending images.
*/
function local_iomad_track_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
global $DB, $CFG, $USER;
if ($context->contextlevel != CONTEXT_COURSE) {
send_file_not_found();
}
require_login();
if ($filearea !== 'issue') {
send_file_not_found();
}
$fs = get_file_storage();
$itemid = array_shift($args);
$filename = array_pop($args);
$filepath = $args ? '/'.implode('/', $args).'/' : '/';
if (!$file = $fs->get_file($context->id, 'local_iomad_track', 'issue', $itemid, $filepath, $filename) or $file->is_directory()) {
send_file_not_found();
}
// NOTE: it woudl be nice to have file revisions here, for now rely on standard file lifetime,
// do not lower it because the files are dispalyed very often.
\core\session\manager::write_close();
send_stored_file($file, null, 0, $forcedownload, $options);
}
/*
* Function to remove entries from the local_iomad_track table.
*
* @param boolean $full remove just the saved certificate or everything.
*/
function local_iomad_track_delete_entry($trackid, $full=false) {
global $DB,$CFG;
// Do we have a recorded certificate?
if ($cert = $DB->get_record('local_iomad_track_certs', array('trackid' => $trackid))) {
$DB->delete_records('local_iomad_track_certs', array('id' => $cert->id));
}
// Remove the actual underlying file.
if ($file = $DB->get_record_sql("SELECT * FROM {files}
WHERE component= :component
AND itemid = :itemid
AND filename != '.'",
array('component' => 'local_iomad_track', 'itemid' => $trackid))) {
$filedir1 = substr($file->contenthash,0,2);
$filedir2 = substr($file->contenthash,2,2);
$filepath = $CFG->dataroot . '/filedir/' . $filedir1 . '/' . $filedir2 . '/' . $file->contenthash;
unlink($filepath);
}
$DB->delete_records('files', array('itemid' => $trackid, 'component' => 'local_iomad_track'));
// Are we getting rid of the full record?
if ($full) {
$DB->delete_records('local_iomad_track', array('id' => $trackid));
}
}
|
gpl-3.0
|
justkarli/ShareX
|
ShareX/TaskManagement/TaskSettingsImage.cs
|
1230
|
using System.Collections.Generic;
using Newtonsoft.Json;
using ShareX.HelpersLib;
using ShareX.ImageEffectsLib;
namespace ShareX.TaskManagement
{
public class TaskSettingsImage
{
//#region Image / General
public EImageFormat ImageFormat = EImageFormat.PNG;
public int ImageJPEGQuality = 90;
public GIFQuality ImageGIFQuality = GIFQuality.Default;
public int ImageSizeLimit = 1024;
public EImageFormat ImageFormat2 = EImageFormat.JPEG;
public FileExistAction FileExistAction = FileExistAction.Ask;
//#endregion Image / General
//#region Image / Effects
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<ImageEffect> ImageEffects = ImageEffectManager.GetDefaultImageEffects();
public bool ShowImageEffectsWindowAfterCapture = false;
public bool ImageEffectOnlyRegionCapture = false;
//#endregion Image / Effects
//#region Image / Thumbnail
public int ThumbnailWidth = 200;
public int ThumbnailHeight = 0;
public string ThumbnailName = "-thumbnail";
public bool ThumbnailCheckSize = false;
//#endregion Image / Thumbnail
}
}
|
gpl-3.0
|
key-value/BankTransferSample
|
src/Program.cs
|
2645
|
using System;
using System.Reflection;
using BankTransferSample.Commands;
using BankTransferSample.Domain;
using BankTransferSample.DomainEvents;
using ECommon.Autofac;
using ECommon.Configurations;
using ECommon.Components;
using ECommon.JsonNet;
using ECommon.Log4Net;
using ECommon.Utilities;
using ENode.Commanding;
using ENode.Configurations;
using ENode.Eventing;
namespace BankTransferSample
{
class Program
{
static void Main(string[] args)
{
InitializeENodeFramework();
var commandService = ObjectContainer.Resolve<ICommandService>();
Console.WriteLine(string.Empty);
//创建两个银行账户
commandService.Execute(new CreateAccountCommand("00001", "雪华")).Wait();
commandService.Execute(new CreateAccountCommand("00002", "凯锋")).Wait();
Console.WriteLine(string.Empty);
//每个账户都存入1000元
commandService.StartProcess(new StartDepositTransactionCommand(ObjectId.GenerateNewStringId(), "00001", 1000)).Wait();
commandService.StartProcess(new StartDepositTransactionCommand(ObjectId.GenerateNewStringId(), "00002", 1000)).Wait();
Console.WriteLine(string.Empty);
//账户1向账户2转账300元
commandService.StartProcess(new StartTransferTransactionCommand(new TransferTransactionInfo(ObjectId.GenerateNewStringId(), "00001", "00002", 300D))).Wait();
Console.WriteLine(string.Empty);
//账户2向账户1转账500元
commandService.StartProcess(new StartTransferTransactionCommand(new TransferTransactionInfo(ObjectId.GenerateNewStringId(), "00002", "00001", 500D))).Wait();
Console.WriteLine(string.Empty);
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
static void InitializeENodeFramework()
{
var assemblies = new[] { Assembly.GetExecutingAssembly() };
Configuration
.Create()
.UseAutofac()
.RegisterCommonComponents()
.UseLog4Net()
.UseJsonNet()
.CreateENode()
.RegisterENodeComponents()
.SetProviders()
.RegisterBusinessComponents(assemblies)
.UseEQueue()
.InitializeBusinessAssemblies(assemblies)
.StartRetryCommandService()
.StartWaitingCommandService()
.StartEQueue();
Console.WriteLine("ENode framework started...");
}
}
}
|
gpl-3.0
|
joehillen/aura
|
src/Aura/Packages/AUR.hs
|
3208
|
-- Module for connecting to the AUR servers,
-- downloading PKGBUILDs and source tarballs, and handling them.
{-
Copyright 2012, 2013, 2014, 2015 Colin Woodbury <colingw@gmail.com>
This file is part of Aura.
Aura 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.
Aura 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 Aura. If not, see <http://www.gnu.org/licenses/>.
-}
module Aura.Packages.AUR
( aurLookup
, aurRepo
, isAurPackage
, sourceTarball
, aurInfo
, aurSearch
, pkgUrl
) where
import Control.Monad ((>=>),join)
import Data.Function (on)
import Data.List (sortBy)
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Traversable as Traversable (mapM)
import Linux.Arch.Aur
import System.FilePath ((</>))
import Aura.Monad.Aura
import Aura.Pkgbuild.Base
import Aura.Settings.Base
import Aura.Core
import Utilities (decompress)
import Internet
---
aurLookup :: String -> Aura (Maybe Buildable)
aurLookup name = fmap (makeBuildable name . T.unpack) <$> pkgbuild name
aurRepo :: Repository
aurRepo = Repository $ aurLookup >=> Traversable.mapM packageBuildable
makeBuildable :: String -> Pkgbuild -> Buildable
makeBuildable name pb = Buildable
{ baseNameOf = name
, pkgbuildOf = pb
, isExplicit = False
, buildScripts = f }
where f fp = sourceTarball fp (T.pack name) >>= Traversable.mapM decompress
isAurPackage :: String -> Aura Bool
isAurPackage name = isJust <$> pkgbuild name
----------------
-- AUR PKGBUILDS
----------------
aurLink :: String
aurLink = "https://aur4.archlinux.org"
pkgUrl :: String -> String
pkgUrl pkg = aurLink </> "packages" </> pkg
------------------
-- SOURCE TARBALLS
------------------
sourceTarball :: FilePath -- ^ Where to save the tarball.
-> T.Text -- ^ Package name.
-> IO (Maybe FilePath) -- ^ Saved tarball location.
sourceTarball path = fmap join . (info >=> Traversable.mapM f)
where f = saveUrlContents path . (++) aurLink . T.unpack . urlPathOf
------------
-- RPC CALLS
------------
sortAurInfo :: SortScheme -> [AurInfo] -> [AurInfo]
sortAurInfo scheme ai = sortBy compare' ai
where compare' = case scheme of
ByVote -> \x y -> compare (aurVotesOf y) (aurVotesOf x)
Alphabetically -> compare `on` aurNameOf
aurSearch :: T.Text -> Aura [AurInfo]
aurSearch regex = asks sortSchemeOf >>= \scheme ->
sortAurInfo scheme <$> search regex
aurInfo :: [T.Text] -> Aura [AurInfo]
aurInfo pkgs = sortAurInfo Alphabetically <$> multiinfo pkgs
|
gpl-3.0
|
d1eg0/simplertk
|
tests/test_ciclyc.c
|
3688
|
#include "../simplertk.h"
static float reference=2;
static float r=2;
struct data{
unsigned int sem;
unsigned long d;
unsigned long t;
unsigned int r;
};
struct data* d;
struct data* d2;
struct data* d3;
struct data* d4;
struct data* d5;
void taskprueba2(void *args){
d2=(struct data*)args;
d2->t = srtGetRelease();
d2->d = srtGetDeadline();
while(1){
//LATBbits.LATB10 ^=1;
if (d2->r == 1)
{
d2->r=2;
//LATBbits.LATB14 = 1;//Orange led switch on
}else{
d2->r=1;
//LATBbits.LATB14 = 0;//Orange led switch off
}
srtSleep(SECONDS2TICKS(0.06), SECONDS2TICKS(0.06));
}
}
void taskprueba3(void *args){
d3=(struct data*)args;
d3->t = srtGetRelease();
d3->d = srtGetDeadline();
while(1){
//LATBbits.LATB10 ^=1;
if (d3->r == 1)
{
d3->r=2;
//LATBbits.LATB14 = 1;//Orange led switch on
}else{
d3->r=1;
//LATBbits.LATB14 = 0;//Orange led switch off
}
srtSleep(SECONDS2TICKS(0.09), SECONDS2TICKS(0.09));
}
}
void taskprueba4(void *args){
d4=(struct data*)args;
d4->t = srtGetRelease();
d4->d = srtGetDeadline();
while(1){
//LATBbits.LATB10 ^=1;
if (d4->r == 1)
{
d4->r=2;
//LATBbits.LATB14 = 1;//Orange led switch on
}else{
d4->r=1;
//LATBbits.LATB14 = 0;//Orange led switch off
}
srtSleep(SECONDS2TICKS(0.07), SECONDS2TICKS(0.07));
}
}
void taskprueba5(void *args){
d5=(struct data*)args;
d5->t = srtGetRelease();
d5->d = srtGetDeadline();
while(1){
LATBbits.LATB10 ^=1;
if (d5->r == 1)
{
d5->r=2;
LATBbits.LATB14 = 1;//Orange led switch on
}else{
d5->r=1;
LATBbits.LATB14 = 0;//Orange led switch off
}
srtSleep(SECONDS2TICKS(0.08), SECONDS2TICKS(0.08));
}
}
void taskreference(void *args){
d=(struct data*)args;
d->t = srtGetRelease();
d->d = srtGetDeadline();
while(1){
//LATBbits.LATB10 ^=1;
if (reference == 1.0)
{
reference=2.0;
//LATBbits.LATB14 = 1;//Orange led switch on
}else{
reference=1.0;
//LATBbits.LATB14 = 0;//Orange led switch off
}
srtSleep(SECONDS2TICKS(0.05), SECONDS2TICKS(0.05));
}
}
struct data datos3,datos2, datos4,datos5,datos6;
int main(void)
{
datos2.sem=0;
datos2.r=2;
datos3.sem=0;
datos3.r=2;
datos4.sem=0;
datos4.r=2;
datos5.sem=0;
datos5.r=2;
datos6.sem=0;
datos6.r=2;
//pruebaargs(&datos);
/* set LEDs drive state low */
LATF &= 0xFFF0;
LATD &= 0xF0FF;
/* set LEDs pin as output */
TRISF &= 0xFFF0;
TRISD &= 0xF0FF;
// Led naranja
LATBbits.LATB14 = 0;
TRISBbits.TRISB14=0;
LATBbits.LATB14 = 0;
TRISDbits.TRISD1 = 0;
srtInitKernel(180);
srtCreateTask(taskprueba2, 100, SECONDS2TICKS(0.06), SECONDS2TICKS(0.06), &datos2);
srtCreateTask(taskprueba3, 100, SECONDS2TICKS(0.09), SECONDS2TICKS(0.09), &datos3);
srtCreateTask(taskprueba4, 100, SECONDS2TICKS(0.07), SECONDS2TICKS(0.07), &datos4);
srtCreateTask(taskprueba5, 100, SECONDS2TICKS(0.08), SECONDS2TICKS(0.08), &datos5);
srtCreateTask(taskreference, 100, SECONDS2TICKS(0.05), SECONDS2TICKS(0.05), &datos6);
//trtCreateTask(taskcontroller, 100, SECONDS2TICKS(0.050), SECONDS2TICKS(0.050), &datos2);
//trtCreateTask(tasksend, 100, SECONDS2TICKS(0.1), SECONDS2TICKS(0.01), &datos3);
// trtCreateTask(prueba4, 100, SECONDS2TICKS(0.03), SECONDS2TICKS(0.05), &datos4);
// trtCreateTask(prueba5, 100, SECONDS2TICKS(0.02), SECONDS2TICKS(0.04), &datos5);
// trtCreateTask(prueba6, 100, SECONDS2TICKS(0.01), SECONDS2TICKS(0.03), &datos6);
while(1);
CloseTimer1();
}
|
gpl-3.0
|
rsommerard/rsgen
|
README.md
|
557
|
rsgen
=====
Simple template generator in CLI.
How it works ?
=====
This CLI application use Thor gem.
If you don't have Thor gem installed on your system, run "gem install thor"
To create a new html file called myHTMLFileName run "ruby rsgen.rb html myHTMLFileName"
If you want just an empty html file, run with "-e" or "--empty" option like this "ruby rsgen.rb html -e myHTMLFileName"
To create a new css file called myCSSFileName run "ruby rsgen.rb css myCSSFileName"
To create a new js file called myJSFileName run "ruby rsgen.rb js myJSFileName"
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/libraries/vendor/joomla/event/src/EventInterface.php
|
96
|
Joomla 3.6.4 = be7f77906288a07f69084e46680ff6e5
Joomla 3.4.8 = 96990e227c35c2adc8f1f42e2493f9c0
|
gpl-3.0
|
syspl/syspl
|
source/SyntaxTree/SymbolDeclaration.ts
|
1053
|
// Copyright (C) 2015, 2017 Simon Mika <simon@mika.se>
//
// This file is part of SysPL.
//
// SysPL 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.
//
// SysPL 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 SysPL. If not, see <http://www.gnu.org/licenses/>.
//
import { Utilities } from "@cogneco/mend"
import * as Tokens from "../Tokens"
import { Declaration } from "./Declaration"
import { Node } from "./Node"
export abstract class SymbolDeclaration extends Declaration {
constructor(symbol: string, tokens?: Utilities.Enumerable<Tokens.Substance> | Node) {
super(symbol, tokens)
}
}
|
gpl-3.0
|
axelmuhr/Helios-NG
|
tcpip/include/protocols/rwhod.h
|
961
|
/*
* rwho protocol packet format.
*/
struct outmp {
char out_line[8]; /* tty name */
char out_name[8]; /* user id */
long out_time; /* time on */
};
struct whod {
char wd_vers; /* protocol version # */
char wd_type; /* packet type, see below */
char wd_pad[2];
int wd_sendtime; /* time stamp by sender */
int wd_recvtime; /* time stamp applied by receiver */
char wd_hostname[32]; /* hosts's name */
int wd_loadav[3]; /* load average as in uptime */
int wd_boottime; /* time system booted */
struct whoent {
struct outmp we_utmp; /* active tty info */
int we_idle; /* tty idle time */
} wd_we[1024 / sizeof (struct whoent)];
};
#define WHODVERSION 1
#define WHODTYPE_STATUS 1 /* host status */
#define RWHODPORTNO 513
#define RWHODRUPTIME 0
#define RWHODRWHO 1
#define RWHO_MAXSIZE 16384
typedef struct rwhodpkt {
int type, len;
int who_offset;
char buff[RWHO_MAXSIZE];
} RWHODPKT;
#define RWHOVAR "RWHOSERVER"
|
gpl-3.0
|
Snailpower/IdontAmbulancecare
|
Newest/Assets/Scripts/New/DoorHandleScript.cs
|
1224
|
using UnityEngine;
using System.Collections;
public class DoorHandleScript : MonoBehaviour {
private Transform Target = null;
private Vector3 LookAtPos = Vector3.zero;
public Transform Joint;
void Start () {
}
void Update () {
if (Target != null)
{
//test with the vive if this works
LookAtPos = new Vector3(Target.position.x, Joint.position.y, Target.position.z);
Joint.LookAt(LookAtPos);
Joint.localEulerAngles = new Vector3(0, ClampAngle(Joint.localEulerAngles.y, 270, 90), 0);
}
}
public void SetTarget(Transform newTarget)
{
Target = newTarget;
}
public Transform GetTarget()
{
return Target;
}
float ClampAngle(float angle, float min, float max)
{
float returnAngle = 0;
while (angle > 180)
{
angle -= 360;
}
while (max > 180)
{
max -= 360;
}
while (min > 180)
{
min -= 360;
}
returnAngle = Mathf.Clamp(angle, min, max);
while (returnAngle < 0)
{
returnAngle += 360;
}
return returnAngle;
}
}
|
gpl-3.0
|
osv-team/osvcad
|
setup.py
|
2202
|
#!/usr/bin/env python
# coding: utf-8
"""setuptools based setup module"""
from setuptools import setup
# from setuptools import find_packages
# To use a consistent encoding
import codecs
from os import path
import osvcad
here = path.abspath(path.dirname(__file__))
# Get the long description from the README_SHORT file
with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name=osvcad.__name__,
version=osvcad.__version__,
description=osvcad.__description__,
long_description=long_description,
url=osvcad.__url__,
download_url=osvcad.__download_url__,
author=osvcad.__author__,
author_email=osvcad.__author_email__,
license=osvcad.__license__,
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Software Development',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
keywords=['OpenCascade', 'PythonOCC', 'ccad', 'CAD', 'parts', 'json'],
packages=['osvcad',
'osvcad.jupyter',
'osvcad.utils',
'osvcad.ui'],
install_requires=[],
# OCC, scipy and wx cannot be installed via pip
extras_require={'dev': [],
'test': ['pytest', 'coverage'], },
package_data={},
data_files=[('osvcad/ui/icons',
['osvcad/ui/icons/blue_folder.png',
'osvcad/ui/icons/file_icon.png',
'osvcad/ui/icons/folder.png',
'osvcad/ui/icons/green_folder.png',
'osvcad/ui/icons/open.png',
'osvcad/ui/icons/python_icon.png',
'osvcad/ui/icons/quit.png',
'osvcad/ui/icons/refresh.png',
'osvcad/ui/icons/save.png']),
('osvcad/ui',
['osvcad/ui/osvcad.ico',
'osvcad/ui/osvcadui.ini'])],
entry_points={},
scripts=['bin/osvcad-ui']
)
|
gpl-3.0
|
DevinDewitt/pyqt5
|
doc/html/api/qhelpenginecore.html
|
5273
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>QHelpEngineCore — PyQt 5.5 Reference Guide</title>
<link rel="stylesheet" href="../_static/classic.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '5.5',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="shortcut icon" href="../_static/logo_tn.ico"/>
<link rel="top" title="PyQt 5.5 Reference Guide" href="../index.html" />
<link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" />
<link rel="next" title="QHelpEvent" href="qhelpevent.html" />
<link rel="prev" title="QHelpEngine" href="qhelpengine.html" />
</head>
<body role="document">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="qhelpevent.html" title="QHelpEvent"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="qhelpengine.html" title="QHelpEngine"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5 Reference Guide</a> »</li>
<li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="qhelpenginecore">
<h1>QHelpEngineCore<a class="headerlink" href="#qhelpenginecore" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="PyQt5.QtHelp.QHelpEngineCore">
<em class="property">class </em><code class="descclassname">PyQt5.QtHelp.</code><code class="descname">QHelpEngineCore</code><a class="headerlink" href="#PyQt5.QtHelp.QHelpEngineCore" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference external" href="http://qt-project.org/doc/qt-5/qhelpenginecore.html">C++ documentation</a></p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../index.html">
<img class="logo" src="../_static/logo.png" alt="Logo"/>
</a></p>
<h4>Previous topic</h4>
<p class="topless"><a href="qhelpengine.html"
title="previous chapter">QHelpEngine</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="qhelpevent.html"
title="next chapter">QHelpEvent</a></p>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="qhelpevent.html" title="QHelpEvent"
>next</a> |</li>
<li class="right" >
<a href="qhelpengine.html" title="QHelpEngine"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5 Reference Guide</a> »</li>
<li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2015 Riverbank Computing Limited.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
</div>
</body>
</html>
|
gpl-3.0
|
mater06/LEGOChimaOnlineReloaded
|
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/IHierarchyData.cs
|
2771
|
// Decompiled with JetBrains decompiler
// Type: System.Web.UI.IHierarchyData
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
namespace System.Web.UI
{
/// <summary>
/// Exposes a node of a hierarchical data structure, including the node object and some properties that describe characteristics of the node. Objects that implement the <see cref="T:System.Web.UI.IHierarchyData"/> interface can be contained in <see cref="T:System.Web.UI.IHierarchicalEnumerable"/> collections, and are used by ASP.NET site navigation and data source controls.
/// </summary>
public interface IHierarchyData
{
/// <summary>
/// Indicates whether the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents has any child nodes.
/// </summary>
///
/// <returns>
/// true if the current node has child nodes; otherwise, false.
/// </returns>
bool HasChildren { get; }
/// <summary>
/// Gets the hierarchical path of the node.
/// </summary>
///
/// <returns>
/// A <see cref="T:System.String"/> that identifies the hierarchical path relative to the current node.
/// </returns>
string Path { get; }
/// <summary>
/// Gets the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Object"/> hierarchical data node object.
/// </returns>
object Item { get; }
/// <summary>
/// Gets the name of the type of <see cref="T:System.Object"/> contained in the <see cref="P:System.Web.UI.IHierarchyData.Item"/> property.
/// </summary>
///
/// <returns>
/// The name of the type of object that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.
/// </returns>
string Type { get; }
/// <summary>
/// Gets an enumeration object that represents all the child nodes of the current hierarchical node.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Web.UI.IHierarchicalEnumerable"/> collection of child nodes of the current hierarchical node.
/// </returns>
IHierarchicalEnumerable GetChildren();
/// <summary>
/// Gets an <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
/// </returns>
IHierarchyData GetParent();
}
}
|
gpl-3.0
|
UnstuckME/UnstuckME
|
UnstuckME/UnstuckMEServerGUI/GetAllOrganizations_Result.cs
|
616
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace UnstuckMEServerGUI
{
public partial class GetAllOrganizations_Result
{
public int MentorID { get; set; }
public string OrganizationName { get; set; }
}
}
|
gpl-3.0
|
fabrimaciel/colosoft
|
Excel/Colosoft.Excel/FORMULA2.cs
|
795
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Colosoft.Excel{
public partial class FORMULA : Record {
public FORMULA (Record a) : base (a) {
}
public UInt16 RowIndex;
public UInt16 ColIndex;
public UInt16 XFIndex;
public UInt64 Result;
public UInt16 OptionFlags;
public UInt32 Unused;
public Byte[] FormulaData;
public override void Decode () {
MemoryStream a = new MemoryStream (Data);
BinaryReader b = new BinaryReader (a);
this.RowIndex = b.ReadUInt16 ();
this.ColIndex = b.ReadUInt16 ();
this.XFIndex = b.ReadUInt16 ();
this.Result = b.ReadUInt64 ();
this.OptionFlags = b.ReadUInt16 ();
this.Unused = b.ReadUInt32 ();
this.FormulaData = b.ReadBytes ((int)(a.Length - a.Position));
}
}
}
|
gpl-3.0
|
mihailikus/cengen
|
tr.sh
|
113
|
lupdate CenGen.pro -ts cengen_ru.ts cengen_en.ts
linguist cengen_ru.ts
cp cengen_ru.qm ../cengen-build-desktop/
|
gpl-3.0
|
tomm/pioneer
|
data/factions/063_Dagger_Kingdoms.lua
|
1036
|
-- Copyright © 2008-2016 Pioneer Developers. See AUTHORS.txt for details
-- Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
local f = Faction:new('Dagger Kingdoms')
:description_short('Dagger Kingdoms')
:description('Very little is currently known about The Dagger Kingdoms')
:homeworld(35,58,58,2,9)
:foundingDate(3069)
:expansionRate(0.723071)
:military_name('Kingdoms Navy')
:police_name('Kingdoms Prefecture')
:colour(0.886275,0.380392,0.219608)
f:govtype_weight('LIBDEM', 100)
f:govtype_weight('CORPORATE', 69)
f:govtype_weight('SOCDEM', 69)
f:govtype_weight('PLUTOCRATIC', 48)
f:govtype_weight('COMMUNIST', 48)
f:govtype_weight('MILDICT1', 33)
f:govtype_weight('MILDICT2', 33)
f:illegal_goods_probability('LIVE_ANIMALS', 52)
f:illegal_goods_probability('ROBOTS', 100)
f:illegal_goods_probability('SLAVES', 100)
f:illegal_goods_probability('HAND_WEAPONS', 57)
f:illegal_goods_probability('NERVE_GAS', 40)
f:illegal_goods_probability('NARCOTICS', 100)
f:add_to_factions('Dagger Kingdoms')
|
gpl-3.0
|
JoseLoarca/twitterclient
|
TwitterClient/app/src/main/java/org/jcloarca/twitterclient/images/ImagesInteractor.java
|
155
|
package org.jcloarca.twitterclient.images;
/**
* Created by JCLoarca on 6/19/2016 1:38 AM.
*/
public interface ImagesInteractor {
void execute();
}
|
gpl-3.0
|
hcemreyilmaz/STM32_HAL_nRF24L01P
|
STM32F4xx_nRF24L01P_Driver/Inc/nRF24L01P.h
|
9566
|
#ifndef NRF24L01_H_
#define NRF24L01_H_
#include "stm32f4xx_hal.h"
#include "spi.h"
//Define some constans for nRF24L01PP
#define nRF_SPI_TIMEOUT 1000 // milliseconds
//Define the commands for operate the nRF24L01+
//For Commands table, take a look at nRF24L01+ Product Specification Page 51.
#define nRF_CMD_R_REGISTER 0x00 // Command for read register
#define nRF_CMD_W_REGISTER 0x20 // Command for write register
#define nRF_CMD_R_RX_PAYLOAD 0x61 // Command for read RX payload
#define nRF_CMD_W_TX_PAYLOAD 0xA0 // Command for write TX payload
#define nRF_CMD_FLUSH_TX 0xE1 // Command for flush TX FIFO
#define nRF_CMD_FLUSH_RX 0xE2 // Command for flush RX FIFO
#define nRF_CMD_REUSE_TX_PL 0xE3 // Command for reuse TX payload
#define nRF_CMD_R_RX_PL_WID 0x60 // Command for read RX payload width
#define nRF_CMD_W_ACK_PAYLOAD 0xA8 // Command for write payload to be transmitted with ACK packet
#define nRF_CMD_W_TX_PAYLOAD_NOACK 0xB0 // Command for disable AUTOACK on a specific packet
#define NOP 0xFF // No operation, might be used to read the STATUS register
//Define the register address for nRF24L01PP
#define nRF_CONFIG 0x00 // Configurate the status of transceiver, mode of CRC and the replay of transceiver status
#define nRF_EN_AA 0x01 // Enable the atuo-ack in all channels
#define nRF_EN_RXADDR 0x02 // Enable Rx Address
#define nRF_SETUP_AW 0x03 // Configurate the address width
#define nRF_SETUP_RETR 0x04 // Setup the retransmit
#define nRF_RF_CH 0x05 // Configurate the RF frequency
#define nRF_RF_SETUP 0x06 // Setup the rate of data, and transmit power
#define nRF_STATUS 0x07 //
#define nRF_OBSERVE_TX 0x08 //
#define nRF_CD 0x09 // Carrier detect
#define nRF_RX_ADDR_P0 0x0A // Receive address of channel 0
#define nRF_RX_ADDR_P1 0x0B // Receive address of channel 1
#define nRF_RX_ADDR_P2 0x0C // Receive address of channel 2
#define nRF_RX_ADDR_P3 0x0D // Receive address of channel 3
#define nRF_RX_ADDR_P4 0x0E // Receive address of channel 4
#define nRF_RX_ADDR_P5 0x0F // Receive address of channel 5
#define nRF_TX_ADDR 0x10 // Transmit address
#define nRF_RX_PW_P0 0x11 // Size of receive data in channel 0
#define nRF_RX_PW_P1 0x12 // Size of receive data in channel 1
#define nRF_RX_PW_P2 0x13 // Size of receive data in channel 2
#define nRF_RX_PW_P3 0x14 // Size of receive data in channel 3
#define nRF_RX_PW_P4 0x15 // Size of receive data in channel 4
#define nRF_RX_PW_P5 0x16 // Size of receive data in channel 5
#define nRF_FIFO_STATUS 0x17 // FIFO Status
#define nRF_DYNPD 0x1C // Dynamic Payload State for pipes
#define nRF_FEATURE 0x1D // FEATURE Register
typedef enum{
nRF_DATA_PIPE_0 = 0,
nRF_DATA_PIPE_1 = 1,
nRF_DATA_PIPE_2 = 2,
nRF_DATA_PIPE_3 = 3,
nRF_DATA_PIPE_4 = 4,
nRF_DATA_PIPE_5 = 5
} nRF_DATA_PIPE;
typedef enum{
nRF_RETX_DELAY_250uS = 0,
nRF_RETX_DELAY_500uS = 1,
nRF_RETX_DELAY_750uS = 2,
nRF_RETX_DELAY_1000uS = 3,
nRF_RETX_DELAY_1250uS = 4,
nRF_RETX_DELAY_1500uS = 5,
nRF_RETX_DELAY_1750uS = 6,
nRF_RETX_DELAY_2000uS = 7,
nRF_RETX_DELAY_2250uS = 8,
nRF_RETX_DELAY_2500uS = 9,
nRF_RETX_DELAY_2750uS = 10,
nRF_RETX_DELAY_3000uS = 11,
nRF_RETX_DELAY_3250uS = 12,
nRF_RETX_DELAY_3500uS = 13,
nRF_RETX_DELAY_3750uS = 14,
nRF_RETX_DELAY_4000uS = 15
} nRF_RETX_DELAY;
typedef enum{
nRF_RETX_DISABLED = 0,
nRF_RETX_COUNT_1 = 1,
nRF_RETX_COUNT_2 = 2,
nRF_RETX_COUNT_3 = 3,
nRF_RETX_COUNT_4 = 4,
nRF_RETX_COUNT_5 = 5,
nRF_RETX_COUNT_6 = 6,
nRF_RETX_COUNT_7 = 7,
nRF_RETX_COUNT_8 = 8,
nRF_RETX_COUNT_9 = 9,
nRF_RETX_COUNT_10 = 10,
nRF_RETX_COUNT_11 = 11,
nRF_RETX_COUNT_12 = 12,
nRF_RETX_COUNT_13 = 13,
nRF_RETX_COUNT_14 = 14,
nRF_RETX_COUNT_15 = 15
} nRF_RETX_COUNT;
typedef enum{
nRF_DATA_RATE_250KBPS = 1,
nRF_DATA_RATE_1MBPS = 0,
nRF_DATA_RATE_2MBPS = 2
} nRF_DATA_RATE;
typedef enum{
nRF_TX_PWR_M18dBm = 0,
nRF_TX_PWR_M12dBm = 1,
nRF_TX_PWR_M6dBm = 2,
nRF_TX_PWR_0dBm = 3
} nRF_TX_PWR;
typedef enum{
nRF_ADDR_WIDTH_3 = 1,
nRF_ADDR_WIDTH_4 = 2,
nRF_ADDR_WIDTH_5 = 3
} nRF_ADDR_WIDTH;
typedef enum{
nRF_CRC_WIDTH_BYTE = 0,
nRF_CRC_WIDTH_HALFWORD = 1
} nRF_CRC_WIDTH;
typedef enum{
nRF_STATE_TX = 0,
nRF_STATE_RX = 1
} nRF_TXRX_STATE;
typedef enum{
nRF_DISABLE = 0,
nRF_ENABLE = 1
} nRF_STATE;
typedef enum{
nRF_RXPW_1BYTE = 1,
nRF_RXPW_2BYTES = 2,
nRF_RXPW_3BYTES = 3,
nRF_RXPW_4BYTES = 4,
nRF_RXPW_5BYTES = 5,
nRF_RXPW_6BYTES = 6,
nRF_RXPW_7BYTES = 7,
nRF_RXPW_8BYTES = 8,
nRF_RXPW_9BYTES = 9,
nRF_RXPW_10BYTES = 10,
nRF_RXPW_11BYTES = 11,
nRF_RXPW_12BYTES = 12,
nRF_RXPW_13BYTES = 13,
nRF_RXPW_14BYTES = 14,
nRF_RXPW_15BYTES = 15,
nRF_RXPW_16BYTES = 16,
nRF_RXPW_17BYTES = 17,
nRF_RXPW_18BYTES = 18,
nRF_RXPW_19BYTES = 19,
nRF_RXPW_20BYTES = 20,
nRF_RXPW_21BYTES = 21,
nRF_RXPW_22BYTES = 22,
nRF_RXPW_23BYTES = 23,
nRF_RXPW_24BYTES = 24,
nRF_RXPW_25BYTES = 25,
nRF_RXPW_26BYTES = 26,
nRF_RXPW_27BYTES = 27,
nRF_RXPW_28BYTES = 28,
nRF_RXPW_29BYTES = 29,
nRF_RXPW_30BYTES = 30,
nRF_RXPW_31BYTES = 31,
nRF_RXPW_32BYTES = 32
} nRF_PRX_WIDTH;
typedef struct{
SPI_HandleTypeDef *hspi;
nRF_CRC_WIDTH CRC_Width;
nRF_ADDR_WIDTH ADDR_Width;
nRF_DATA_RATE Data_Rate;
nRF_TX_PWR TX_Power;
nRF_TXRX_STATE State;
uint8_t RF_Channel;
nRF_PRX_WIDTH PayloadWidth;
nRF_RETX_COUNT RetransmitCount;
nRF_RETX_DELAY RetransmitDelay;
uint8_t* RX_Address;
uint8_t* TX_Address;
uint8_t Busy;
uint8_t* RX_Buffer;
uint8_t* TX_Buffer;
GPIO_TypeDef* nRF_nSS_GPIO_PORT;
uint16_t nRF_nSS_GPIO_PIN;
GPIO_TypeDef* nRF_CE_GPIO_PORT;
uint16_t nRF_CE_GPIO_PIN;
} nRF24L01P;
/* ---- Function Prototypes ---- */
HAL_StatusTypeDef HAL_nRF24L01P_ReadRegister(nRF24L01P *nRF, uint8_t regAddr, uint8_t *pRegData);
HAL_StatusTypeDef HAL_nRF24L01P_WriteRegister(nRF24L01P *nRF, uint8_t regAddr, uint8_t *pRegData);
HAL_StatusTypeDef HAL_nRF24L01P_ReadRXPayload(nRF24L01P *nRF, uint8_t *pRegData);
HAL_StatusTypeDef HAL_nRF24L01P_WriteTXPayload(nRF24L01P *nRF, uint8_t *pRegData);
HAL_StatusTypeDef HAL_nRF24L01P_WriteTXPayloadACK(nRF24L01P *nRF, uint8_t *pRegData, nRF_DATA_PIPE Pipe);
HAL_StatusTypeDef HAL_nRF24L01P_FlushRX(nRF24L01P *nRF);
HAL_StatusTypeDef HAL_nRF24L01P_FlushTX(nRF24L01P *nRF);
HAL_StatusTypeDef HAL_nRF24L01P_SetDataRate(nRF24L01P *nRF, nRF_DATA_RATE Rate);
HAL_StatusTypeDef HAL_nRF24L01P_SetTXPower(nRF24L01P *nRF, nRF_TX_PWR Power);
HAL_StatusTypeDef HAL_nRF24L01P_SetContinuousWave(nRF24L01P *nRF, nRF_STATE ContWave);
HAL_StatusTypeDef HAL_nRF24L01P_ClearInterrupts(nRF24L01P *nRF);
HAL_StatusTypeDef HAL_nRF24L01P_SetRFChannel(nRF24L01P *nRF, uint8_t Channel);
HAL_StatusTypeDef HAL_nRF24L01P_SetRetransmissionCount(nRF24L01P *nRF, nRF_RETX_COUNT Count);
HAL_StatusTypeDef HAL_nRF24L01P_SetRetransmissionDelay(nRF24L01P *nRF, nRF_RETX_DELAY Delay);
HAL_StatusTypeDef HAL_nRF24L01P_SetAddressWidth(nRF24L01P *nRF, nRF_ADDR_WIDTH AddrWidth);
HAL_StatusTypeDef HAL_nRF24L01P_RXPipe(nRF24L01P *nRF, nRF_DATA_PIPE Pipe, nRF_STATE Pipe_State);
HAL_StatusTypeDef HAL_nRF24L01P_AutoACK(nRF24L01P *nRF, nRF_DATA_PIPE Pipe, nRF_STATE ACK_State);
HAL_StatusTypeDef HAL_nRF24L01P_CRC(nRF24L01P *nRF, nRF_STATE CRC_State);
HAL_StatusTypeDef HAL_nRF24L01P_SetCRCWidth(nRF24L01P *nRF, nRF_CRC_WIDTH CRC_Width);
HAL_StatusTypeDef HAL_nRF24L01P_PowerUP(nRF24L01P *nRF, nRF_STATE Power);
HAL_StatusTypeDef HAL_nRF24L01P_TXRX(nRF24L01P *nRF, nRF_TXRX_STATE TxRx_State);
HAL_StatusTypeDef HAL_nRF24L01P_RXDataReadyIRQ(nRF24L01P *nRF, nRF_STATE IRQ_State);
HAL_StatusTypeDef HAL_nRF24L01P_TXDataSentIRQ(nRF24L01P *nRF, nRF_STATE IRQ_State);
HAL_StatusTypeDef HAL_nRF24L01P_MaxReTransmitIRQ(nRF24L01P *nRF, nRF_STATE IRQ_State);
HAL_StatusTypeDef HAL_nRF24L01P_SetPRXAddress(nRF24L01P *nRF, uint8_t *pRegData, nRF_DATA_PIPE Pipe);
HAL_StatusTypeDef HAL_nRF24L01P_SetPTXAddress(nRF24L01P *nRF, uint8_t *pRegData);
HAL_StatusTypeDef HAL_nRF24L01P_SetPRXWidth(nRF24L01P *nRF, nRF_PRX_WIDTH Width, nRF_DATA_PIPE Pipe);
HAL_StatusTypeDef HAL_nRF24L01P_DynACK(nRF24L01P *nRF, nRF_STATE ACK_State);
HAL_StatusTypeDef HAL_nRF24L01P_ACKPayload(nRF24L01P *nRF, nRF_STATE ACK_State);
HAL_StatusTypeDef HAL_nRF24L01P_DynPayload(nRF24L01P *nRF, nRF_STATE DPL_State);
HAL_StatusTypeDef HAL_nRF24L01P_DPLPipe(nRF24L01P *nRF, nRF_DATA_PIPE Pipe, nRF_STATE DPL_State);
HAL_StatusTypeDef HAL_nRF24L01P_TransmitPacket(nRF24L01P *nRF, uint8_t *Data);
HAL_StatusTypeDef HAL_nRF24L01P_TransmitPacketACK(nRF24L01P *nRF, uint8_t *Data, nRF_DATA_PIPE Pipe);
HAL_StatusTypeDef HAL_nRF24L01P_ReceivePacket(nRF24L01P *nRF, uint8_t *Data);
HAL_StatusTypeDef HAL_nRF24L01P_IRQ_Handler(nRF24L01P *nRF);
HAL_StatusTypeDef HAL_nRF24L01P_Init(nRF24L01P *nRF);
HAL_StatusTypeDef HAL_nRF24L01P_SendCommand(nRF24L01P *nRF, uint8_t Command, uint8_t *TxBuffer, uint8_t *RxBuffer, uint8_t Size);
/* ---- LL Function Prototypes ---- */
void HAL_nRF24L01P_nSS_High(nRF24L01P *nRF);
void HAL_nRF24L01P_nSS_Low(nRF24L01P *nRF);
void HAL_nRF24L01P_CE_High(nRF24L01P *nRF);
void HAL_nRF24L01P_CE_Low(nRF24L01P *nRF);
#endif
|
gpl-3.0
|
amadibra/sipeg
|
Form_PLT453.php
|
9824
|
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="shortcut icon" href="images/icon/profile.png"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LAPORAN PELAKSANAAN PENUGASAN</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="bg">
<div id= "main">
<div id="header">
<div id="logo">
<h1><a href="http://www.pln.co.id">PT. PLN (Persero) </a> </h1>
<h2><a href="https://simdiklat.pln-pusdiklat.co.id/portal/"> Pusat Pendidikan dan Pelatihan </a></h2>
</div>
</div>
<div id="buttons">
<ul>
<?
include "inc/config.inc.php";
include "inc/function.inc.php";
include "inc/tools.inc.php";
$act = "Informasi Pegawai";
if(!ceksession($session, $act)) header("Location: errorsession.htm");
/* cari nipeg pengunjung */
$sql = "select user from $tbl_session where session='$session'";
$q = mysql_query($sql);
list($user) = mysql_fetch_row($q);
$sql1 = "select kd_posisi from $tbl_bio01 where nipeg='$user'";
$q1 = mysql_query($sql1);
list($kd_posisi) = mysql_fetch_row($q1);
print "
<li class=first><a href=info-pegawai.php?session=$session>Awal</a></li>
<li><a href=daftar-pegawai.php?session=$session>Daftar Pegawai</a></li>
<li><a href=cek-pegawai.php?session=$session&nipeg=$user&pos=$kd_posisi>Biodata</a></li>
<li><a href=ubah-data.php?session=$session>Koreksi Data</a></li>
<li><a href=Dozir.php?session=$session>Lihat Dosir</a></li>
<li><a href=Input_Restitusi.php?session=$session>Input Restitusi</a></li>
<li class='dropdown'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#'>Menu 1 <span class='caret'></span></a>
<ul class='dropdown-menu'>
<li><a href='#' style='color:black'>Form 4.1</a></li>
<li><a href='#' style='color:black'>Form 4.2</a></li>
</ul>
</li>
";
/* cari nipeg pengunjung */
$sql = "select user from $tbl_session where session='$session'";
$q = mysql_query($sql);
list($nipeg) = mysql_fetch_row($q);
/* cek apakah pengunjung adalah admin atau bukan */
$sql = "select nipeg from $tbl_admin where nipeg='$nipeg'";
$q = mysql_query($sql);
list($adadata) = mysql_fetch_row($q);
/* apabila admin, tambahan menu baru */
$sql = "select nipeg from admin_dosir where nipeg like '$adadata'";
$q = mysql_query($sql);
list($cek_nipeg) = mysql_fetch_row($q);
$sql = "select nipeg from super_admin where nipeg like '$adadata'";
$q = mysql_query($sql);
list($super) = mysql_fetch_row($q);
if($super != '') {
print "
<li><a href=daftar-pesan.php?session=$session>Daftar Pesan</a></li>
<li><a href=importSAP.php?session=$session>Import Data dari SAP</a></li>
";
}
if($cek_nipeg != ''){
print "
<li><a href=inputdozir1.php?session=$session>Input Dosir</a></li>
";
}
print "
<li><a href=logout.php?session=$session>Keluar</a></li>
";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbsipeg";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT nipeg FROM wig WHERE nipeg = '$user'";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT3.php?session=$session&user2=$user");
// output data of each row
// while($row = $result->fetch_assoc()) {
// echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
//}
} else {
//echo "0 results";
}
$sql2 = "SELECT kd_posisi FROM bio01 WHERE nipeg = '$user'";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT2.php?session=$session");
while($row = $result->fetch_assoc()) {
$posisi = $row["kd_posisi"];
$posisi = str_replace(" ","",$posisi);
}
} else {
//echo "0 results";
}
$sql2 = "SELECT wig.nipeg, bio01.kd_posisi
FROM bio01
INNER JOIN wig
ON bio01.nipeg=wig.nipeg;
";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT2.php?session=$session");
while($row = $result->fetch_assoc()) {
$nama = $row["kd_posisi"];
$array = str_split($nama);
$num_digits = strlen($array);
$jumlah ="";
for($i=0;$i<$num_digits;$i++)
{
$jumlah .= $array[$i];
}
$pengisi = $row["nipeg"];
if($jumlah == $posisi)
{
//header("Location: Form_PLT2.php?session=$session&user2=$pengisi");
}
else{}
}
} else {
}
?>
</ul></div>
<div class="container">
<br>
<div class="row">
<div class="col-md-5 col-md-offset-2"><b style="font-size:20px">LAPORAN PELAKSANAAN PENUGASAN</b></div>
</div>
<br>
<?php
echo '<form class="form-horizontal" method="post" action="insert_laporan_pelaksanaan.php?session='.$session.'">';
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbsipeg";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT plt FROM wig where nipeg = '$user2'";
$result2 = $conn->query($sql2);
echo '<div class="form-group">';
echo '<div class="col-sm-3">';
echo '<label for="sel1">PLT:</label>';
echo '<p class="form-control-static">';
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$jabatan = $row["plt"];
}
echo $jabatan;
echo '</p>';
echo '</div>';
echo '</div>';
}
$sql2 = "SELECT * FROM laporan_pelaksanaan where nipeg = '$user'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">JUDUL :</label>
</div>
<div class="form-group">
<div class="col-sm-5" >';
echo '<p class="form-control-static">'.$row["judul"].' </p></div></div>';
echo '<br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">ABSTRAK :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["abstrak"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">LATAR BELAKANG :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["latar_belakang"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-md-4 text-left">LAPORAN PENCAPAIAN WIG DAN LAG MEASURE :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["laporan_pencapaian"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">USULAN DAN REKOMENDASI :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["usulan_rekomendasi"].' </p></div></div>';
}
}
$sql = "SELECT feedback FROM laporan_pelaksanaan where nipeg = '$user2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="form-group">';
echo '<div class="col-sm-5">';
echo '<label for="exampleInputName2">Feedback : </label><br>';
echo $row['feedback'];
echo '</div>';
echo '</div>';
}
} else {
echo "0 results";
}
$status = null;
$sql = "SELECT status FROM laporan_pelaksanaan where nipeg = '$user2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($row["status"] == 0)
{
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-warning" name="tombol1" value="1" disabled="disabled">Belum Disetujui</button>';
echo '</div>';
}
else{
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-success" name="tombol1" value="0" disabled="disabled">Disetujui</button>';
echo '</div>';
}
}
} else {
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-warning" name="tombol1" value="1" disabled="disabled">Belum Disetujui</button>';
echo '</div>';
}
$conn->close();
?>
<br>
<!--div class="form-group">
<div class="col-sm-5">
<label for="exampleInputName2">Nomor Induk Pegawai</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Nipeg Anda" name="nipeg">
</div>
</div-->
<input type="submit" name="Submit" value="Next" />
</form>
</div>
</div>
</div>
</body>
<script>
var nomor = 4;
function add()
{
$("#tambah").append(' <div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label"> '+nomor+' :</label><div class="col-sm-5" ><textarea type="text" class="form-control" placeholder="Text input" name="lmw1'+nomor+'"></textarea></div></div>');
nomor++;
}
var nomor2 = 4;
function add2()
{
$("#tambah2").append(' <div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label"> '+nomor2+' :</label><div class="col-sm-5" ><textarea type="text" class="form-control" placeholder="Text input" name="lmw2'+nomor2+'"></textarea></div></div>');
nomor2++;
}
</script>
</html>
|
gpl-3.0
|
YongbaoWang/Doctor
|
Doctor/MainTableViewCell.h
|
355
|
//
// MainTableViewCell.h
// Doctor
//
// Created by Ever on 15/3/19.
// Copyright (c) 2015年 Ever. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MainTableViewCell : UITableViewCell
{
UIImageView *_imageView;
UILabel *_titleLbl;
}
@property(nonatomic,assign)NSInteger index ;
@property(nonatomic,strong)NSString *title;
@end
|
gpl-3.0
|
pstiasny/VITABS
|
vitabs/editor.py
|
20458
|
# Copyright (C) 2011 Pawel Stiasny
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import curses
import locale
import pickle
import os
import os.path
from fractions import Fraction
from .tablature import Fret, Chord, Bar, Tablature, ChordRange
from . import symbols
from . import music
from .player import Player
locale.setlocale(locale.LC_ALL, '')
encoding = locale.getpreferredencoding()
class Editor:
screen_initiated = False
cursor_prev_bar_x = 2
insert_duration = Fraction('1/4')
st = ''
file_name = None
terminate = False
visible_meta = 'meter'
continuous_playback = False
yanked_bar = None
string = 0
def __init__(self, stdscr, tab = Tablature()):
self.root = stdscr
self.tab = tab
self.nmap = {}
self.motion_commands = {}
self.commands = {}
self.player = Player()
def init_screen(self):
screen_height, screen_width = self.root.getmaxyx()
self.stdscr = curses.newwin(screen_height - 1, 0, 0, 0)
self.stdscr.keypad(1)
if self.file_name:
self.set_term_title(self.file_name + ' - VITABS')
else:
self.set_term_title('[unnamed] - VITABS')
self.status_line = curses.newwin(0, 0, screen_height - 1, 0)
self.status_line.scrollok(False)
self.first_visible_bar = self.tab.cursor_bar
self.redraw_view()
self.cy = 2
self.move_cursor()
curses.doupdate()
self.screen_initiated = True
def make_motion_cmd(self, f):
'''Turn a motion command into a normal mode command'''
def motion_wrap(ed, num):
m = f(ed, num)
if m is not None:
ed.make_motion(f(ed, num))
motion_wrap.__name__ = f.__name__
motion_wrap.__doc__ = f.__doc__
motion_wrap.nosidefx = True
return motion_wrap
def mark_changed(self):
if not getattr(self.tab, 'changed', False):
if self.file_name:
self.set_term_title(self.file_name + ' + - VITABS')
else:
self.set_term_title('[unnamed] + - VITABS')
self.tab.changed = True
def register_handlers(self, module):
'''Add commands defined in the module'''
for f in module.__dict__.values():
if hasattr(f, 'normal_keys'):
if getattr(f, 'motion_command', False):
for k in f.normal_keys:
self.nmap[k] = self.make_motion_cmd(f)
self.motion_commands[k] = f
else:
for k in f.normal_keys:
self.nmap[k] = f
if hasattr(f, 'handles_command'):
self.commands[f.handles_command] = f
def load_tablature(self, filename):
'''Unpickle tab from a file'''
try:
if os.path.isfile(filename):
infile = open(filename, 'rb')
self.tab = pickle.load(infile)
infile.close()
else:
self.tab = Tablature()
self.file_name = filename
self.set_term_title(filename + ' - VITABS')
self.st = '{0} ({1} bars, tuning: {2})'.format(
filename, len(self.tab.bars),
music.tuning_str(getattr(self.tab, 'tuning', music.standard_E)))
except:
self.st = 'Error: Can\'t open the specified file'
def save_tablature(self, filename):
'''Pickle tab to a file'''
if hasattr(self.tab, 'changed'):
self.tab.changed = False
delattr(self.tab, 'changed')
try:
outfile = open(filename, 'wb')
pickle.dump(self.tab, outfile)
outfile.close()
self.file_name = filename
except:
self.st = 'Error: Can\'t save'
self.set_term_title(filename + ' - VITABS')
def set_term_title(self, text):
'''Atempt to change virtual terminal window title'''
import sys
try:
term = os.environ['TERM']
if 'xterm' in term or 'rxvt' in term:
sys.stdout.write('\033]0;' + text + '\007')
sys.stdout.flush()
except:
pass
def draw_bar(self, y, x, bar):
'''Render a single bar at specified position'''
stdscr = self.stdscr
screen_width = self.stdscr.getmaxyx()[1]
stdscr.vline(y, x - 1, curses.ACS_VLINE, 6)
gcd = bar.gcd()
total_width = bar.total_width(gcd)
for i in range(6):
stdscr.hline(y + i, x, curses.ACS_HLINE, total_width)
x += 1
for chord in bar.chords:
for i in list(chord.strings.keys()):
if x < screen_width:
stdscr.addstr(y+i, x, str(chord.strings[i]), curses.A_BOLD)
# should it really be here?
if self.visible_meta == 'length':
dstr = music.len_str(chord.duration)
if x + len(dstr) < screen_width:
stdscr.addstr(y - 1, x, dstr)
width = int(chord.duration / gcd)
x = x + width*2 + 1
if x + 1 < screen_width:
stdscr.vline(y, x + 1, curses.ACS_VLINE, 6)
return x + 2
def draw_bar_meta(self, y, x, bar, prev_bar, index):
'''Print additional bar info at specified position'''
if self.visible_meta == 'meter':
if (prev_bar == None
or bar.sig_num != prev_bar.sig_num
or bar.sig_den != prev_bar.sig_den):
self.stdscr.addstr(
y, x,
str(bar.sig_num) + '/' + str(bar.sig_den))
elif self.visible_meta == 'number':
self.stdscr.addstr(y, x, str(index))
elif self.visible_meta == 'label':
if hasattr(bar, 'label'):
self.stdscr.addstr(y, x, bar.label)
def draw_tab(self, t):
'''Render the whole tablature'''
x = 2
y = 1
prev_bar = None
screen_height, screen_width = self.stdscr.getmaxyx()
for i, tbar in enumerate(t.bars[self.first_visible_bar - 1 : ]):
bar_width = tbar.total_width(tbar.gcd())
if x + bar_width >= screen_width and x != 2:
x = 2
y += 8
if y + 8 > screen_height:
break
self.draw_bar_meta(y, x, tbar, prev_bar, self.first_visible_bar + i)
x = self.draw_bar(y + 1, x, tbar)
self.last_visible_bar = i + self.first_visible_bar
prev_bar = tbar
def redraw_view(self):
'''Redraw tab window'''
self.stdscr.erase()
self.draw_tab(self.tab) # merge theese functions?
self.stdscr.noutrefresh()
def term_resized(self):
'''Called when the terminal window is resized, updates window sizes'''
height, width = self.root.getmaxyx()
self.status_line.mvwin(height - 1, 0)
self.stdscr.resize(height - 1, width)
self.redraw_view()
self.move_cursor()
def redraw_status(self):
'''Update status bar'''
width = self.status_line.getmaxyx()[1]
self.status_line.erase()
# general purpose status line
self.status_line.addstr(0, 0, self.st)
# position indicator
self.status_line.addstr(
0, width - 8,
'{0},{1}'.format(self.tab.cursor_bar, self.tab.cursor_chord))
# note length indicator
self.status_line.addstr(
0, width - 16,
str(self.tab.get_cursor_chord().duration))
# meter incomplete indicator
cb = self.tab.get_cursor_bar()
if cb.real_duration() != cb.required_duration():
self.status_line.addstr(0, width - 18, 'M')
self.status_line.noutrefresh()
def pager(self, lines):
'''Display a list of lines in a paged fashion'''
self.root.scrollok(True)
self.root.clear()
i = 0
h = self.root.getmaxyx()[0]
for line in lines:
self.root.addstr(i, 1, line)
i += 1
if i == h - 1:
self.root.addstr(i, 0, '<Space> NEXT PAGE')
self.root.refresh()
while self.get_char() != ord(' '): pass
self.root.clear()
i = 0
self.root.addstr(h - 1, 0, '<Space> CONTINUE')
while self.get_char(self.root) != ord(' '): pass
self.root.scrollok(False)
self.root.clear()
self.redraw_view()
def move_cursor(self, new_bar=None, new_chord=None, cache_lengths=False):
'''Set new cursor position'''
if not new_bar: new_bar = self.tab.cursor_bar
if not new_chord: new_chord = self.tab.cursor_chord
if not cache_lengths: self.cursor_prev_bar_x = None
# make sure the cursor stays inside the visible bar range
if new_bar < self.first_visible_bar or new_bar > self.last_visible_bar:
self.first_visible_bar = new_bar
self.redraw_view()
newbar_i = self.tab.bars[new_bar - 1]
# calculate the width of preceeding bars
screen_height, screen_width = self.stdscr.getmaxyx()
if new_bar != self.tab.cursor_bar or self.cursor_prev_bar_x == None:
self.cursor_prev_bar_x = 2
self.cy = 2
if new_bar > self.first_visible_bar:
for b in self.tab.bars[self.first_visible_bar - 1 : new_bar - 1]:
barw = b.total_width(b.gcd()) + 1
self.cursor_prev_bar_x += barw
if (self.cursor_prev_bar_x > screen_width and
self.cursor_prev_bar_x != 2 + barw):
self.cursor_prev_bar_x = 2 + barw
self.cy += 8
# should the cursor bar be wrapped?
newbar_w = newbar_i.total_width(newbar_i.gcd()) + 1
if newbar_w + self.cursor_prev_bar_x > screen_width:
self.cursor_prev_bar_x = 2
self.cy += 8
# width of preceeding chords
offset = 1
gcd = newbar_i.gcd()
for c in newbar_i.chords[:new_chord - 1]:
offset += int(c.duration / gcd)*2 + 1
self.tab.cursor_bar = new_bar
self.tab.cursor_chord = new_chord
self.cx = self.cursor_prev_bar_x + offset
def make_motion(self, pos):
self.move_cursor(pos[0], 1 if pos[1] is None else pos[1],
cache_lengths=True)
def go_left(self, num=1):
'''Returns position pair [num] chords left from the cursor'''
if self.tab.cursor_chord <= num:
if self.tab.cursor_bar > 1:
return (self.tab.cursor_bar - 1,
len(self.tab.bars[self.tab.cursor_bar - 2].chords))
else:
return (1, 1)
else:
return (self.tab.cursor_bar, self.tab.cursor_chord - num)
def move_cursor_left(self):
self.make_motion(self.go_left())
def go_right(self, num=1):
'''Returns position pair [num] chords right from the cursor'''
if self.tab.cursor_chord + num > len(self.tab.get_cursor_bar().chords):
if self.tab.cursor_bar < len(self.tab.bars):
return (self.tab.cursor_bar + 1, 1)
else:
return self.tab.last_position()
else:
return (self.tab.cursor_bar, self.tab.cursor_chord + num)
def move_cursor_right(self):
self.make_motion(self.go_right())
def play_range(self, fro, to):
def redraw_playback_status():
self.st = 'Playing... <CTRL-C> to abort'
self.redraw_status()
curses.setsyx(self.cy - 1, self.cx)
curses.doupdate()
def move_to_beginning():
self.move_cursor(fro[0], fro[1])
redraw_playback_status()
return True
def update_playback_status():
self.move_cursor_right()
redraw_playback_status()
return True
p = self.player
p.before_repeat = move_to_beginning
p.post_play_chord = update_playback_status
p.set_instrument(getattr(self.tab, 'instrument', 24))
p.play(ChordRange(self.tab, fro, to), self.continuous_playback)
self.st = ''
def get_char(self, parent=None):
'''Get a character from terminal, handling things like terminal
resize'''
if parent is None:
parent = self.stdscr
c = parent.getch()
if c == curses.KEY_RESIZE:
self.term_resized()
return c
def insert_mode(self, free_motion=False):
'''Switch to insert mode and listen for keys'''
if free_motion:
self.st = '-- REPLACE --'
else:
self.st = '-- INSERT --'
self.redraw_view()
insert_beg = self.tab.cursor_position()
insert_end = insert_beg
while True:
self.redraw_status()
curses.setsyx(self.cy + self.string, self.cx)
curses.doupdate()
c = self.get_char()
if c == 27: # ESCAPE
self.st = ''
break
elif ord('0') <= c <= ord('9'):
curch = self.tab.get_cursor_chord()
string = self.string
if string in curch.strings and curch.strings[string].fret < 10:
st_dec = curch.strings[string].fret * 10
curch.strings[string].fret = st_dec + c - ord('0')
else:
curch.strings[string] = Fret(c - ord('0'))
self.redraw_view()
elif c == curses.KEY_DC or c == ord('x'):
if self.string in self.tab.get_cursor_chord().strings:
del self.tab.get_cursor_chord().strings[self.string]
self.redraw_view()
elif c == curses.KEY_UP or c == ord('k'):
self.string = max(self.string - 1, 0)
elif c == curses.KEY_DOWN or c == ord('j'):
self.string = min(self.string + 1, 5)
elif c == ord('E'): self.string = 5
elif c == ord('A'): self.string = 4
elif c == ord('D'): self.string = 3
elif c == ord('G'): self.string = 2
elif c == ord('B'): self.string = 1
elif c == ord('e'): self.string = 0
elif c == ord(' '):
# TODO: don't repeat yourself...
self.tab.get_cursor_bar().chords.insert(
self.tab.cursor_chord,
Chord(self.insert_duration))
self.redraw_view()
self.move_cursor_right()
self.move_cursor()
insert_end = (insert_end[0], insert_end[1] + 1)
elif (c == curses.KEY_RIGHT or c == ord('l')) and not free_motion:
right = (self.tab.cursor_bar, self.tab.cursor_chord + 1)
if right > insert_end:
self.tab.get_cursor_bar().chords.insert(
self.tab.cursor_chord,
Chord(self.insert_duration))
self.redraw_view()
insert_end = right
self.make_motion(right)
self.move_cursor()
elif (c == curses.KEY_LEFT or c == ord('h')) and not free_motion:
left = self.go_left()
if left >= insert_beg:
self.make_motion(left)
elif c == curses.KEY_RIGHT or c == ord('l') and free_motion:
self.move_cursor_right()
elif (c == curses.KEY_LEFT or c == ord('h')) and free_motion:
self.move_cursor_left()
try:
# try to find a symbol in key -> symbol dict
sym = symbols.keys[c]
fr = self.tab.get_cursor_chord().strings[self.string]
if sym in fr.symbols:
fr.symbols.remove(sym)
else:
fr.symbols.append(sym)
self.redraw_view()
except KeyError:
pass
def exec_command(self, args, apply_to=None):
cmd = args[0]
try:
if apply_to is not None:
try:
self.commands[cmd](self, args, apply_to=apply_to)
except TypeError:
self.st = 'Command does not accept range'
else:
self.commands[cmd](self, args)
except KeyError:
self.st = 'Invalid command'
def command_mode(self):
'''Read a command'''
import sys
curses.echo()
self.status_line.erase()
self.status_line.addstr(0, 0, ":")
try:
line = self.status_line.getstr(0, 1).decode(encoding)
except KeyboardInterrupt:
line = ''
words = line.split(' ')
cmd = words[0]
curses.noecho()
if cmd:
try:
self.exec_command(words)
except:
exc = sys.exc_info()
self.st = "Exception: " + str(exc[0].__name__) + ": " + \
str(exc[1])
self.redraw_view()
def _is_number(self, char):
return (ord('0') <= char <= ord('9'))
def _parse_numeric_arg(self, c, num_arg):
if num_arg:
num_arg = num_arg * 10 + c - ord('0')
elif c != ord('0'):
num_arg = c - ord('0')
return num_arg
def expect_range(self, num=None, whole_bar_cmd=None):
'''Get a motion command and return a range from cursor position to
motion'''
num_motion = None
c = self.get_char()
while self._is_number(c) and (c != ord('0') or num_motion):
num_motion = self._parse_numeric_arg(c, num_motion)
c = self.get_char()
if num_motion and num: total_num = num * num_motion
elif num_motion: total_num = num_motion
else: total_num = num
cur = self.tab.cursor_position()
if whole_bar_cmd and c == whole_bar_cmd:
return ChordRange(self.tab,
(cur[0], 1),
(cur[0], None))
try:
dest = self.motion_commands[c](self, total_num)
if dest:
if dest > cur:
return ChordRange(self.tab, cur, dest)
else:
return ChordRange(self.tab, dest, cur)
except KeyError:
return None
def normal_mode(self):
'''Enter normal mode, returns on quit'''
num_arg = None
t = self.tab
while True:
if self.terminate:
break
self.redraw_status()
self.st = ''
curses.setsyx(self.cy - 1, self.cx)
curses.doupdate()
# TODO: accept multi-char commands
try:
c = self.get_char()
if c in self.nmap:
cmd = self.nmap[c]
cmd(self, num_arg)
if not (getattr(cmd, 'nosidefx', False)):
self.mark_changed()
self.redraw_view()
if self._is_number(c):
num_arg = self._parse_numeric_arg(c, num_arg)
if num_arg: self.st = str(num_arg)
else:
# reset after a command
num_arg = None
if c == 27: # ESCAPE
self.st = ''
except KeyboardInterrupt:
self.st = 'Use :q<Enter> to quit'
|
gpl-3.0
|
boompieman/iim_project
|
nxt_1.4.4/apidoc/net/sourceforge/nite/nom/link/package-frame.html
|
1239
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_91) on Sat Mar 19 01:50:16 CST 2016 -->
<title>net.sourceforge.nite.nom.link</title>
<meta name="date" content="2016-03-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../net/sourceforge/nite/nom/link/package-summary.html" target="classFrame">net.sourceforge.nite.nom.link</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="NOMControl.html" title="interface in net.sourceforge.nite.nom.link" target="classFrame"><i>NOMControl</i></a></li>
<li><a href="NOMEdit.html" title="interface in net.sourceforge.nite.nom.link" target="classFrame"><i>NOMEdit</i></a></li>
<li><a href="NOMView.html" title="interface in net.sourceforge.nite.nom.link" target="classFrame"><i>NOMView</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="DefaultEdit.html" title="class in net.sourceforge.nite.nom.link" target="classFrame">DefaultEdit</a></li>
</ul>
</div>
</body>
</html>
|
gpl-3.0
|
nsol-nmsu/ndnSIM
|
docs/icens/latex/classnfd_1_1FaceStatusPublisher.tex
|
2011
|
\hypertarget{classnfd_1_1FaceStatusPublisher}{}\section{nfd\+:\+:Face\+Status\+Publisher Class Reference}
\label{classnfd_1_1FaceStatusPublisher}\index{nfd\+::\+Face\+Status\+Publisher@{nfd\+::\+Face\+Status\+Publisher}}
Inheritance diagram for nfd\+:\+:Face\+Status\+Publisher\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=3.000000cm]{classnfd_1_1FaceStatusPublisher}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
{\bfseries Face\+Status\+Publisher} (const \hyperlink{classnfd_1_1FaceTable}{Face\+Table} \&face\+Table, \hyperlink{classnfd_1_1AppFace}{App\+Face} \&face, const \hyperlink{classndn_1_1Name}{Name} \&prefix, \hyperlink{classndn_1_1security_1_1KeyChain}{ndn\+::\+Key\+Chain} \&key\+Chain)\hypertarget{classnfd_1_1FaceStatusPublisher_a0f9c66d45d7e714f176e964fb423c9ab}{}\label{classnfd_1_1FaceStatusPublisher_a0f9c66d45d7e714f176e964fb423c9ab}
\end{DoxyCompactItemize}
\subsection*{Protected Member Functions}
\begin{DoxyCompactItemize}
\item
virtual size\+\_\+t \hyperlink{classnfd_1_1FaceStatusPublisher_a9f266d532a5019548b8e422e99576afb}{generate} (ndn\+::\+Encoding\+Buffer \&out\+Buffer)\hypertarget{classnfd_1_1FaceStatusPublisher_a9f266d532a5019548b8e422e99576afb}{}\label{classnfd_1_1FaceStatusPublisher_a9f266d532a5019548b8e422e99576afb}
\begin{DoxyCompactList}\small\item\em In a derived class, write the octets into out\+Buffer. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}
\subsection{Detailed Description}
Definition at line 36 of file face-\/status-\/publisher.\+hpp.
The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
/home/network/\+N\+S\+O\+L/ndn\+S\+I\+M-\/dev/ns-\/3/src/ndn\+S\+I\+M/\+N\+F\+D/daemon/mgmt/face-\/status-\/publisher.\+hpp\item
/home/network/\+N\+S\+O\+L/ndn\+S\+I\+M-\/dev/ns-\/3/src/ndn\+S\+I\+M/\+N\+F\+D/daemon/mgmt/face-\/status-\/publisher.\+cpp\end{DoxyCompactItemize}
|
gpl-3.0
|
darklukee/poziomica
|
inc/aTask.hpp
|
1061
|
/*
* myTask.hpp
*
* Created on: 10-11-2012
* Author: lukee
*/
#ifndef ATASK_HPP_
#define ATASK_HPP_
#include "stm32f4xx.h"
/* FreeRTOS includes */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
//my include
#include "hw_config.h"
#include "math.h"
static const uint8_t queueSIZE = 6;
extern "C" void vBALANCETask(void *pvParameters);
extern "C++"
{
class CBalance
{
private:
static const uint16_t N = 32; //table size
static const float a, b, c, d; //exponential coefficients
float accelXFloat, accelYFloat;
int8_t meanX[N], meanY[N];
int16_t meanXSigma, meanYSigma, accelX, accelY;
int16_t accelXCal, accelYCal;
static const uint8_t maxValue; //maksymalna wartosc wskazania przy wychyleniu 90st
static const uint8_t cmpValue; //wartosc do porownywania przyspieszenia
uint16_t k, j;
//void GetData(void);
static int temp;
public:
int8_t xBuffer_receive[queueSIZE]; //bufor wejsciowy
CBalance(void);
//~CBalance(void);
void Calibrate(void);
void Calculate(void);
void SetData(void);
};
}
#endif /* ATASK_HPP_ */
|
gpl-3.0
|
diracmcpn/ApiLibertyReserve
|
documentation/doc.html
|
5340
|
<!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" xml:lang="en">
<head>
<title>Free Liberty Reserve Module</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="doc.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="title">Liberty Reserve Module<br/></h1>
<p>
The Liberty Reserve module uses <a href="http://www.libertyreserve.com/en/help/programmatic-access/api/">the Liberty Reserve's XML API</a>.<a href="#details"> More ...</a><br/>
</p>
<h2>Classes</h2>
<p>
<table width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd">
<th><a href="class/account.html">Account</a></th>
<td>Base class as a part of authentification</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/accountname.html">AccountName</a></th>
<td>Used in the parse of an AccountNameResponse</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/accountnameoperation.html">AccountNameOperation</a></th>
<td>Base class for every account name operation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/accountnamerequest.html">AccountNameRequest</a></th>
<td>Create request for one or several AccountNameOperation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/accountnameresponse.html">AccountNameResponse</a></th>
<td>Base class for the response of an AccountNameRequest</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/balance.html">Balance</a></th>
<td>Used in the parse of a BalanceResponse</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/balanceoperation.html">BalanceOperation</a></th>
<td>Base class for every balance operation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/balancerequest.html">BalanceRequest</a></th>
<td>Create request for one or several BalanceOperation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/balanceresponse.html">BalanceResponse</a></th>
<td>Base class for the response of a BalanceRequest</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/error.html">Error</a></th>
<td>Base class used in the parse of any response for errors</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/historyoperation.html">HistoryOperation</a></th>
<td>Base class for every history operation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/historyrequest.html">HistoryRequest</a></th>
<td>Create request for one HistoryOperation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/historyresponse.html">HistoryResponse</a></th>
<td>Used in the parse of a HistoryResponse</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/id.html">Id</a></th>
<td>Used to yield an identity as a part of authentification for every request</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/merchantref.html">MerchantRef</a></th>
<td>Used to yield a merchant reference for a TransferOperation</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/pager.html">Pager</a></th>
<td>Used in the parse of a HistoryResponse</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/processor.html">Processor</a></th>
<td>Process requests and responses for transfer, history, balance and accountname operations</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/receipt.html">Receipt</a></th>
<td>Base class used in the parse of a TransferResponse</td>
</tr>
<tr valign="top" class="even">
<th><a href="class/transferoperation.html">TransferOperation</a></th>
<td>Base class for every transfer operation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/transferrequest.html">TransferRequest</a></th>
<td>Create request for one or several TransferOperation</td>
</tr>
<tr valign="top" class="odd">
<th><a href="class/transferresponse.html">TransferResponse</a></th>
<td>Base class for the response of a TransferRequest</td>
</tr>
</table>
</p>
<a name="details"></a>
<h2>Detailed Description</h2>
<p>
It enables to communicate between Liberty Reserve accounts sending and receiving payments, receiving informations about incoming and outgoing payments, obtaining history of performed actions and receiving informations about Liberty Reserve accounts.<br/>
Required DOM class from php 5.
</p>
<address>
<hr/>
<div align="center">
<table width="100%" cellspacing="0" border="0">
<tr class="address">
<td width="40%" align="left">Copyright © 2010 Dirac</td>
<td width="20%" align="center"><a href="../LICENCE.txt">GNU General Public License</a></td>
<td width="40%" align="right"><div align="right">Free Liberty Reserve Module</div></td>
</tr>
</table>
</div>
</address>
</body>
</html>
|
gpl-3.0
|
esetomo/mio
|
include/mio/material/material.h
|
416
|
#ifndef __MIO_MATERIAL_MATERIAL_H__
#define __MIO_MATERIAL_MATERIAL_H__
#include <mio/mio.h>
#include <mio/mio_object.h>
namespace mio
{
namespace material
{
class MaterialVisitor;
class MIO_API Material : public MioObject
{
public:
Material(const char *name="");
virtual ~Material() = 0;
virtual void accept(mio::material::MaterialVisitor *visitor);
};
}
}
#endif
|
gpl-3.0
|
lleaff/ASCII-life
|
src/js/lib/world_directions.js
|
2772
|
/* =Spatial directions
* ------------------------------------------------------------ */
Direction = new (function() { /* jshint ignore:line */
this.n = new Vector( 0, 1); this.up = this.n;
this.ne = new Vector( 1, 1);
this.e = new Vector( 1, 0); this.right = this.e;
this.se = new Vector( 1, -1);
this.s = new Vector( 0, -1); this.bottom = this.s;
this.sw = new Vector(-1, -1);
this.w = new Vector(-1, 0); this.left = this.w;
this.nw = new Vector(-1, 1);
})();
Directions = [ "n", "ne", "e", "se", "s", "sw", "w", "nw" ];
Directions.vectors = [ new Vector(0, 1), new Vector(1, 1),
new Vector(1, 0), new Vector(1, -1), new Vector(0, -1),
new Vector(-1, -1), new Vector(-1, 0), new Vector(-1, 1) ];
Directions._indexOf = function(direction) {
for (var i = 0; i < Directions.vectors.length; ++i)
if (Directions.vectors[i].equal(direction))
return i;
assert(false,
"Directions._indexOf: Invalid direction: "+direction);
};
Direction.vectorToDirectionName = function(directionVector) {
return Directions[Directions._indexOf(directionVector)];
};
Direction.vectorToDirection = function(vector) {
return new Vector(vector.x ? 1 : 0, vector.y ? 1 : 0);
};
Direction.vectorToDistance = function(vector) {
return Math.max(vector.x, vector.y);
};
Direction.rotate = function(direction, degree) {
var resolution = 45;
var shift = degree / resolution;
assert(shift - (shift>>0) === 0,
"Direction.rotate: "+"'degree' ("+degree+
") must be a multiple of "+resolution);
return Directions.vectors[(Directions._indexOf(direction) + shift +
Directions.length) % Directions.length];
};
Direction.random = function() {
var x, y, vec;
while (!x && !y) {
x = randomInt(-1, 1);
y = randomInt(-1, 1);
}
return new Vector(x, y);
};
Direction.forEach = function(callback, thisArg) {
var self = this;
Directions.forEach(
function(str) { callback(self[str], str, self); }, thisArg);
};
/* Iterate through directions by gradually going farther
* from 'initialDirection' */
Direction.forEachFrom =
function(initialDirection, callback, thisArg) {
var initI = Directions.indexOf(
Direction.vectorToDirectionName(initialDireciton));
var curI = initI;
var upI, loI;
function incrementUp() {
return upI += upI < Directions.length ? 1 : 0; }
function incrementLo() {
return loI -= loI > 0 ? 1 : Directions.length; }
while (upI !== initI && loI !== initI) {
callback.call(thisArg,
directions.vectors[curI], directions[curI], this);
if (curI === upI) { curI = incrementUp(); }
else { curI = incrementLo(); }
}
};
Direction.some = function(callback, thisArg) {
var self = this;
return Directions.some(
function(str) {
return callback.call(thisArg, self[str], str, self); },
thisArg);
};
|
gpl-3.0
|
armadito/armadito-agent
|
lib/Armadito/Agent/Antivirus/Kaspersky/Task/Alerts.pm
|
780
|
package Armadito::Agent::Antivirus::Kaspersky::Task::Alerts;
use strict;
use warnings;
use base 'Armadito::Agent::Task::Alerts';
sub run {
my ( $self, %params ) = @_;
$self->SUPER::run(%params);
my $osclass = $self->{agent}->{antivirus}->getOSClass();
my $alerts = { alerts => $osclass->getAlerts() };
my $n_alerts = @{ $alerts->{alerts} };
$self->{logger}->info( $n_alerts . " alert(s) found." );
$self->_sendAlerts($alerts);
}
1;
__END__
=head1 NAME
Armadito::Agent::Antivirus::Kaspersky::Task::Alerts - Alerts Task for Kaspersky Antivirus.
=head1 DESCRIPTION
This task inherits from L<Armadito::Agent::Task:Alerts>. Get Antivirus' alerts and send them as json messages to armadito glpi plugin.
=head1 FUNCTIONS
=head2 run ( $self, %params )
Run the task.
|
gpl-3.0
|
espocrm/espocrm
|
application/Espo/Modules/Crm/Tools/MassEmail/Processor.php
|
16942
|
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\MassEmail;
use Laminas\Mail\Message;
use Espo\Entities\EmailTemplate;
use Espo\Repositories\EmailAddress as EmailAddressRepository;
use Espo\Core\{
Exceptions\Error,
ORM\EntityManager,
ServiceFactory,
Utils\Config,
Utils\Language,
Mail\EmailSender,
Mail\Sender,
Mail\Mail\Header\XQueueItemId,
Utils\Log,
};
use Espo\{
Modules\Crm\Entities\EmailQueueItem,
Modules\Crm\Entities\Campaign,
Modules\Crm\Entities\MassEmail,
Modules\Crm\Services\Campaign as CampaignService,
Services\EmailTemplate as EmailTemplateService,
ORM\Entity,
Entities\Email,
};
use Exception;
use DateTime;
class Processor
{
private $config;
private $serviceFactory;
private $entityManager;
private $defaultLanguage;
private $emailSender;
protected const MAX_ATTEMPT_COUNT = 3;
protected const MAX_PER_HOUR_COUNT = 10000;
private $campaignService = null;
private $emailTemplateService = null;
protected $log;
public function __construct(
Config $config,
ServiceFactory $serviceFactory,
EntityManager $entityManager,
Language $defaultLanguage,
EmailSender $emailSender,
Log $log
) {
$this->config = $config;
$this->serviceFactory = $serviceFactory;
$this->entityManager = $entityManager;
$this->defaultLanguage = $defaultLanguage;
$this->emailSender = $emailSender;
$this->log = $log;
}
public function process(MassEmail $massEmail, bool $isTest = false): void
{
$maxBatchSize = $this->config->get('massEmailMaxPerHourCount', self::MAX_PER_HOUR_COUNT);
if (!$isTest) {
$threshold = new DateTime();
$threshold->modify('-1 hour');
$sentLastHourCount = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_SENT,
'sentAt>' => $threshold->format('Y-m-d H:i:s'),
])
->count();
if ($sentLastHourCount >= $maxBatchSize) {
return;
}
$maxBatchSize = $maxBatchSize - $sentLastHourCount;
}
$queueItemList = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
'isTest' => $isTest,
])
->limit(0, $maxBatchSize)
->find();
$templateId = $massEmail->get('emailTemplateId');
if (!$templateId) {
$this->setFailed($massEmail);
return;
}
$campaign = null;
$campaignId = $massEmail->get('campaignId');
if ($campaignId) {
$campaign = $this->entityManager->getEntity('Campaign', $campaignId);
}
$emailTemplate = $this->entityManager->getEntity('EmailTemplate', $templateId);
if (!$emailTemplate) {
$this->setFailed($massEmail);
return;
}
/** @var iterable<\Espo\Entities\Attachment> */
$attachmentList = $this->entityManager
->getRDBRepository('EmailTemplate')
->getRelation($emailTemplate, 'attachments')
->find();
$smtpParams = null;
if ($massEmail->get('inboundEmailId')) {
$inboundEmail = $this->entityManager->getEntity('InboundEmail', $massEmail->get('inboundEmailId'));
if (!$inboundEmail) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' is not available."
);
}
if (
$inboundEmail->get('status') !== 'Active' ||
!$inboundEmail->get('useSmtp') ||
!$inboundEmail->get('smtpIsForMassEmail')
) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' can't be used for Mass Email."
);
}
$inboundEmailService = $this->serviceFactory->create('InboundEmail');
$smtpParams = $inboundEmailService->getSmtpParamsFromAccount($inboundEmail);
if (!$smtpParams) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' has no SMTP params."
);
}
if ($inboundEmail->get('replyToAddress')) {
$smtpParams['replyToAddress'] = $inboundEmail->get('replyToAddress');
}
}
foreach ($queueItemList as $queueItem) {
$this->sendQueueItem(
$queueItem,
$massEmail,
$emailTemplate,
$attachmentList,
$campaign,
$isTest,
$smtpParams
);
}
if (!$isTest) {
$countLeft = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
'isTest' => false,
])
->count();
if ($countLeft == 0) {
$massEmail->set('status', MassEmail::STATUS_COMPLETE);
$this->entityManager->saveEntity($massEmail);
}
}
}
protected function getPreparedEmail(
EmailQueueItem $queueItem,
MassEmail $massEmail,
EmailTemplate $emailTemplate,
Entity $target,
iterable $trackingUrlList = []
): ?Email {
$templateParams = [
'parent' => $target,
];
$emailData = $this->getEmailTemplateService()->parseTemplate($emailTemplate, $templateParams);
$body = $emailData['body'];
$optOutUrl = $this->getSiteUrl() . '?entryPoint=unsubscribe&id=' . $queueItem->getId();
$optOutLink =
'<a href="' . $optOutUrl . '">' .
$this->defaultLanguage->translate('Unsubscribe', 'labels', 'Campaign') .
'</a>';
$body = str_replace('{optOutUrl}', $optOutUrl, $body);
$body = str_replace('{optOutLink}', $optOutLink, $body);
foreach ($trackingUrlList as $trackingUrl) {
$url = $this->getSiteUrl() .
'?entryPoint=campaignUrl&id=' . $trackingUrl->getId() . '&queueItemId=' . $queueItem->getId();
$body = str_replace($trackingUrl->get('urlToUse'), $url, $body);
}
if (
!$this->config->get('massEmailDisableMandatoryOptOutLink') &&
stripos($body, '?entryPoint=unsubscribe&id') === false
) {
if ($emailData['isHtml']) {
$body .= "<br><br>" . $optOutLink;
}
else {
$body .= "\n\n" . $optOutUrl;
}
}
$trackImageAlt = $this->defaultLanguage->translate('Campaign', 'scopeNames');
$trackOpenedUrl = $this->getSiteUrl() . '?entryPoint=campaignTrackOpened&id=' . $queueItem->getId();
$trackOpenedHtml =
'<img alt="' . $trackImageAlt . '" width="1" height="1" border="0" src="' . $trackOpenedUrl . '">';
if ($massEmail->get('campaignId') && $this->config->get('massEmailOpenTracking')) {
if ($emailData['isHtml']) {
$body .= '<br>' . $trackOpenedHtml;
}
}
$emailData['body'] = $body;
$email = $this->entityManager->getEntity('Email');
$email->set($emailData);
$emailAddress = $target->get('emailAddress');
if (empty($emailAddress)) {
return null;
}
$email->set('to', $emailAddress);
if ($massEmail->get('fromAddress')) {
$email->set('from', $massEmail->get('fromAddress'));
}
if ($massEmail->get('replyToAddress')) {
$email->set('replyTo', $massEmail->get('replyToAddress'));
}
return $email;
}
protected function prepareQueueItemMessage(
EmailQueueItem $queueItem,
Sender $sender,
Message $message,
array &$params
): void {
$header = new XQueueItemId();
$header->setId($queueItem->getId());
$message->getHeaders()->addHeader($header);
$message->getHeaders()->addHeaderLine('Precedence', 'bulk');
if (!$this->config->get('massEmailDisableMandatoryOptOutLink')) {
$optOutUrl = $this->getSiteUrl() . '?entryPoint=unsubscribe&id=' . $queueItem->getId();
$message->getHeaders()->addHeaderLine('List-Unsubscribe', '<' . $optOutUrl . '>');
}
$fromAddress = $params['fromAddress'] ?? $this->config->get('outboundEmailFromAddress');
if ($this->config->get('massEmailVerp')) {
if ($fromAddress && strpos($fromAddress, '@')) {
$bounceAddress = explode('@', $fromAddress)[0] . '+bounce-qid-' . $queueItem->getId() .
'@' . explode('@', $fromAddress)[1];
$sender->withEnvelopeOptions([
'from' => $bounceAddress,
]);
}
}
}
protected function setFailed(MassEmail $massEmail): void
{
$massEmail->set('status', MassEmail::STATUS_FAILED);
$this->entityManager->saveEntity($massEmail);
$queueItemList = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
])
->find();
foreach ($queueItemList as $queueItem) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
}
}
/**
* @param iterable<\Espo\Entities\Attachment> $attachmentList
*/
protected function sendQueueItem(
EmailQueueItem $queueItem,
MassEmail $massEmail,
EmailTemplate $emailTemplate,
$attachmentList = [],
?Campaign $campaign = null,
bool $isTest = false,
$smtpParams = null
): bool {
$queueItemFetched = $this->entityManager->getEntity($queueItem->getEntityType(), $queueItem->getId());
if ($queueItemFetched->get('status') !== EmailQueueItem::STATUS_PENDING) {
return false;
}
$queueItem->set('status', EmailQueueItem::STATUS_SENDING);
$this->entityManager->saveEntity($queueItem);
$target = $this->entityManager->getEntity($queueItem->get('targetType'), $queueItem->get('targetId'));
$emailAddress = null;
if ($target) {
$emailAddress = $target->get('emailAddress');
}
if (
!$target ||
!$target->getId() ||
!$emailAddress
) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
return false;
}
/** @var EmailAddressRepository $emailAddressRepository */
$emailAddressRepository = $this->entityManager->getRepository('EmailAddress');
$emailAddressRecord = $emailAddressRepository->getByAddress($emailAddress);
if ($emailAddressRecord) {
if ($emailAddressRecord->get('invalid') || $emailAddressRecord->get('optOut')) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
return false;
}
}
$trackingUrlList = [];
if ($campaign) {
$trackingUrlList = $this->entityManager
->getRDBRepository('Campaign')
->getRelation($campaign, 'trackingUrls')
->find();
}
$email = $this->getPreparedEmail($queueItem, $massEmail, $emailTemplate, $target, $trackingUrlList);
if (!$email) {
return false;
}
if ($email->get('replyToAddress')) {
unset($smtpParams['replyToAddress']);
}
if ($campaign) {
$email->setLinkMultipleIdList(
'teams',
$campaign->getLinkMultipleIdList('teams')
);
}
$params = [];
if ($massEmail->get('fromName')) {
$params['fromName'] = $massEmail->get('fromName');
}
if ($massEmail->get('replyToName')) {
$params['replyToName'] = $massEmail->get('replyToName');
}
try {
$attemptCount = $queueItem->get('attemptCount');
$attemptCount++;
$queueItem->set('attemptCount', $attemptCount);
$sender = $this->emailSender->create();
if ($smtpParams) {
$sender->withSmtpParams($smtpParams);
}
$message = new Message();
$this->prepareQueueItemMessage($queueItem, $sender, $message, $params);
$sender
->withParams($params)
->withMessage($message)
->withAttachments($attachmentList)
->send($email);
}
catch (Exception $e) {
$maxAttemptCount = $this->config->get('massEmailMaxAttemptCount', self::MAX_ATTEMPT_COUNT);
if ($queueItem->get('attemptCount') >= $maxAttemptCount) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
}
else {
$queueItem->set('status', EmailQueueItem::STATUS_PENDING);
}
$this->entityManager->saveEntity($queueItem);
$this->log->error('MassEmail#sendQueueItem: [' . $e->getCode() . '] ' .$e->getMessage());
return false;
}
$emailObject = $emailTemplate;
if ($massEmail->get('storeSentEmails') && !$isTest) {
$this->entityManager->saveEntity($email);
$emailObject = $email;
}
$queueItem->set('emailAddress', $target->get('emailAddress'));
$queueItem->set('status', EmailQueueItem::STATUS_SENT);
$queueItem->set('sentAt', date('Y-m-d H:i:s'));
$this->entityManager->saveEntity($queueItem);
if ($campaign) {
$this->getCampaignService()->logSent(
$campaign->getId(),
$queueItem->getId(),
$target,
$emailObject,
$target->get('emailAddress'),
null,
$queueItem->get('isTest')
);
}
return true;
}
protected function getEmailTemplateService(): EmailTemplateService
{
if (!$this->emailTemplateService) {
$this->emailTemplateService = $this->serviceFactory->create('EmailTemplate');
}
return $this->emailTemplateService;
}
protected function getCampaignService(): CampaignService
{
if (!$this->campaignService) {
$this->campaignService = $this->serviceFactory->create('Campaign');
}
return $this->campaignService;
}
protected function getSiteUrl(): string
{
return $this->config->get('massEmailSiteUrl') ?? $this->config->get('siteUrl');
}
}
|
gpl-3.0
|
versionstudio/vibestreamer
|
src/win32/AboutDialog.cpp
|
1655
|
/*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio point 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/>.
*/
#include "common.h"
#include "aboutdialog.h"
#include "hyperlinks.h"
INT CALLBACK AboutDialog::dialogProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch ( msg )
{
case WM_COMMAND:
{
switch ( wParam )
{
case IDC_BUTTON_CLOSE:
{
EndDialog(hWnd, NULL);
}
break;
case IDC_STATIC_URL:
{
char sz[255] = {0};
GetWindowText(GetDlgItem(hWnd,IDC_STATIC_URL),sz,255);
ShellExecute(hWnd,"open",sz,NULL,NULL,SW_SHOWNORMAL);
}
break;
}
}
break;
}
return 0;
}
void AboutDialog::dialogInit(HWND hWnd,LPARAM lParam)
{
SetWindowText(GetDlgItem(hWnd,IDC_STATIC_APPLICATION), TEXT(APP_NAME) TEXT(" ") TEXT(APP_VERSION) TEXT(APP_MILESTONE));
ConvertStaticToHyperlink(GetDlgItem(hWnd,IDC_STATIC_URL));
WinUtil::WindowUtil::centerParent(hWnd);
SetFocus(GetDlgItem(hWnd, IDC_BUTTON_CLOSE));
}
|
gpl-3.0
|
BrunoJuchli/RibbonizerSample
|
Ribbonizer.Wrappers.Microsoft/RibbonGroupWrapper.cs
|
1094
|
namespace Ribbonizer.Wrappers.Microsoft
{
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using System.Windows.Controls.Ribbon;
using Ribbonizer.Ribbon.Groups;
[ExcludeFromCodeCoverage]
internal class RibbonGroupWrapper : IRibbonGroupView, IWrapper<RibbonGroup>
{
private readonly RibbonGroup ribbonGroup;
public RibbonGroupWrapper(RibbonGroup ribbonGroup)
{
this.ribbonGroup = ribbonGroup;
}
public RibbonGroup Wrapped
{
get { return this.ribbonGroup; }
}
public string Caption
{
get { return (string)this.ribbonGroup.Header; }
set { this.ribbonGroup.Header = value; }
}
public void AddItem(object item)
{
var wrapper = item as IWrapper<Control>;
if (wrapper != null)
{
this.ribbonGroup.Items.Add(wrapper.Wrapped);
}
else
{
this.ribbonGroup.Items.Add(item);
}
}
}
}
|
gpl-3.0
|
dtu-compute/dtu-quiz
|
spec/models/multiple_choice_question_spec.rb
|
1050
|
require 'rails_helper'
RSpec.describe MultipleChoiceQuestion, type: :model do
describe "#correct" do
context "answered questions (right)" do
let(:answered_question) { build(:multiple_choice_question) }
it { expect(answered_question).to be_valid }
it { expect(answered_question.correct?).to eq(true) }
end
context "answered questions (wrong)" do
let(:answered_question) { build(:multiple_choice_question, :wrong) }
it { expect(answered_question).to be_valid }
it { expect(answered_question.correct?).to eq(false) }
end
context "unanswered questions" do
let(:unanswered_question) do
build(:multiple_choice_question, :answers => [
FactoryGirl.build(:true_false_answer, :unset_wrong, :answer_text => "unset_wrong"),
FactoryGirl.build(:true_false_answer, :unset_right, :answer_text => "unset_right") ] )
end
it { expect(unanswered_question).to be_valid }
it { expect(unanswered_question.correct?).to be false }
end
end
end
|
gpl-3.0
|
idega/is.fmr.landskra
|
src/java/fasteignaskra/landskra_wse/FasteignaskraFasteignMatseining.java
|
30821
|
/**
* FasteignaskraFasteignMatseining.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
*/
package fasteignaskra.landskra_wse;
public class FasteignaskraFasteignMatseining implements java.io.Serializable {
private java.lang.Integer fastanr;
private java.lang.Integer matseiningarnr;
private java.lang.Integer landnr;
private java.lang.Integer heitinr;
private java.lang.String skyring;
private java.lang.Short notkunarlykill;
private java.lang.String notkun;
private java.lang.String merking;
private java.math.BigDecimal flatarmal;
private java.lang.String flatarmalseining;
private java.lang.String byggingarstigslykill;
private java.lang.String byggingarstig;
private java.lang.String byggingarefnislykill;
private java.lang.String byggingarefni;
private java.lang.String byggingarar;
private java.lang.Integer herbergi;
private java.math.BigDecimal husmat;
private java.math.BigDecimal lodarhlutamat;
private java.math.BigDecimal fasteignamat;
private java.math.BigDecimal brunabotamat;
private java.math.BigDecimal byggingarvisitala;
private java.util.Calendar bvisitdags;
public FasteignaskraFasteignMatseining() {
}
public FasteignaskraFasteignMatseining(
java.lang.Integer fastanr,
java.lang.Integer matseiningarnr,
java.lang.Integer landnr,
java.lang.Integer heitinr,
java.lang.String skyring,
java.lang.Short notkunarlykill,
java.lang.String notkun,
java.lang.String merking,
java.math.BigDecimal flatarmal,
java.lang.String flatarmalseining,
java.lang.String byggingarstigslykill,
java.lang.String byggingarstig,
java.lang.String byggingarefnislykill,
java.lang.String byggingarefni,
java.lang.String byggingarar,
java.lang.Integer herbergi,
java.math.BigDecimal husmat,
java.math.BigDecimal lodarhlutamat,
java.math.BigDecimal fasteignamat,
java.math.BigDecimal brunabotamat,
java.math.BigDecimal byggingarvisitala,
java.util.Calendar bvisitdags) {
this.fastanr = fastanr;
this.matseiningarnr = matseiningarnr;
this.landnr = landnr;
this.heitinr = heitinr;
this.skyring = skyring;
this.notkunarlykill = notkunarlykill;
this.notkun = notkun;
this.merking = merking;
this.flatarmal = flatarmal;
this.flatarmalseining = flatarmalseining;
this.byggingarstigslykill = byggingarstigslykill;
this.byggingarstig = byggingarstig;
this.byggingarefnislykill = byggingarefnislykill;
this.byggingarefni = byggingarefni;
this.byggingarar = byggingarar;
this.herbergi = herbergi;
this.husmat = husmat;
this.lodarhlutamat = lodarhlutamat;
this.fasteignamat = fasteignamat;
this.brunabotamat = brunabotamat;
this.byggingarvisitala = byggingarvisitala;
this.bvisitdags = bvisitdags;
}
/**
* Gets the fastanr value for this FasteignaskraFasteignMatseining.
*
* @return fastanr
*/
public java.lang.Integer getFastanr() {
return fastanr;
}
/**
* Sets the fastanr value for this FasteignaskraFasteignMatseining.
*
* @param fastanr
*/
public void setFastanr(java.lang.Integer fastanr) {
this.fastanr = fastanr;
}
/**
* Gets the matseiningarnr value for this FasteignaskraFasteignMatseining.
*
* @return matseiningarnr
*/
public java.lang.Integer getMatseiningarnr() {
return matseiningarnr;
}
/**
* Sets the matseiningarnr value for this FasteignaskraFasteignMatseining.
*
* @param matseiningarnr
*/
public void setMatseiningarnr(java.lang.Integer matseiningarnr) {
this.matseiningarnr = matseiningarnr;
}
/**
* Gets the landnr value for this FasteignaskraFasteignMatseining.
*
* @return landnr
*/
public java.lang.Integer getLandnr() {
return landnr;
}
/**
* Sets the landnr value for this FasteignaskraFasteignMatseining.
*
* @param landnr
*/
public void setLandnr(java.lang.Integer landnr) {
this.landnr = landnr;
}
/**
* Gets the heitinr value for this FasteignaskraFasteignMatseining.
*
* @return heitinr
*/
public java.lang.Integer getHeitinr() {
return heitinr;
}
/**
* Sets the heitinr value for this FasteignaskraFasteignMatseining.
*
* @param heitinr
*/
public void setHeitinr(java.lang.Integer heitinr) {
this.heitinr = heitinr;
}
/**
* Gets the skyring value for this FasteignaskraFasteignMatseining.
*
* @return skyring
*/
public java.lang.String getSkyring() {
return skyring;
}
/**
* Sets the skyring value for this FasteignaskraFasteignMatseining.
*
* @param skyring
*/
public void setSkyring(java.lang.String skyring) {
this.skyring = skyring;
}
/**
* Gets the notkunarlykill value for this FasteignaskraFasteignMatseining.
*
* @return notkunarlykill
*/
public java.lang.Short getNotkunarlykill() {
return notkunarlykill;
}
/**
* Sets the notkunarlykill value for this FasteignaskraFasteignMatseining.
*
* @param notkunarlykill
*/
public void setNotkunarlykill(java.lang.Short notkunarlykill) {
this.notkunarlykill = notkunarlykill;
}
/**
* Gets the notkun value for this FasteignaskraFasteignMatseining.
*
* @return notkun
*/
public java.lang.String getNotkun() {
return notkun;
}
/**
* Sets the notkun value for this FasteignaskraFasteignMatseining.
*
* @param notkun
*/
public void setNotkun(java.lang.String notkun) {
this.notkun = notkun;
}
/**
* Gets the merking value for this FasteignaskraFasteignMatseining.
*
* @return merking
*/
public java.lang.String getMerking() {
return merking;
}
/**
* Sets the merking value for this FasteignaskraFasteignMatseining.
*
* @param merking
*/
public void setMerking(java.lang.String merking) {
this.merking = merking;
}
/**
* Gets the flatarmal value for this FasteignaskraFasteignMatseining.
*
* @return flatarmal
*/
public java.math.BigDecimal getFlatarmal() {
return flatarmal;
}
/**
* Sets the flatarmal value for this FasteignaskraFasteignMatseining.
*
* @param flatarmal
*/
public void setFlatarmal(java.math.BigDecimal flatarmal) {
this.flatarmal = flatarmal;
}
/**
* Gets the flatarmalseining value for this FasteignaskraFasteignMatseining.
*
* @return flatarmalseining
*/
public java.lang.String getFlatarmalseining() {
return flatarmalseining;
}
/**
* Sets the flatarmalseining value for this FasteignaskraFasteignMatseining.
*
* @param flatarmalseining
*/
public void setFlatarmalseining(java.lang.String flatarmalseining) {
this.flatarmalseining = flatarmalseining;
}
/**
* Gets the byggingarstigslykill value for this FasteignaskraFasteignMatseining.
*
* @return byggingarstigslykill
*/
public java.lang.String getByggingarstigslykill() {
return byggingarstigslykill;
}
/**
* Sets the byggingarstigslykill value for this FasteignaskraFasteignMatseining.
*
* @param byggingarstigslykill
*/
public void setByggingarstigslykill(java.lang.String byggingarstigslykill) {
this.byggingarstigslykill = byggingarstigslykill;
}
/**
* Gets the byggingarstig value for this FasteignaskraFasteignMatseining.
*
* @return byggingarstig
*/
public java.lang.String getByggingarstig() {
return byggingarstig;
}
/**
* Sets the byggingarstig value for this FasteignaskraFasteignMatseining.
*
* @param byggingarstig
*/
public void setByggingarstig(java.lang.String byggingarstig) {
this.byggingarstig = byggingarstig;
}
/**
* Gets the byggingarefnislykill value for this FasteignaskraFasteignMatseining.
*
* @return byggingarefnislykill
*/
public java.lang.String getByggingarefnislykill() {
return byggingarefnislykill;
}
/**
* Sets the byggingarefnislykill value for this FasteignaskraFasteignMatseining.
*
* @param byggingarefnislykill
*/
public void setByggingarefnislykill(java.lang.String byggingarefnislykill) {
this.byggingarefnislykill = byggingarefnislykill;
}
/**
* Gets the byggingarefni value for this FasteignaskraFasteignMatseining.
*
* @return byggingarefni
*/
public java.lang.String getByggingarefni() {
return byggingarefni;
}
/**
* Sets the byggingarefni value for this FasteignaskraFasteignMatseining.
*
* @param byggingarefni
*/
public void setByggingarefni(java.lang.String byggingarefni) {
this.byggingarefni = byggingarefni;
}
/**
* Gets the byggingarar value for this FasteignaskraFasteignMatseining.
*
* @return byggingarar
*/
public java.lang.String getByggingarar() {
return byggingarar;
}
/**
* Sets the byggingarar value for this FasteignaskraFasteignMatseining.
*
* @param byggingarar
*/
public void setByggingarar(java.lang.String byggingarar) {
this.byggingarar = byggingarar;
}
/**
* Gets the herbergi value for this FasteignaskraFasteignMatseining.
*
* @return herbergi
*/
public java.lang.Integer getHerbergi() {
return herbergi;
}
/**
* Sets the herbergi value for this FasteignaskraFasteignMatseining.
*
* @param herbergi
*/
public void setHerbergi(java.lang.Integer herbergi) {
this.herbergi = herbergi;
}
/**
* Gets the husmat value for this FasteignaskraFasteignMatseining.
*
* @return husmat
*/
public java.math.BigDecimal getHusmat() {
return husmat;
}
/**
* Sets the husmat value for this FasteignaskraFasteignMatseining.
*
* @param husmat
*/
public void setHusmat(java.math.BigDecimal husmat) {
this.husmat = husmat;
}
/**
* Gets the lodarhlutamat value for this FasteignaskraFasteignMatseining.
*
* @return lodarhlutamat
*/
public java.math.BigDecimal getLodarhlutamat() {
return lodarhlutamat;
}
/**
* Sets the lodarhlutamat value for this FasteignaskraFasteignMatseining.
*
* @param lodarhlutamat
*/
public void setLodarhlutamat(java.math.BigDecimal lodarhlutamat) {
this.lodarhlutamat = lodarhlutamat;
}
/**
* Gets the fasteignamat value for this FasteignaskraFasteignMatseining.
*
* @return fasteignamat
*/
public java.math.BigDecimal getFasteignamat() {
return fasteignamat;
}
/**
* Sets the fasteignamat value for this FasteignaskraFasteignMatseining.
*
* @param fasteignamat
*/
public void setFasteignamat(java.math.BigDecimal fasteignamat) {
this.fasteignamat = fasteignamat;
}
/**
* Gets the brunabotamat value for this FasteignaskraFasteignMatseining.
*
* @return brunabotamat
*/
public java.math.BigDecimal getBrunabotamat() {
return brunabotamat;
}
/**
* Sets the brunabotamat value for this FasteignaskraFasteignMatseining.
*
* @param brunabotamat
*/
public void setBrunabotamat(java.math.BigDecimal brunabotamat) {
this.brunabotamat = brunabotamat;
}
/**
* Gets the byggingarvisitala value for this FasteignaskraFasteignMatseining.
*
* @return byggingarvisitala
*/
public java.math.BigDecimal getByggingarvisitala() {
return byggingarvisitala;
}
/**
* Sets the byggingarvisitala value for this FasteignaskraFasteignMatseining.
*
* @param byggingarvisitala
*/
public void setByggingarvisitala(java.math.BigDecimal byggingarvisitala) {
this.byggingarvisitala = byggingarvisitala;
}
/**
* Gets the bvisitdags value for this FasteignaskraFasteignMatseining.
*
* @return bvisitdags
*/
public java.util.Calendar getBvisitdags() {
return bvisitdags;
}
/**
* Sets the bvisitdags value for this FasteignaskraFasteignMatseining.
*
* @param bvisitdags
*/
public void setBvisitdags(java.util.Calendar bvisitdags) {
this.bvisitdags = bvisitdags;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof FasteignaskraFasteignMatseining)) return false;
FasteignaskraFasteignMatseining other = (FasteignaskraFasteignMatseining) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.fastanr==null && other.getFastanr()==null) ||
(this.fastanr!=null &&
this.fastanr.equals(other.getFastanr()))) &&
((this.matseiningarnr==null && other.getMatseiningarnr()==null) ||
(this.matseiningarnr!=null &&
this.matseiningarnr.equals(other.getMatseiningarnr()))) &&
((this.landnr==null && other.getLandnr()==null) ||
(this.landnr!=null &&
this.landnr.equals(other.getLandnr()))) &&
((this.heitinr==null && other.getHeitinr()==null) ||
(this.heitinr!=null &&
this.heitinr.equals(other.getHeitinr()))) &&
((this.skyring==null && other.getSkyring()==null) ||
(this.skyring!=null &&
this.skyring.equals(other.getSkyring()))) &&
((this.notkunarlykill==null && other.getNotkunarlykill()==null) ||
(this.notkunarlykill!=null &&
this.notkunarlykill.equals(other.getNotkunarlykill()))) &&
((this.notkun==null && other.getNotkun()==null) ||
(this.notkun!=null &&
this.notkun.equals(other.getNotkun()))) &&
((this.merking==null && other.getMerking()==null) ||
(this.merking!=null &&
this.merking.equals(other.getMerking()))) &&
((this.flatarmal==null && other.getFlatarmal()==null) ||
(this.flatarmal!=null &&
this.flatarmal.equals(other.getFlatarmal()))) &&
((this.flatarmalseining==null && other.getFlatarmalseining()==null) ||
(this.flatarmalseining!=null &&
this.flatarmalseining.equals(other.getFlatarmalseining()))) &&
((this.byggingarstigslykill==null && other.getByggingarstigslykill()==null) ||
(this.byggingarstigslykill!=null &&
this.byggingarstigslykill.equals(other.getByggingarstigslykill()))) &&
((this.byggingarstig==null && other.getByggingarstig()==null) ||
(this.byggingarstig!=null &&
this.byggingarstig.equals(other.getByggingarstig()))) &&
((this.byggingarefnislykill==null && other.getByggingarefnislykill()==null) ||
(this.byggingarefnislykill!=null &&
this.byggingarefnislykill.equals(other.getByggingarefnislykill()))) &&
((this.byggingarefni==null && other.getByggingarefni()==null) ||
(this.byggingarefni!=null &&
this.byggingarefni.equals(other.getByggingarefni()))) &&
((this.byggingarar==null && other.getByggingarar()==null) ||
(this.byggingarar!=null &&
this.byggingarar.equals(other.getByggingarar()))) &&
((this.herbergi==null && other.getHerbergi()==null) ||
(this.herbergi!=null &&
this.herbergi.equals(other.getHerbergi()))) &&
((this.husmat==null && other.getHusmat()==null) ||
(this.husmat!=null &&
this.husmat.equals(other.getHusmat()))) &&
((this.lodarhlutamat==null && other.getLodarhlutamat()==null) ||
(this.lodarhlutamat!=null &&
this.lodarhlutamat.equals(other.getLodarhlutamat()))) &&
((this.fasteignamat==null && other.getFasteignamat()==null) ||
(this.fasteignamat!=null &&
this.fasteignamat.equals(other.getFasteignamat()))) &&
((this.brunabotamat==null && other.getBrunabotamat()==null) ||
(this.brunabotamat!=null &&
this.brunabotamat.equals(other.getBrunabotamat()))) &&
((this.byggingarvisitala==null && other.getByggingarvisitala()==null) ||
(this.byggingarvisitala!=null &&
this.byggingarvisitala.equals(other.getByggingarvisitala()))) &&
((this.bvisitdags==null && other.getBvisitdags()==null) ||
(this.bvisitdags!=null &&
this.bvisitdags.equals(other.getBvisitdags())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getFastanr() != null) {
_hashCode += getFastanr().hashCode();
}
if (getMatseiningarnr() != null) {
_hashCode += getMatseiningarnr().hashCode();
}
if (getLandnr() != null) {
_hashCode += getLandnr().hashCode();
}
if (getHeitinr() != null) {
_hashCode += getHeitinr().hashCode();
}
if (getSkyring() != null) {
_hashCode += getSkyring().hashCode();
}
if (getNotkunarlykill() != null) {
_hashCode += getNotkunarlykill().hashCode();
}
if (getNotkun() != null) {
_hashCode += getNotkun().hashCode();
}
if (getMerking() != null) {
_hashCode += getMerking().hashCode();
}
if (getFlatarmal() != null) {
_hashCode += getFlatarmal().hashCode();
}
if (getFlatarmalseining() != null) {
_hashCode += getFlatarmalseining().hashCode();
}
if (getByggingarstigslykill() != null) {
_hashCode += getByggingarstigslykill().hashCode();
}
if (getByggingarstig() != null) {
_hashCode += getByggingarstig().hashCode();
}
if (getByggingarefnislykill() != null) {
_hashCode += getByggingarefnislykill().hashCode();
}
if (getByggingarefni() != null) {
_hashCode += getByggingarefni().hashCode();
}
if (getByggingarar() != null) {
_hashCode += getByggingarar().hashCode();
}
if (getHerbergi() != null) {
_hashCode += getHerbergi().hashCode();
}
if (getHusmat() != null) {
_hashCode += getHusmat().hashCode();
}
if (getLodarhlutamat() != null) {
_hashCode += getLodarhlutamat().hashCode();
}
if (getFasteignamat() != null) {
_hashCode += getFasteignamat().hashCode();
}
if (getBrunabotamat() != null) {
_hashCode += getBrunabotamat().hashCode();
}
if (getByggingarvisitala() != null) {
_hashCode += getByggingarvisitala().hashCode();
}
if (getBvisitdags() != null) {
_hashCode += getBvisitdags().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(FasteignaskraFasteignMatseining.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("urn:landskra-wse:fasteignaskra", ">>>Fasteignaskra>Fasteign>Matseining"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fastanr");
elemField.setXmlName(new javax.xml.namespace.QName("", "fastanr"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("matseiningarnr");
elemField.setXmlName(new javax.xml.namespace.QName("", "matseiningarnr"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("landnr");
elemField.setXmlName(new javax.xml.namespace.QName("", "landnr"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("heitinr");
elemField.setXmlName(new javax.xml.namespace.QName("", "heitinr"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("skyring");
elemField.setXmlName(new javax.xml.namespace.QName("", "skyring"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("notkunarlykill");
elemField.setXmlName(new javax.xml.namespace.QName("", "notkunarlykill"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "short"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("notkun");
elemField.setXmlName(new javax.xml.namespace.QName("", "notkun"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("merking");
elemField.setXmlName(new javax.xml.namespace.QName("", "merking"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("flatarmal");
elemField.setXmlName(new javax.xml.namespace.QName("", "flatarmal"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("flatarmalseining");
elemField.setXmlName(new javax.xml.namespace.QName("", "flatarmalseining"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarstigslykill");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarstigslykill"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarstig");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarstig"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarefnislykill");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarefnislykill"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarefni");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarefni"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarar");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarar"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("herbergi");
elemField.setXmlName(new javax.xml.namespace.QName("", "herbergi"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("husmat");
elemField.setXmlName(new javax.xml.namespace.QName("", "husmat"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lodarhlutamat");
elemField.setXmlName(new javax.xml.namespace.QName("", "lodarhlutamat"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fasteignamat");
elemField.setXmlName(new javax.xml.namespace.QName("", "fasteignamat"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("brunabotamat");
elemField.setXmlName(new javax.xml.namespace.QName("", "brunabotamat"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("byggingarvisitala");
elemField.setXmlName(new javax.xml.namespace.QName("", "byggingarvisitala"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("bvisitdags");
elemField.setXmlName(new javax.xml.namespace.QName("", "bvisitdags"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
gpl-3.0
|
sanchay160887/vacuum-im
|
src/translations/es/xmppstreams.ts
|
1626
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="es" sourcelanguage="en">
<context>
<name>XmppStream</name>
<message>
<source>Password request</source>
<translation>Solicitar contraseña</translation>
</message>
<message>
<source>Enter password for <b>%1</b></source>
<translation>Entrar la contraseña para <b>%1</b></translation>
</message>
<message>
<source>Connection not specified</source>
<translation>Conexión sin definir</translation>
</message>
</context>
<context>
<name>XmppStreams</name>
<message>
<source>XMPP Streams Manager</source>
<translation>Administrador de flujos XMPP</translation>
</message>
<message>
<source>Allows other modules to create XMPP streams and get access to them</source>
<translation>Permite a otros módulos crear flujos XMPP y tener acceso a ellos</translation>
</message>
<message>
<source>XMPP stream destroyed</source>
<translation>Flujo XMP destruido</translation>
</message>
<message>
<source>Secure connection is not established</source>
<translation>No se ha podido establecer una conexión segura</translation>
</message>
<message>
<source>Connection closed unexpectedly</source>
<translation>La conexión ha cerrado inesperadamente</translation>
</message>
<message>
<source>Failed to start connection</source>
<translation>Error al iniciar la conexión</translation>
</message>
</context>
</TS>
|
gpl-3.0
|
aczwink/ACStdLib
|
include/Std++/UI/Displays/VideoWidget.hpp
|
1633
|
/*
* Copyright (c) 2017-2020 Amir Czwink (amir130@hotmail.de)
*
* This file is part of Std++.
*
* Std++ 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.
*
* Std++ 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 Std++. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
//Local
#include "../../Multimedia/Packet.hpp"
#include "../../Multitasking/Mutex.hpp"
#include "../../Rendering/Texture2D.hpp"
#include "PathRenderTargetWidget.hpp"
namespace StdXX
{
namespace UI
{
class STDPLUSPLUS_API VideoWidget : public PathRenderTargetWidget
{
public:
//Constructor
inline VideoWidget(const WidgetFrameBufferSetup& frameBufferSetup)
: PathRenderTargetWidget(frameBufferSetup),
texture(nullptr), nextFrame(nullptr)
{
}
//Destructor
~VideoWidget();
//Methods
void UpdatePicture(Multimedia::Packet *videoPacket, Math::Size<uint16> frameSize);
protected:
//Event handlers
void OnRealized() override;
private:
//Members
Rendering::Texture2D *texture;
Multimedia::Packet *nextFrame;
Math::Size<uint16> frameSize;
Mutex frameLock;
//Eventhandlers
void OnPaint(PaintEvent& event) override;
};
}
}
|
gpl-3.0
|
jsnfwlr/editor27
|
lib/editor/atto/styles.css
|
2508
|
.editor_atto_content_wrap {
background-color: white;
}
.editor_atto_content {
padding: 4px;
}
.editor_atto_content_wrap,
.editor_atto + textarea {
width: 100%;
padding: 0;
border: 1px solid #BBB;
border-top: none;
}
.editor_atto + textarea {
border-radius: 0;
resize: vertical;
margin-top: -1px;
}
div.editor_atto_toolbar {
display: block;
background: #F2F2F2;
min-height: 35px;
border: 1px solid #BBB;
width: 100%;
padding: 0 0 9px 0;
}
div.editor_atto_toolbar button {
padding: 5px 6px;
background: none;
border: 0px;
margin: 0;
border-radius: 0;
cursor: pointer;
}
div.editor_atto_toolbar button + button {
border-left: 1px solid #CCC;
}
div.editor_atto_toolbar button[disabled] {
opacity: .45;
background: none;
cursor: default;
}
.editor_atto_toolbar button:hover {
background-image: radial-gradient(ellipse at center, #ffffff 60%,#dfdfdf 100%);
background-color: #ebebeb;
}
.editor_atto_toolbar button:active {
background-image: radial-gradient(ellipse at center, #ffffff 40%,#dfdfdf 100%);
background-color: #dfdfdf;
}
div.editor_atto_toolbar button img {
padding: 1px;
}
div.editor_atto_toolbar div.atto_group {
display: inline-block;
border: 1px solid #CCC;
border-bottom: 1px solid #B3B3B3;
border-radius: 4px;
margin: 9px 0px 0px 9px;
background: #FFF;
}
div.editor_atto_toolbar.collapsetoolbar .atto_group + .atto_group + .atto_group + .atto_group {
display: none;
}
.editor_atto_content img {
resize: both; overflow: auto;
}
.atto_menuentry img {
width: 16px;
height: 16px;
}
.atto_menu {
min-width: 12em;
background: white;
padding: 1px;
}
.atto_menu a {
color: black;
}
.atto_menuentry {
border-bottom: 1px solid #eee;
padding: 2px;
clear: left;
}
.atto_menuentry h1,
.atto_menuentry h2,
.atto_menuentry p {
margin: 4px;
}
.atto_form label.sameline {
display: inline-block;
min-width: 4em;
}
.atto_form input.fullwidth,
.atto_form textarea.fullwidth {
width: 100%;
}
.atto_form {
padding-left: 30px;
padding-right: 30px;
}
.atto_form label {
display: block;
margin: 5px;
}
/* RTL Rules */
body.dir-rtl div.editor_atto_toolbar button + button {
border-left: 0;
border-right: 1px solid #CCC;
}
body.dir-rtl div.editor_atto_toolbar img.icon {
padding: 0;
}
body.dir-rtl div.editor_atto_toolbar div.atto_group {
margin: 9px 9px 0px 0px;
}
|
gpl-3.0
|
SpencerFranklin/MinecraftMod
|
src/main/java/net/spencer/test/init/ModItems.java
|
2194
|
package net.spencer.test.init;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.spencer.test.Reference;
import net.spencer.test.entity.EntityBomb;
import net.spencer.test.entity.EntityFireball;
import net.spencer.test.items.ItemBomb;
import net.spencer.test.items.ItemCheese;
import net.spencer.test.items.ItemCheeseStick;
import net.spencer.test.items.ItemFillStick;
import net.spencer.test.items.ItemFireball;
import net.spencer.test.items.ItemMCBowl;
import net.spencer.test.items.ItemMagicStick;
public class ModItems {
public static Item cheese, magic_stick, bomb, mcbowl, cheese_stick, fill_stick, fireball;
public static void init () {
cheese = new ItemCheese(5, 1, false).setAlwaysEdible();
mcbowl = new ItemMCBowl(8, 1.5f, false).setAlwaysEdible();
magic_stick = new ItemMagicStick();
cheese_stick = new ItemCheeseStick();
bomb = new ItemBomb();
fill_stick = new ItemFillStick();
fireball = new ItemFireball();
}
public static void register () {
GameRegistry.register(cheese);
GameRegistry.register(magic_stick);
GameRegistry.register(bomb);
GameRegistry.register(mcbowl);
GameRegistry.register(cheese_stick);
GameRegistry.register(fill_stick);
GameRegistry.register(fireball);
}
public static void registerRenders () {
registerRender (cheese);
registerRender (magic_stick);
registerRender (bomb);
registerRender (mcbowl);
registerRender (cheese_stick);
registerRender (fill_stick);
registerRender (fireball);
//RenderingRegistry.registerEntityRenderingHandler(entityClass, RenderSnowball());
}
private static void registerRender (Item item) {
System.out.println(item.getRegistryName());
Minecraft.getMinecraft().getRenderItem().getItemModelMesher()
.register(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
}
|
gpl-3.0
|
mishakos/InsuranceSystem.Library
|
InsuranceSystem.Library/Models/Documents/PostBlankItem.cs
|
537
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InsuranceSystem.Library.Models.Catalogs;
namespace InsuranceSystem.Library.Models.Documents
{
public class PostBlankItem
{
public int Id { get; set; }
public int PostBlankId { get; set; }
public virtual PostBlank PostBlank { get; set; }
public int BlankId { get; set; }
public virtual Blank Blank { get; set; }
public decimal Price { get; set; }
}
}
|
gpl-3.0
|
JulienBernard/ApocalySpace
|
Pilotage/docs/html/class_data-members.html
|
12891
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>ApocalySpace: Liste des membres</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">ApocalySpace
 <span id="projectnumber">1.6</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Généré par Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Recherche');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Page principale</span></a></li>
<li><a href="pages.html"><span>Pages associées</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Fichiers</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Recherche" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Liste des classes</span></a></li>
<li><a href="classes.html"><span>Index des classes</span></a></li>
<li><a href="hierarchy.html"><span>Hiérarchie des classes</span></a></li>
<li><a href="functions.html"><span>Membres de classe</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>Tout</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Fonctions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Data Liste des membres</div> </div>
</div><!--header-->
<div class="contents">
<p>Liste complète des membres de <a class="el" href="class_data.html">Data</a>, y compris les membres hérités :</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="class_data.html#a34d287f8561e98e15fce0a6c02662a2a">__construct</a>($viewBuildings, $viewTechnologies)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>calculProdRes</b>($normal, $bonus) (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getBuildingsList</b>($type=null) (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getFaction</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getId</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getManagePopulationMax</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getNatality</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getNbMessageNoRead</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_data.html#a04141c8f1697125b68fb5a843afc33c0">getNumberOfPopulationWhoAreManagedNow</a>($buildingId=null)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getPlanet</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getPlanetId</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getPlanetName</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getPopulation</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getPosX</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getPosY</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getPR</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getProdPr</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getProdRes1</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getProdRes1Bonus</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getProdRes2</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getProdRes2Bonus</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getProdRes3</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getProdRes3Bonus</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getProductionTime</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getRes1</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getRes2</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getRes3</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getTechnologiesList</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getTotalProdRes1</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getTotalProdRes2</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getTotalProdRes3</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getTotalProdResPR</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getUser</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>getUsername</b>() (défini dans <a class="el" href="class_data.html">Data</a>)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_data.html#a48c6fd9c75a46dbf364965f6ff505901">sortBuildingListByType</a>($array, $type)</td><td class="entry"><a class="el" href="class_data.html">Data</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Généré le Dimanche Août 25 2013 23:19:13 pour ApocalySpace par  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
|
gpl-3.0
|
MinerAp/dueler
|
src/main/java/in/nikitapek/dueler/util/SupplementaryTypes.java
|
559
|
package in.nikitapek.dueler.util;
import com.google.gson.reflect.TypeToken;
import in.nikitapek.dueler.Arena;
import org.bukkit.Location;
import java.lang.reflect.Type;
import java.util.TreeSet;
@SuppressWarnings("rawtypes")
public final class SupplementaryTypes {
public static final Type LOCATION = new TypeToken<Location>() {
}.getType();
public static final Type ARENA = new TypeToken<Arena>() {
}.getType();
public static final Type TREESET = new TypeToken<TreeSet>() {
}.getType();
private SupplementaryTypes() {
}
}
|
gpl-3.0
|
williamfdevine/PrettyLinux
|
tools/testing/selftests/powerpc/vphn/test-vphn.c
|
6697
|
#include <stdio.h>
#include <byteswap.h>
#include "utils.h"
#include "subunit.h"
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define cpu_to_be32(x) bswap_32(x)
#define be32_to_cpu(x) bswap_32(x)
#define be16_to_cpup(x) bswap_16(*x)
#define cpu_to_be64(x) bswap_64(x)
#else
#define cpu_to_be32(x) (x)
#define be32_to_cpu(x) (x)
#define be16_to_cpup(x) (*x)
#define cpu_to_be64(x) (x)
#endif
#include "vphn.c"
static struct test
{
char *descr;
long input[VPHN_REGISTER_COUNT];
u32 expected[VPHN_ASSOC_BUFSIZE];
} all_tests[] =
{
{
"vphn: no data",
{
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000000
}
},
{
"vphn: 1 x 16-bit value",
{
0x8001ffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000001,
0x00000001
}
},
{
"vphn: 2 x 16-bit values",
{
0x80018002ffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000002,
0x00000001,
0x00000002
}
},
{
"vphn: 3 x 16-bit values",
{
0x800180028003ffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000003,
0x00000001,
0x00000002,
0x00000003
}
},
{
"vphn: 4 x 16-bit values",
{
0x8001800280038004,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000004,
0x00000001,
0x00000002,
0x00000003,
0x00000004
}
},
{
/* Parsing the next 16-bit value out of the next 64-bit input
* value.
*/
"vphn: 5 x 16-bit values",
{
0x8001800280038004,
0x8005ffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
},
{
0x00000005,
0x00000001,
0x00000002,
0x00000003,
0x00000004,
0x00000005
}
},
{
/* Parse at most 6 x 64-bit input values */
"vphn: 24 x 16-bit values",
{
0x8001800280038004,
0x8005800680078008,
0x8009800a800b800c,
0x800d800e800f8010,
0x8011801280138014,
0x8015801680178018
},
{
0x00000018,
0x00000001,
0x00000002,
0x00000003,
0x00000004,
0x00000005,
0x00000006,
0x00000007,
0x00000008,
0x00000009,
0x0000000a,
0x0000000b,
0x0000000c,
0x0000000d,
0x0000000e,
0x0000000f,
0x00000010,
0x00000011,
0x00000012,
0x00000013,
0x00000014,
0x00000015,
0x00000016,
0x00000017,
0x00000018
}
},
{
"vphn: 1 x 32-bit value",
{
0x00000001ffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000001,
0x00000001
}
},
{
"vphn: 2 x 32-bit values",
{
0x0000000100000002,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000002,
0x00000001,
0x00000002
}
},
{
/* Parsing the next 32-bit value out of the next 64-bit input
* value.
*/
"vphn: 3 x 32-bit values",
{
0x0000000100000002,
0x00000003ffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000003,
0x00000001,
0x00000002,
0x00000003
}
},
{
/* Parse at most 6 x 64-bit input values */
"vphn: 12 x 32-bit values",
{
0x0000000100000002,
0x0000000300000004,
0x0000000500000006,
0x0000000700000008,
0x000000090000000a,
0x0000000b0000000c
},
{
0x0000000c,
0x00000001,
0x00000002,
0x00000003,
0x00000004,
0x00000005,
0x00000006,
0x00000007,
0x00000008,
0x00000009,
0x0000000a,
0x0000000b,
0x0000000c
}
},
{
"vphn: 16-bit value followed by 32-bit value",
{
0x800100000002ffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000002,
0x00000001,
0x00000002
}
},
{
"vphn: 32-bit value followed by 16-bit value",
{
0x000000018002ffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000002,
0x00000001,
0x00000002
}
},
{
/* Parse a 32-bit value split accross two consecutives 64-bit
* input values.
*/
"vphn: 16-bit value followed by 2 x 32-bit values",
{
0x8001000000020000,
0x0003ffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000003,
0x00000001,
0x00000002,
0x00000003,
0x00000004,
0x00000005
}
},
{
/* The lower bits in 0x0001ffff don't get mixed up with the
* 0xffff terminator.
*/
"vphn: 32-bit value has all ones in 16 lower bits",
{
0x0001ffff80028003,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff,
0xffffffffffffffff
},
{
0x00000003,
0x0001ffff,
0x00000002,
0x00000003
}
},
{
/* The following input doesn't follow the specification.
*/
"vphn: last 32-bit value is truncated",
{
0x0000000100000002,
0x0000000300000004,
0x0000000500000006,
0x0000000700000008,
0x000000090000000a,
0x0000000b800c2bad
},
{
0x0000000c,
0x00000001,
0x00000002,
0x00000003,
0x00000004,
0x00000005,
0x00000006,
0x00000007,
0x00000008,
0x00000009,
0x0000000a,
0x0000000b,
0x0000000c
}
},
{
"vphn: garbage after terminator",
{
0xffff2bad2bad2bad,
0x2bad2bad2bad2bad,
0x2bad2bad2bad2bad,
0x2bad2bad2bad2bad,
0x2bad2bad2bad2bad,
0x2bad2bad2bad2bad
},
{
0x00000000
}
},
{
NULL
}
};
static int test_one(struct test *test)
{
__be32 output[VPHN_ASSOC_BUFSIZE] = { 0 };
int i, len;
vphn_unpack_associativity(test->input, output);
len = be32_to_cpu(output[0]);
if (len != test->expected[0])
{
printf("expected %d elements, got %d\n", test->expected[0],
len);
return 1;
}
for (i = 1; i < len; i++)
{
u32 val = be32_to_cpu(output[i]);
if (val != test->expected[i])
{
printf("element #%d is 0x%x, should be 0x%x\n", i, val,
test->expected[i]);
return 1;
}
}
return 0;
}
static int test_vphn(void)
{
static struct test *test;
for (test = all_tests; test->descr; test++)
{
int ret;
ret = test_one(test);
test_finish(test->descr, ret);
if (ret)
{
return ret;
}
}
return 0;
}
int main(int argc, char **argv)
{
return test_harness(test_vphn, "test-vphn");
}
|
gpl-3.0
|
khan0407/FinalArcade
|
report/log/graph.php
|
6948
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Produces a graph of log accesses for a user
*
* Generates an image representing the log data in a graphical manner for a user.
*
* @package report_log
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require("../../config.php");
require_once("$CFG->libdir/graphlib.php");
require_once($CFG->dirroot.'/report/log/locallib.php');
$id = required_param('id', PARAM_INT); // Course ID
$type = required_param('type', PARAM_FILE); // Graph Type
$user = required_param('user', PARAM_INT); // Student ID
$date = optional_param('date', 0, PARAM_INT); // A time of a day (in GMT)
$url = new moodle_url('/report/log/graph.php', array('id'=>$id,'type'=>$type,'user'=>$user,'date'=>$date));
$PAGE->set_url($url);
if ($type !== "usercourse.png" and $type !== "userday.png") {
$type = 'userday.png';
}
$course = $DB->get_record("course", array("id"=>$id), '*', MUST_EXIST);
$user = $DB->get_record("user", array("id"=>$user, 'deleted'=>0), '*', MUST_EXIST);
$coursecontext = context_course::instance($course->id);
$personalcontext = context_user::instance($user->id);
if ($USER->id != $user->id and has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)
and !is_enrolled($coursecontext, $USER) and is_enrolled($coursecontext, $user)) {
//TODO: do not require parents to be enrolled in courses - this is a hack!
require_login();
$PAGE->set_course($course);
} else {
require_login($course);
}
list($all, $today) = report_log_can_access_user_report($user, $course);
if ($type === "userday.png") {
if (!$today) {
require_capability('report/log:viewtoday', $coursecontext);
}
} else {
if (!$all) {
require_capability('report/log:view', $coursecontext);
}
}
add_to_log($course->id, 'course', 'report log', "report/log/graph.php?user=$user->id&id=$course->id&type=$type&date=$date", $course->id);
$logs = array();
$timenow = time();
if ($type === "usercourse.png") {
$site = get_site();
if ($course->id == $site->id) {
$courseselect = 0;
} else {
$courseselect = $course->id;
}
$maxseconds = REPORT_LOG_MAX_DISPLAY * 3600 * 24; // seconds
//$maxseconds = 60 * 3600 * 24; // seconds
if ($timenow - $course->startdate > $maxseconds) {
$course->startdate = $timenow - $maxseconds;
}
if (!empty($CFG->loglifetime)) {
$maxseconds = $CFG->loglifetime * 3600 * 24; // seconds
if ($timenow - $course->startdate > $maxseconds) {
$course->startdate = $timenow - $maxseconds;
}
}
$timestart = $coursestart = usergetmidnight($course->startdate);
if ((($timenow - $timestart)/86400.0) > 40) {
$reducedays = 7;
} else {
$reducedays = 0;
}
$days = array();
$i = 0;
while ($timestart < $timenow) {
$timefinish = $timestart + 86400;
if ($reducedays) {
if ($i % $reducedays) {
$days[$i] = "";
} else {
$days[$i] = userdate($timestart, "%a %d %b");
}
} else {
$days[$i] = userdate($timestart, "%a %d %b");
}
$logs[$i] = 0;
$i++;
$timestart = $timefinish;
}
if ($rawlogs = get_logs_usercourse($user->id, $courseselect, $coursestart)) {
foreach ($rawlogs as $rawlog) {
$logs[$rawlog->day] = $rawlog->num;
}
}
$graph = new graph(750, 400);
<<<<<<< HEAD
=======
$a = new stdClass();
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
$a->coursename = format_string($course->shortname, true, array('context' => $coursecontext));
$a->username = fullname($user, true);
$graph->parameter['title'] = get_string("hitsoncourse", "", $a);
$graph->x_data = $days;
$graph->y_data['logs'] = $logs;
$graph->y_order = array('logs');
if (!empty($CFG->preferlinegraphs)) {
$graph->y_format['logs'] = array('colour' => 'blue','line' => 'line');
} else {
$graph->y_format['logs'] = array('colour' => 'blue','bar' => 'fill','bar_size' => 0.6);
$graph->parameter['bar_spacing'] = 0;
}
$graph->parameter['y_label_left'] = get_string("hits");
$graph->parameter['label_size'] = "12";
$graph->parameter['x_axis_angle'] = 90;
$graph->parameter['x_label_angle'] = 0;
$graph->parameter['tick_length'] = 0;
$graph->parameter['shadow'] = 'none';
error_reporting(5); // ignore most warnings such as font problems etc
$graph->draw_stack();
} else {
$site = get_site();
if ($course->id == $site->id) {
$courseselect = 0;
} else {
$courseselect = $course->id;
}
if ($date) {
$daystart = usergetmidnight($date);
} else {
$daystart = usergetmidnight(time());
}
$dayfinish = $daystart + 86400;
$hours = array();
for ($i=0; $i<=23; $i++) {
$logs[$i] = 0;
$hour = $daystart + $i * 3600;
$hours[$i] = $i;
}
if ($rawlogs = get_logs_userday($user->id, $courseselect, $daystart)) {
foreach ($rawlogs as $rawlog) {
$logs[$rawlog->hour] = $rawlog->num;
}
}
$graph = new graph(750, 400);
<<<<<<< HEAD
=======
$a = new stdClass();
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
$a->coursename = format_string($course->shortname, true, array('context' => $coursecontext));
$a->username = fullname($user, true);
$graph->parameter['title'] = get_string("hitsoncoursetoday", "", $a);
$graph->x_data = $hours;
$graph->y_data['logs'] = $logs;
$graph->y_order = array('logs');
if (!empty($CFG->preferlinegraphs)) {
$graph->y_format['logs'] = array('colour' => 'blue','line' => 'line');
} else {
$graph->y_format['logs'] = array('colour' => 'blue','bar' => 'fill','bar_size' => 0.9);
}
$graph->parameter['y_label_left'] = get_string("hits");
$graph->parameter['label_size'] = "12";
$graph->parameter['x_axis_angle'] = 0;
$graph->parameter['x_label_angle'] = 0;
$graph->parameter['shadow'] = 'none';
error_reporting(5); // ignore most warnings such as font problems etc
$graph->draw_stack();
}
|
gpl-3.0
|
cliffordp/tk-event-weather
|
css/tk-event-weather.css
|
1552
|
.tk-event-weather__error {
border-left: 4px solid #dc3232; /* same red as admin Error notice */
-webkit-box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
margin: 15px;
padding: 5px 12px
}
.tk-event-weather__wrapper {
line-height: 1;
margin: 2rem auto;
}
.tk-event-weather__wrap_single_day {
margin-top: 2rem;
}
h4.tk-event-weather-day-name {
margin-top: 1rem;
margin-bottom: 1rem;
}
.tk-event-weather__after {
margin-top: 0.5rem;
}
/* TK Event Weather and Dark Sky credit links */
.tk-event-weather__credit-links {
margin-top: 2rem;
font-size: 0.5em;
}
.tk-event-weather-day-name {
margin-top: 1rem;
}
.tk-event-weather-day-summary {
margin-bottom: 1rem;
}
.tk-event-weather__wind-direction-icon {
display: inline-block; /* so icon rotation works */
font-size: 2rem;
text-align: center;
vertical-align: middle;
}
/* hourly_horizontal */
.tk-event-weather__wrapper .template-hourly_horizontal__item {
display: inline-block;
text-align: center;
width: 85px;
margin-bottom: 25px; /* in case wraps to multiple line display and for credit links */
}
.tk-event-weather__wrapper .template-hourly_horizontal__item > span {
display: block;
}
.tk-event-weather__wrapper .template-hourly_horizontal__icon {
font-size: 2rem;
}
/* hourly_vertical */
.tk-event-weather__wrapper .template-hourly_vertical__item > span {
display: inline-block;
min-width: 50px;
}
.tk-event-weather__wrapper .template-hourly_vertical__icon {
font-size: 2rem;
text-align: center;
vertical-align: middle;
}
|
gpl-3.0
|
FAForever/faftools
|
faf/tools/fa/update_version.py
|
1436
|
"""
Updates the version in the binary executable of the Forged Alliance game. Will write a new ForgedAlliance.version.exe
file.
Usage:
update_version <version> [--file=<file>] [--dest=<dest>]
Options:
--file=<file> The binary file to update [default: ForgedAlliance.exe]
--dest=<dest> The folder path where to create the patched filed [default: .]
"""
import os
import struct
import shutil
import logging
from docopt import docopt
logger = logging.getLogger(__name__)
def update_exe_version(source, destination, version):
"""
:param source: Path to the static base copy of ForgedAlliance.exe - Hardcoded in API
:param destination: Path this update is being copied to
:param version: New mod version
:return:
"""
# os.path.join due to Python 2.7 compatibility
destination = os.path.join(str(destination), "ForgedAlliance.%s.exe" % version)
shutil.copyfile(str(source), str(destination))
addr = [0xd3d3f, 0x47612c, 0x476665]
f = open(str(destination), 'rb+')
for a in addr:
v = struct.pack("<L", int(version))
f.seek(a+1, 0)
f.write(v)
f.close()
logger.info("Saved ForgedAlliance.%s.exe" % version)
return f
if __name__ == '__main__':
arguments = docopt(__doc__)
source, destination, version = arguments.get('--file'), arguments.get('--dest'), arguments.get('<version>')
update_exe_version(source, destination, version)
|
gpl-3.0
|
berrueta/smw-dump
|
src/main/java/net/berrueta/smwdump/Main.java
|
5672
|
package net.berrueta.smwdump;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Collections;
import java.util.LinkedList;
import net.sourceforge.jwbf.mediawiki.actions.MediaWiki;
import net.sourceforge.jwbf.mediawiki.actions.queries.AllPageTitles;
import net.sourceforge.jwbf.mediawiki.bots.MediaWikiBot;
import org.apache.log4j.Logger;
import org.xml.sax.SAXParseException;
import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.impl.IRIImplException;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.shared.JenaException;
/**
* Script to extract a RDF dump from a SemanticMediaWiki instance by
* means of web requests, i.e., without having local access to the server
* or the database.
*
* Command line syntax: wikiURL [outputfile.rdf]
*
* The wikiURL parameter should be the URL of the wiki, i.e.,
* http://www.crisiswiki.org/
*
* The second parameter is optional. If specified, the collected
* RDF triples will be stored in that file. Otherwise, the
* file "out.rdf" is assumed.
*
* @author Diego Berrueta
*
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
/**
* Milliseconds between requests
*/
private static final long DELAY_MILIS = 0;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please provide the URL to the wiki as the first argument, e.g., http://www.crisiswiki.org/");
} else {
String wikiUrl = args[0];
File outputFile = new File(args.length == 2 ? args[1] : "out.rdf");
MediaWikiBot b = new MediaWikiBot (wikiUrl);
int count = 0;
Model m = ModelFactory.createDefaultModel();
LinkedList<String> articleNames = new LinkedList<String>();
for (int namespace : MediaWiki.NS_ALL) {
logger.info("Geting a list of all pages in namespace " + namespace); // see http://en.wikipedia.org/wiki/Wikipedia:Namespace
AllPageTitles apt = new AllPageTitles(b, namespace);
articleNames.addAll(asList(apt));
}
logger.info("There are " + articleNames.size() + " pages");
long startTime = System.currentTimeMillis();
for (String articleName : articleNames) {
logger.info("Getting RDF data for article (" + count + " of " + articleNames.size() + "): " + articleName);
readArticleIntoModel(m, wikiUrl, articleName);
logger.info("After reading [[" + articleName + "]], the model contains " + m.size() + " triples");
count++;
long currentTime = System.currentTimeMillis();
double progress = (double) count / (double) articleNames.size();
long elapsedTime = currentTime-startTime;
long remainingTime = Math.round(elapsedTime * (1-progress) / progress);
logger.info("Elapsed time (sec): " + (currentTime-startTime)/1000 + " -- Progress: " + Math.floor(progress * 100.0) + "% -- Est. remaining time (sec): " + remainingTime/1000);
Thread.sleep(DELAY_MILIS);
}
removeMalformedURIs(m);
// save data
logger.info("Saving " + m.size() + " triples to file " + outputFile + ", " + count + " pages have been retrieved");
m.write(new FileOutputStream(outputFile)); // avoid FileWriter, see http://jena.sourceforge.net/IO/iohowto.html#encoding
}
}
private static LinkedList<String> asList(AllPageTitles apt) {
LinkedList<String> articleNames = new LinkedList<String>();
for (String articleName : apt) {
articleNames.add(articleName);
}
return articleNames;
}
/**
* Fetches the RDF triples about a wiki article and adds them to the model
*
* @param m
* @param articleName
*/
private static void readArticleIntoModel(Model m, String wikiUrl, String articleName) {
String rdfUrl = wikiUrl + "index.php?title=Special:ExportRDF/" + MediaWiki.encode(articleName);
logger.debug("RDF URL: " + rdfUrl);
try {
m.read(rdfUrl);
} catch (JenaException e) {
logger.error("Skipped " + rdfUrl + " because of parsing errors", e);
}
}
/**
* Remove buggy resource URIs, i.e., URIs that are not valid
*
* @param m
*/
private static void removeMalformedURIs(Model m) {
IRIFactory iriFactory = IRIFactory.semanticWebImplementation();
NodeIterator nodeIterator = m.listObjects();
while (nodeIterator.hasNext()) {
RDFNode node = nodeIterator.next();
if (node.isResource() == true && node.isAnon() == false) {
Resource resource = node.asResource();
logger.info("Checking " + resource.getURI());
try {
iriFactory.construct(resource.getURI()); // just try to construct the IRI, check for exceptions
} catch (IRIImplException e) {
logger.error("Malformed URI fetched from wiki: " + resource.getURI());
logger.info("Removing all triples with object: " + resource.getURI());
m.removeAll(null, null, resource);
}
}
}
}
}
|
gpl-3.0
|
mater06/LEGOChimaOnlineReloaded
|
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/GridViewCommandEventArgs.cs
|
3381
|
// Decompiled with JetBrains decompiler
// Type: System.Web.UI.WebControls.GridViewCommandEventArgs
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
using System.Runtime;
namespace System.Web.UI.WebControls
{
/// <summary>
/// Provides data for the <see cref="E:System.Web.UI.WebControls.GridView.RowCommand"/> event.
/// </summary>
public class GridViewCommandEventArgs : CommandEventArgs
{
private GridViewRow _row;
private object _commandSource;
/// <summary>
/// Gets the source of the command.
/// </summary>
///
/// <returns>
/// A instance of the <see cref="T:System.Object"/> class that represents the source of the command.
/// </returns>
public object CommandSource
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._commandSource;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the control has handled the event.
/// </summary>
///
/// <returns>
/// true if data-bound event code was skipped or has finished; otherwise, false.
/// </returns>
public bool Handled { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set; }
internal GridViewRow Row
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._row;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.GridViewCommandEventArgs"/> class using the specified row, source of the command, and event arguments.
/// </summary>
/// <param name="row">A <see cref="T:System.Web.UI.WebControls.GridViewRow"/> object that represents the row containing the button.</param><param name="commandSource">The source of the command.</param><param name="originalArgs">A <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> object that contains event data.</param>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public GridViewCommandEventArgs(GridViewRow row, object commandSource, CommandEventArgs originalArgs)
: base(originalArgs)
{
this._row = row;
this._commandSource = commandSource;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.GridViewCommandEventArgs"/> class using the specified source of the command and event arguments.
/// </summary>
/// <param name="commandSource">The source of the command.</param><param name="originalArgs">A <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> object that contains event data.</param>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public GridViewCommandEventArgs(object commandSource, CommandEventArgs originalArgs)
: base(originalArgs)
{
this._commandSource = commandSource;
}
}
}
|
gpl-3.0
|
stream-labs/streamlabs-obs
|
app/components-react/shared/inputs/SliderInput.tsx
|
2040
|
import React from 'react';
import { InputComponent, TSlobsInputProps, useInput, ValuesOf } from './inputs';
import { Slider, InputNumber, Row, Col } from 'antd';
import { SliderSingleProps } from 'antd/lib/slider';
import InputWrapper from './InputWrapper';
import omit from 'lodash/omit';
// select which features from the antd lib we are going to use
const ANT_SLIDER_FEATURES = ['min', 'max', 'step', 'tooltipPlacement', 'tipFormatter'] as const;
export type TSliderInputProps = TSlobsInputProps<
{ hasNumberInput?: boolean; slimNumberInput?: boolean },
number,
SliderSingleProps,
ValuesOf<typeof ANT_SLIDER_FEATURES>
>;
export const SliderInput = InputComponent((partialProps: TSliderInputProps) => {
// apply default props
const p = {
hasNumberInput: false,
...partialProps,
};
const { inputAttrs, wrapperAttrs, dataAttrs } = useInput('slider', p, ANT_SLIDER_FEATURES);
const numberInputHeight = p.slimNumberInput ? '50px' : '70px';
function onChangeHandler(val: number) {
// don't emit onChange if the value is out of range
if (typeof val !== 'number') return;
if (typeof p.max === 'number' && val > p.max) return;
if (typeof p.min === 'number' && val < p.min) return;
inputAttrs.onChange(val);
}
return (
<InputWrapper {...wrapperAttrs}>
<Row>
<Col flex="auto" {...dataAttrs} data-role="input" data-value={inputAttrs.value}>
<Slider {...inputAttrs} />
</Col>
{p.hasNumberInput && (
<Col flex={numberInputHeight}>
<InputNumber
// Antd passes tooltipPlacement onto a DOM element when passed as
// a prop to InputNumber, which makes React complain. It's not a
// valid prop for InputNumber anyway, so we just omit it.
{...omit(inputAttrs, 'tooltipPlacement')}
onChange={onChangeHandler}
style={{ width: numberInputHeight, marginLeft: '8px' }}
/>
</Col>
)}
</Row>
</InputWrapper>
);
});
|
gpl-3.0
|
chriskmanx/qmole
|
QMOLEDEV/xorg-ignore/xorg-server-1.5.1/hw/xfree86/xf4bpp/ppcIO.c
|
7733
|
/*
Copyright (c) 1990 X Consortium
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.
Copyright IBM Corporation 1987,1988,1989
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of IBM not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
*/
#ifdef HAVE_XORG_CONFIG_H
#include <xorg-config.h>
#endif
#include <stdlib.h>
#include "xf4bpp.h"
#include "mfbmap.h"
#include "mfb.h"
#include "mi.h"
#include "micmap.h"
#include "scrnintstr.h"
#include "vgaVideo.h"
#if 0
/* XXX This remains to remind of the PC98 difference */
static VisualRec vgaVisuals[] = {
/* StaticColor needs to be first so is can be used as the default */
/* vid class bpRGB cmpE nplan rMask gMask bMask oRed oGreen oBlue */
#ifdef PC98
{ 0, StaticColor, 4, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, StaticGray, 4, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, GrayScale, 4, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, PseudoColor, 4, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
#else
{ 0, StaticColor, 6, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, StaticGray, 6, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, GrayScale, 6, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
{ 0, PseudoColor, 6, 1 << VGA_MAXPLANES, VGA_MAXPLANES, 0, 0, 0, 0, 0, 0 },
#endif
} ;
#endif
void
xf4bppNeverCalled()
{
FatalError("xf4bppNeverCalled was nevertheless called\n");
}
/*ARGSUSED*/
static Bool
vgaScreenClose
(
int idx,
ScreenPtr pScreen
)
{
pScreen->defColormap = 0 ;
return TRUE;
}
static GCPtr sampleGCperDepth[MAXFORMATS+1] = { 0 };
static PixmapPtr samplePixmapPerDepth[1] = { 0 };
/* GJA -- Took this from miscrinit.c.
* We want that devKind contains the distance in bytes between two scanlines.
* The computation that mi does is not appropriate for planar VGA.
* Therefore we provide here our own routine.
*/
/* GJA -- WARNING: this is an internal structure declaration, taken from
* miscrinit.c
*/
typedef struct
{
pointer pbits; /* pointer to framebuffer */
int width; /* delta to add to a framebuffer addr to move one row down */
} miScreenInitParmsRec, *miScreenInitParmsPtr;
/* With the introduction of pixmap privates, the "screen pixmap" can no
* longer be created in miScreenInit, since all the modules that could
* possibly ask for pixmap private space have not been initialized at
* that time. pScreen->CreateScreenResources is called after all
* possible private-requesting modules have been inited; we create the
* screen pixmap here.
*/
static Bool
v16CreateScreenResources
(
ScreenPtr pScreen
)
{
miScreenInitParmsPtr pScrInitParms;
pointer value;
pScrInitParms = (miScreenInitParmsPtr)pScreen->devPrivate;
/* if width is non-zero, pScreen->devPrivate will be a pixmap
* else it will just take the value pbits
*/
if (pScrInitParms->width)
{
PixmapPtr pPixmap;
/* create a pixmap with no data, then redirect it to point to
* the screen
*/
pPixmap = (*pScreen->CreatePixmap)(pScreen, 0, 0, pScreen->rootDepth, 0);
if (!pPixmap)
return FALSE;
if (!(*pScreen->ModifyPixmapHeader)(pPixmap, pScreen->width,
pScreen->height, pScreen->rootDepth, 8 /* bits per pixel */,
/* GJA: was PixmapBytePad(pScrInitParms->width, pScreen->rootDepth), */
#define BITS_PER_BYTE_SHIFT 3
pScrInitParms->width >> BITS_PER_BYTE_SHIFT,
pScrInitParms->pbits))
return FALSE;
value = (pointer)pPixmap;
}
else
{
value = pScrInitParms->pbits;
}
xfree(pScreen->devPrivate); /* freeing miScreenInitParmsRec */
pScreen->devPrivate = value; /* pPixmap or pbits */
return TRUE;
}
Bool
xf4bppScreenInit( pScreen, pbits, virtx, virty, dpix, dpiy, width )
ScreenPtr pScreen;
pointer pbits;
int virtx, virty;
int dpix, dpiy;
int width;
{
Bool ret;
VisualPtr visuals;
DepthPtr depths;
int nvisuals;
int ndepths;
int rootdepth;
VisualID defaultVisual;
rootdepth = 0;
ret = miInitVisuals(&visuals, &depths, &nvisuals, &ndepths, &rootdepth,
&defaultVisual, (unsigned long)1 << 8, 6, -1);
if (!ret)
return FALSE;
pScreen-> id = 0;
pScreen->defColormap = FakeClientID(0);
pScreen-> whitePixel = VGA_WHITE_PIXEL;
pScreen-> blackPixel = VGA_BLACK_PIXEL;
pScreen-> rgf = 0;
*(pScreen-> GCperDepth) = *(sampleGCperDepth);
*(pScreen-> PixmapPerDepth) = *(samplePixmapPerDepth);
pScreen-> CloseScreen = vgaScreenClose;
pScreen-> QueryBestSize = xf4bppQueryBestSize;
pScreen-> GetImage = xf4bppGetImage;
pScreen-> GetSpans = xf4bppGetSpans;
pScreen-> CreateWindow = xf4bppCreateWindowForXYhardware;
pScreen-> DestroyWindow = xf4bppDestroyWindow;
pScreen-> PositionWindow = xf4bppPositionWindow;
pScreen-> CopyWindow = xf4bppCopyWindow;
pScreen-> CreatePixmap = xf4bppCreatePixmap;
pScreen-> CreateGC = xf4bppCreateGC;
pScreen-> CreateColormap = xf4bppInitializeColormap;
pScreen-> DestroyColormap = (DestroyColormapProcPtr)NoopDDA;
pScreen-> InstallColormap = miInstallColormap;
pScreen-> UninstallColormap = miUninstallColormap;
pScreen-> ListInstalledColormaps = miListInstalledColormaps;
pScreen-> StoreColors = (StoreColorsProcPtr)NoopDDA;
pScreen-> ResolveColor = xf4bppResolveColor;
mfbFillInScreen(pScreen);
if (!mfbAllocatePrivates(pScreen, NULL))
return FALSE;
if (!miScreenInit(pScreen, pbits, virtx, virty, dpix, dpiy, width,
rootdepth, ndepths, depths, defaultVisual /* See above */,
nvisuals, visuals))
return FALSE;
/* GJA -- Now we override the supplied default: */
pScreen -> CreateScreenResources = v16CreateScreenResources;
mfbRegisterCopyPlaneProc(pScreen,miCopyPlane); /* GJA -- R4->R5 */
return TRUE;
}
|
gpl-3.0
|
bfabiszewski/ulogger-server
|
js/src/mapapi/api_gmaps.js
|
12253
|
/*
* μlogger
*
* Copyright(C) 2019 Bartek Fabiszewski (www.fabiszewski.net)
*
* This is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
import { lang as $, config } from '../initializer.js';
import MapViewModel from '../mapviewmodel.js';
import uAlert from '../alert.js';
import uTrack from '../track.js';
import uUtils from '../utils.js';
// google maps
/**
* Google Maps API
* @class GoogleMapsApi
* @implements {MapViewModel.api}
*/
export default class GoogleMapsApi {
/**
* @param {MapViewModel} vm
*/
constructor(vm) {
/** @type {google.maps.Map} */
this.map = null;
/** @type {MapViewModel} */
this.viewModel = vm;
/** @type {google.maps.Polyline[]} */
this.polies = [];
/** @type {google.maps.Marker[]} */
this.markers = [];
/** @type {google.maps.InfoWindow} */
this.popup = null;
/** @type {number} */
this.timeoutHandle = 0;
}
/**
* Load and initialize api scripts
* @return {Promise<void, Error>}
*/
init() {
const params = `?${(config.googleKey) ? `key=${config.googleKey}&` : ''}callback=gm_loaded`;
const gmReady = Promise.all([
GoogleMapsApi.onScriptLoaded(),
uUtils.loadScript(`https://maps.googleapis.com/maps/api/js${params}`, 'mapapi_gmaps', GoogleMapsApi.loadTimeoutMs)
]);
return gmReady.then(() => this.initMap());
}
/**
* Listen to Google Maps callbacks
* @return {Promise<void, Error>}
*/
static onScriptLoaded() {
const timeout = uUtils.timeoutPromise(GoogleMapsApi.loadTimeoutMs);
const gmInitialize = new Promise((resolve, reject) => {
window.gm_loaded = () => {
GoogleMapsApi.gmInitialized = true;
resolve();
};
window.gm_authFailure = () => {
GoogleMapsApi.authError = true;
let message = $._('apifailure', 'Google Maps');
message += '<br><br>' + $._('gmauthfailure');
message += '<br><br>' + $._('gmapilink');
if (GoogleMapsApi.gmInitialized) {
uAlert.error(message);
}
reject(new Error(message));
};
if (GoogleMapsApi.authError) {
window.gm_authFailure();
}
if (GoogleMapsApi.gmInitialized) {
window.gm_loaded();
}
});
return Promise.race([ gmInitialize, timeout ]);
}
/**
* Start map engine when loaded
*/
initMap() {
const mapOptions = {
center: new google.maps.LatLng(config.initLatitude, config.initLongitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN,
scaleControl: true,
controlSize: 30
};
// noinspection JSCheckFunctionSignatures
this.map = new google.maps.Map(this.viewModel.mapElement, mapOptions);
this.popup = new google.maps.InfoWindow();
this.popup.addListener('closeclick', () => {
this.popupClose();
});
this.saveState = () => {
this.viewModel.state.mapParams = this.getState();
};
}
/**
* Clean up API
*/
cleanup() {
this.polies.length = 0;
this.markers.length = 0;
this.popup = null;
if (this.map && this.map.getDiv()) {
this.map.getDiv().innerHTML = '';
}
this.map = null;
}
/**
* Display track
* @param {uPositionSet} track
* @param {boolean} update Should fit bounds if true
* @return {Promise.<void>}
*/
displayTrack(track, update) {
if (!track || !track.hasPositions) {
return Promise.resolve();
}
google.maps.event.clearListeners(this.map, 'idle');
const promise = new Promise((resolve) => {
google.maps.event.addListenerOnce(this.map, 'tilesloaded', () => {
console.log('tilesloaded');
if (this.map) {
this.saveState();
this.map.addListener('idle', this.saveState);
}
resolve();
})
});
// init polyline
const polyOptions = {
strokeColor: config.strokeColor,
strokeOpacity: config.strokeOpacity,
strokeWeight: config.strokeWeight
};
// noinspection JSCheckFunctionSignatures
let poly;
const latlngbounds = new google.maps.LatLngBounds();
if (this.polies.length) {
poly = this.polies[0];
for (let i = 0; i < this.markers.length; i++) {
latlngbounds.extend(this.markers[i].getPosition());
}
} else {
poly = new google.maps.Polyline(polyOptions);
poly.setMap(this.map);
this.polies.push(poly);
}
const path = poly.getPath();
let start = this.markers.length;
if (start > 0) {
this.removePoint(--start);
}
for (let i = start; i < track.length; i++) {
// set marker
this.setMarker(i, track);
// update polyline
const position = track.positions[i];
const coordinates = new google.maps.LatLng(position.latitude, position.longitude);
if (track instanceof uTrack) {
path.push(coordinates);
}
latlngbounds.extend(coordinates);
}
if (update) {
this.map.fitBounds(latlngbounds);
if (track.length === 1) {
// only one point, zoom out
const zListener =
google.maps.event.addListenerOnce(this.map, 'bounds_changed', function () {
if (this.getZoom()) {
this.setZoom(15);
}
});
setTimeout(() => {
google.maps.event.removeListener(zListener);
}, 2000);
}
}
return promise;
}
/**
* Clear map
*/
clearMap() {
if (this.polies) {
for (let i = 0; i < this.polies.length; i++) {
this.polies[i].setMap(null);
}
}
if (this.markers) {
for (let i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
}
if (this.popup.getMap()) {
this.popupClose();
}
this.popup.setContent('');
this.markers.length = 0;
this.polies.length = 0;
}
/**
* @param {string} fill Fill color
* @param {boolean} isLarge Is large icon
* @param {boolean} isExtra Is styled with extra mark
* @return {google.maps.Icon}
*/
static getMarkerIcon(fill, isLarge, isExtra) {
// noinspection JSValidateTypes
return {
anchor: new google.maps.Point(15, 35),
url: MapViewModel.getSvgSrc(fill, isLarge, isExtra)
};
}
/**
* Set marker
* @param {uPositionSet} track
* @param {number} id
*/
setMarker(id, track) {
// marker
const position = track.positions[id];
// noinspection JSCheckFunctionSignatures
const marker = new google.maps.Marker({
position: new google.maps.LatLng(position.latitude, position.longitude),
title: (new Date(position.timestamp * 1000)).toLocaleString(),
map: this.map
});
const isExtra = position.hasComment() || position.hasImage();
let icon;
if (track.isLastPosition(id)) {
icon = GoogleMapsApi.getMarkerIcon(config.colorStop, true, isExtra);
} else if (track.isFirstPosition(id)) {
icon = GoogleMapsApi.getMarkerIcon(config.colorStart, true, isExtra);
} else {
icon = GoogleMapsApi.getMarkerIcon(isExtra ? config.colorExtra : config.colorNormal, false, isExtra);
}
marker.setIcon(icon);
marker.addListener('click', () => {
this.popupOpen(id, marker);
});
marker.addListener('mouseover', () => {
this.viewModel.model.markerOver = id;
});
marker.addListener('mouseout', () => {
this.viewModel.model.markerOver = null;
});
this.markers.push(marker);
}
/**
* @param {number} id
*/
removePoint(id) {
if (this.markers.length > id) {
this.markers[id].setMap(null);
this.markers.splice(id, 1);
if (this.polies.length) {
this.polies[0].getPath().removeAt(id);
}
if (this.viewModel.model.markerSelect === id) {
this.popupClose();
}
}
}
/**
* Open popup on marker with given id
* @param {number} id
* @param {google.maps.Marker} marker
*/
popupOpen(id, marker) {
this.popup.setContent(this.viewModel.getPopupElement(id));
this.popup.open(this.map, marker);
this.viewModel.model.markerSelect = id;
}
/**
* Close popup
*/
popupClose() {
this.viewModel.model.markerSelect = null;
this.popup.close();
}
/**
* Animate marker
* @param id Marker sequential id
*/
animateMarker(id) {
if (this.popup.getMap()) {
this.popupClose();
clearTimeout(this.timeoutHandle);
}
const icon = this.markers[id].getIcon();
this.markers[id].setIcon(GoogleMapsApi.getMarkerIcon(config.colorHilite, false, false));
this.markers[id].setAnimation(google.maps.Animation.BOUNCE);
this.timeoutHandle = setTimeout(() => {
this.markers[id].setIcon(icon);
this.markers[id].setAnimation(null);
}, 2000);
}
/**
* Get map bounds
* @returns {number[]} Bounds [ lon_sw, lat_sw, lon_ne, lat_ne ]
*/
getBounds() {
const bounds = this.map.getBounds();
const lat_sw = bounds.getSouthWest().lat();
const lon_sw = bounds.getSouthWest().lng();
const lat_ne = bounds.getNorthEast().lat();
const lon_ne = bounds.getNorthEast().lng();
return [ lon_sw, lat_sw, lon_ne, lat_ne ];
}
/**
* Zoom to track extent
*/
zoomToExtent() {
const bounds = new google.maps.LatLngBounds();
for (let i = 0; i < this.markers.length; i++) {
bounds.extend(this.markers[i].getPosition());
}
this.map.fitBounds(bounds);
}
/**
* Zoom to bounds
* @param {number[]} bounds [ lon_sw, lat_sw, lon_ne, lat_ne ]
*/
zoomToBounds(bounds) {
const sw = new google.maps.LatLng(bounds[1], bounds[0]);
const ne = new google.maps.LatLng(bounds[3], bounds[2]);
const latLngBounds = new google.maps.LatLngBounds(sw, ne);
this.map.fitBounds(latLngBounds);
}
/**
* Is given position within viewport
* @param {number} id
* @return {boolean}
*/
isPositionVisible(id) {
if (id >= this.markers.length) {
return false;
}
return this.map.getBounds().contains(this.markers[id].getPosition());
}
/**
* Center to given position
* @param {number} id
*/
centerToPosition(id) {
if (id < this.markers.length) {
this.map.setCenter(this.markers[id].getPosition());
}
}
/**
* Update size
*/
// eslint-disable-next-line class-methods-use-this
updateSize() {
// ignore for google API
}
/**
* Set default track style
*/
// eslint-disable-next-line class-methods-use-this
setTrackDefaultStyle() {
// ignore for google API
}
/**
* Set gradient style for given track property and scale
* @param {uTrack} track
* @param {string} property
* @param {{ minValue: number, maxValue: number, minColor: number[], maxColor: number[] }} scale
*/
// eslint-disable-next-line class-methods-use-this,no-unused-vars
setTrackGradientStyle(track, property, scale) {
// ignore for google API
}
static get loadTimeoutMs() {
return 10000;
}
/**
* Set map state
* Note: ignores rotation
* @param {MapParams} state
*/
updateState(state) {
this.map.setCenter({ lat: state.center[0], lng: state.center[1] });
this.map.setZoom(state.zoom);
}
/**
* Get map state
* Note: ignores rotation
* @return {MapParams|null}
*/
getState() {
if (this.map) {
const center = this.map.getCenter();
return {
center: [ center.lat(), center.lng() ],
zoom: this.map.getZoom(),
rotation: 0
};
}
return null;
}
// eslint-disable-next-line class-methods-use-this
saveState() {/* empty */}
}
/** @type {boolean} */
GoogleMapsApi.authError = false;
/** @type {boolean} */
GoogleMapsApi.gmInitialized = false;
|
gpl-3.0
|
ximepa/docp
|
templates/claim/manual_list.html
|
2230
|
{% extends 'base.html' %}
{% load staticfiles %}
{% block extra_head %}
{% endblock %}
{% block content %}
<div class="row">
<div class="col-lg-6">
</div><!-- /.col-lg-6 -->
<div class="col-lg-6">
<form method="GET">
<div class="input-group">
{{ filter_form.search }}
<span class="input-group-btn">
<button type="submit" class="btn btn-default" type="button">Go!</button>
</span>
</div><!-- /input-group -->
</form>
<br>
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
<div class="row">
<div class="col-lg-12">
{% for group,val in manual_list_groups.items %}
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ group.pk }}">
{{ group }}
</a>
</h4>
</div>
<div id="collapse{{ group.pk }}" class="panel-collapse collapse in">
{% for manual in val %}
<div class="panel-body">
<a href="/manual/{{ manual.pk }}">
{{ manual.name }} - {{ sensor }}
</a>
</div>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
{% if sensor == False%}
<script type="text/javascript">
$(function() {
$(".collapse").collapse({
toggle: true
})
});
</script>
{% elif sensor == True %}
<script type="text/javascript">
$(function() {
$(".collapse").collapse({
toggle: false
})
});
</script>
{% endif %}
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
{% endblock %}
|
gpl-3.0
|
jizdoteka/jizdoteka-web
|
apps/web/views/car.py
|
1433
|
from django.views.generic import CreateView, DetailView, UpdateView, ListView
from django.views.generic import DeleteView
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django import http
from django.contrib import messages
from .. import forms
from .. import models
class CarNew(CreateView):
model = models.Car
form_class = forms.CarForm
template_name = 'web/car_new.html'
success_url = reverse_lazy('car_list')
def form_valid(self, form):
form.instance.owner = self.request.user
return super(CarNew, self).form_valid(form)
class CarUpdate(UpdateView):
model = models.Car
form_class = forms.CarForm
template_name = 'web/car_new.html'
success_url = reverse_lazy('cars')
def dispatch(self, request, *args, **kwargs):
obj = models.Car.objects.filter(pk=kwargs['pk']).filter(
owner=self.request.user)
if not obj:
messages.error(request, _('This car is not yours.'))
return http.HttpResponseRedirect(reverse_lazy('car_list'))
return super(CarUpdate, self).dispatch(request, *args, **kwargs)
class CarList(ListView):
model = models.Car
def get_queryset(self):
return models.Car.objects.filter(owner=self.request.user).all()
class CarDetail(DetailView):
model = models.Car
class CarDelete(DeleteView):
model = models.Car
|
gpl-3.0
|
Philips14171/qt-creator-opensource-src-4.2.1
|
src/shared/qbs/src/lib/corelib/tools/architectures.cpp
|
4533
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2015 Petroules Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "architectures.h"
#include <QMap>
#include <QMapIterator>
#include <QStringList>
namespace qbs {
QString canonicalTargetArchitecture(const QString &architecture,
const QString &vendor,
const QString &system,
const QString &abi)
{
const QString arch = canonicalArchitecture(architecture);
const bool isApple = (vendor == QStringLiteral("apple")
|| system == QStringLiteral("darwin")
|| system == QStringLiteral("macosx")
|| system == QStringLiteral("ios")
|| system == QStringLiteral("tvos")
|| system == QStringLiteral("watchos")
|| abi == QStringLiteral("macho"));
if (arch == QStringLiteral("armv7a") && isApple)
return QStringLiteral("armv7");
if (arch == QStringLiteral("x86"))
return QStringLiteral("i386");
return arch;
}
QString canonicalArchitecture(const QString &architecture)
{
QMap<QString, QStringList> archMap;
archMap.insert(QLatin1String("x86"), QStringList()
<< QLatin1String("i386")
<< QLatin1String("i486")
<< QLatin1String("i586")
<< QLatin1String("i686")
<< QLatin1String("ia32")
<< QLatin1String("ia-32")
<< QLatin1String("x86_32")
<< QLatin1String("x86-32")
<< QLatin1String("intel32")
<< QLatin1String("mingw32"));
archMap.insert(QLatin1String("x86_64"), QStringList()
<< QLatin1String("x86-64")
<< QLatin1String("x64")
<< QLatin1String("amd64")
<< QLatin1String("ia32e")
<< QLatin1String("em64t")
<< QLatin1String("intel64")
<< QLatin1String("mingw64"));
archMap.insert(QLatin1String("arm64"), QStringList()
<< QLatin1String("aarch64"));
archMap.insert(QLatin1String("ia64"), QStringList()
<< QLatin1String("ia-64")
<< QLatin1String("itanium"));
archMap.insert(QLatin1String("ppc"), QStringList()
<< QLatin1String("powerpc"));
archMap.insert(QLatin1String("ppc64"), QStringList()
<< QLatin1String("powerpc64"));
archMap.insert(QLatin1String("ppc64le"), QStringList()
<< QLatin1String("powerpc64le"));
QMapIterator<QString, QStringList> i(archMap);
while (i.hasNext()) {
i.next();
if (i.value().contains(architecture.toLower()))
return i.key();
}
return architecture;
}
} // namespace qbs
|
gpl-3.0
|
xwcg/SpawnBot
|
xLogger/Properties/AssemblyInfo.cs
|
1390
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("xLogger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("xLogger")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bf86f714-1268-4859-988e-b53fc3664328")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-3.0
|
gg-net/dwoss
|
ui/mandator/src/main/java/eu/ggnet/dwoss/mandator/ui/CachedProxy.java
|
4405
|
/*
* Copyright (C) 2014 GG-Net GmbH - Oliver Günther
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.ggnet.dwoss.mandator.ui;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
/**
* Creates an intermediate proxy object for a given interface. All calls are
* cached.
*
* @author Martin Ankerl (martin.ankerl@gmail.at)
* @version $Rev$
*/
public class CachedProxy {
/**
* Query object to find out if the exact same query was already made.
*
* @author Martin Ankerl (martin.ankerl@profactor.at)
* @version $Rev$
*/
private static final class Args {
private final Method mMethod;
private final Object[] mArgs;
private final int mHash;
public Args(final Method m, final Object[] args) {
mMethod = m;
mArgs = args;
// precalculate hash
mHash = calcHash();
}
/**
* Method and all the arguments have to be equal. Assumes that obj is of
* the same type.
*/
@Override
public boolean equals(final Object obj) {
final Args other = (Args)obj;
if ( !mMethod.equals(other.mMethod) ) {
return false;
}
if ( mArgs != null ) {
for (int i = 0; i < mArgs.length; ++i) {
Object o1 = mArgs[i];
Object o2 = other.mArgs[i];
if ( !(o1 == null ? o2 == null : o1.equals(o2)) ) {
return false;
}
}
}
return true;
}
/**
* Use the precalculated hash.
*/
@Override
public int hashCode() {
return mHash;
}
/**
* Try to use a good & fast hash function here.
*/
public int calcHash() {
int h = mMethod.hashCode();
if ( mArgs != null ) {
for (final Object o : mArgs) {
h = h * 65599 + (o == null ? 0 : o.hashCode());
}
}
return h;
}
}
/**
* Creates an intermediate proxy object that uses cached results if
* available, otherwise calls the given code.
*
* @param <T>
* Type of the class.
* @param clazz
* @param code
* The actual calculation code that should be cached.
* @return The proxy.
*/
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> clazz, final T code) {
// create the cache
final Map<Args, Object> argsToOutput = new HashMap<>();
// proxy for the interface T
return (T)Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final Args input = new Args(method, args);
Object result = argsToOutput.get(input);
// check containsKey to support null values
if ( result == null && !argsToOutput.containsKey(input) ) {
// make sure exceptions are handled transparently
try {
result = method.invoke(code, args);
argsToOutput.put(input, result);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
return result;
}
});
}
}
|
gpl-3.0
|
manusis/dblite
|
test/lib/Testing/Selenium/Exception.php
|
1100
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Exception Class for Selenium
*
* PHP versions 5
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* uses PEAR_Exception
*/
//require_once 'PEAR/Exception.php';
/**
* Testing_Selenium_Exception
*
* @category Testing
* @package Testing_Selenium
* @author Shin Ohno <ganchiku at gmail dot com>
* @author Bjoern Schotte <schotte at mayflower dot de>
* @version @package_version@
*/
class Testing_Selenium_Exception extends Exception
{
}
?>
|
gpl-3.0
|
Ifsttar/NoisePlanet
|
noisecapture_calibration.html
|
20143
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Noise-Planet - Scientific tools for environmental noise assessment">
<meta name="author" content="Gwendall Petit (CNRS , Lab-STICC UMR 6285 / DECIDE Team)">
<meta name="author" content="Judicael Picaut (Univ Eiffel / UMRAE)">
<title>Noise-Planet - NoiseCapture calibration</title>
<!-- Bootstrap core CSS -->
<link href="./assets/css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link rel="shortcut icon" href="./assets/ico/favicon.png">
<link href="./assets/css/main.css" rel="stylesheet">
<link href="./assets/css/font-awesome.min.css" rel="stylesheet">
<link href="./assets/css/animate-custom.css" rel="stylesheet">
<link href='./assets/css/lato.css' rel='stylesheet' type='text/css'>
<link href='./assets/css/raleway.css' rel='stylesheet' type='text/css'>
</head>
<body data-spy="scroll" data-offset="0" data-target="#navbar-main" class="txlive">
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- NAVIGATION BAR -->
<script src="./navbar.js"></script>
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- ==== NoiseCapture ==== -->
<div class="container" id="NoiseCapture" name="NoiseCapture">
<div class="row">
<h1 class="centered"><img class="img-responsive" style="display: inline;" src="./assets/img/logos/Logo_noisecapture.png" height="80px" width="80px" alt="Logo NoiseCapture" /> NoiseCapture calibration</h1>
<hr>
<div class="col-lg-8">
<p align="justify">
On the <b>Calibration</b> menu item, users have the opportunity to calibrate their smartphone.
</p>
<p align="justify">
The smartphone calibration is a crucial and recommanded step. Without calibration, you can be sure that the measured data will be <b>wrong</b>!
</p>
<p align="justify">
The methodology is based on the knowledge of a <b>Reference value</b> for the equivalent noise level Leq <i>(in dB, not in dB(A))</i> for a given duration, from a reference device (an acoustic calibrator, a calibrated smartphone, a sound level meter).
Depending on the calibration method, the calibration can be performed for a given frequency band or for the full range (global value).
This <b>Reference value</b> is then compared to the <b>Measured Leq</b> (in dB) using the smartphone. The difference between these two values gives a <b>correction factor</b> (i.e. the signal gain) that will be applied to the input signal.
</p>
<p align="justify"> Warning:
<ul>
<li>The correction factor is applied for the whole signal. Multi-frequency calibration is not possible for now.</li>
<li>The calibration is carried out with dB values, not dB(A).</li>
</ul>
</p>
</div><!-- col-lg-6 -->
<br>
<br>
<div class="col-lg-offset-1 col-lg-3">
<!-- Screenshot -->
<div id="myCarousel" class="carousel slide" data-ride="carousel" >
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active"><img src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration.png" alt="Calibration" style="width:100%;"></div>
<div class="item"><img src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_Manual.jpg" alt="Manual calibration" style="width:100%;"></div>
<div class="item"><img src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_Auto.jpg" alt="Auto calibration" style="width:100%;"></div>
<div class="item"><img src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_Auto_Reference.jpg" alt="Auto calibration with reference" style="width:100%;"></div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div><!-- col-lg-3 -->
</div><!-- row -->
</div><!-- container -->
<div class="container" id="calibration_methods" name="calibration_methods">
<div class="row">
<div class="col-lg-6">
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_menu.png" alt="Calibration menu" width="300px"></p>
</div><!-- col-lg-6 -->
<div class="col-lg-6">
<br>
<br>
<p align="justify">Several calibration methods are possible:
<ol>
<li>Calibration with the help of road traffic</li>
<li>Manual calibration from a reference device</li>
<li>Manual calibration from a calibrator device</li>
<li>Automatic calibration from a calibrated smartphone</li>
</ol>
</p>
</div><!-- col-lg-6 -->
</div><!-- row -->
</div><!-- container -->
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- ==== Calibration with the help of road traffic ==== -->
<div class="container" id="Calibration_from_traffic" name="Calibration_from_traffic">
<div class="row">
<h2 class="centered">Calibration with the help of road traffic (1)</h2>
<hr>
<h3 class="centered">Introduction</h3>
<div class="col-lg-12">
<p align="center">
This calibration protocol is based on the low variability of the average noise emission of individual vehicles. The advantage of this protocol for the user is that it does not require specific equipment, i.e. reference sound source or device, or special knowledge in acoustics. The method consists in measuring the noise level of a few vehicles as they pass through at different measuring points. The measured levels are compared to the levels expected by a numerical model, the difference serving as an offset for subsequent measurements. The robustness of the protocol was tested in real conditions with a set of 8 smartphones. The comparison with a class 1 sound level meter on 6 control points shows an average error on all phones of −0.6 ± 1.2 dB(A).
<br>
This innovative method is described in the following article: Aumond, P., Can, A., Gozalo, G. R., Fortin, N., & Suárez, E. "<a href="https://doi.org/10.1016/j.apacoust.2020.107337" target="blank">Method for in situ acoustic calibration of smartphone-based sound measurement applications</a>". Applied Acoustics, 166, 2020.
</p>
</div><!-- col-lg-8 -->
<h3 class="centered">Performing the calibration</h3>
<br>
<div class="col-lg-4">
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/calibration_sessions_empty.png" alt="Empty calibration" width="200px"></p>
</div><!-- col-lg-4 -->
<div class="col-lg-4">
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/calibration_passingby.png" alt="Empty calibration" width="200px"></p>
</div><!-- col-lg-4 -->
<div class="col-lg-4">
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/calibration_sessions.png" alt="Empty calibration" width="200px"></p>
</div><!-- col-lg-4 -->
<div class="col-lg-12">
<p align="justify">
<ol>
<li>In order to be able to perform the calibration, you must stand on a sidewalk. The measuring position for calibration must be close enough to the road while ensuring your safety. The nearby road must be relatively flat and vehicles must pass at a constant speed (no acceleration or deceleration, and no congestion). The road must be dry and in good conditions.</li>
<li>To start the calibration protocol, please press “New Measurement”</li>
<ul>
<li>Then you need to estimate the distance between your smartphone and the center of the nearest road. The estimate can be rough, no need to take out the measuring tape!</li>
<li>In the same way, it is a question of estimating the average speed of vehicles. If in doubt, you can enter the legal speed for the section of road you are on.</li>
<li>Start the measurement (Play button) and you just have to wait ... You will then see the yellow progress bar advance little by little with each detected passage. On average, a complete measurement lasts between 3 and 5 minutes. In the case of a very particular acoustic phenomenon (a person coming to talk to you, a very noisy motorcycle, etc.) you can press the pause button, this will erase the last 3 seconds of measurements and thus increase the quality of your calibration.</li>
</ul>
<li>At the end of the measurement session, you will be able to return to the main screen, and you will see your measurement displayed. For optimal calibration, repeat this measurement at least in 3 different locations.
</li>
<li>The calibration value displayed is the average of the estimated calibration values for each session. You can then apply this value to your phone with the "apply" button.</li>
</ol>
</p>
</div><!-- col-lg-12 -->
</div><!-- row -->
</div><!-- container -->
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- ==== Calibration from a reference device or a calibrator ==== -->
<div class="container" id="Calibration_from_reference" name="Calibration_from_reference">
<div class="row">
<h2 class="centered">Calibration from a reference device (2) or a calibrator (3)</h2>
<hr>
<h3 class="centered">Performing the calibration</h3>
<div class="col-lg-4">
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_manual_panel.png" alt="Manual calibration" width="300px"></p>
</div><!-- col-lg-8 -->
<div class="col-lg-8">
<p align="justify">
<ol>
<li>In the 'Calibration mode' list <i>("A" on the illustration)</i>, choose the frequency on which you want perform the calibration. If you calibrate from a reference device <i>(e. g. sound level meter)</i>, you can also choose 'Global' from the list to calibrate over the entire measurement spectrum. In the latter case, remember to configure the reference device to perform a measurement in the same frequency band as your smartphone.</li>
<li>Press the START button.</li>
<ul>
<li>Before calibration starts, you have a warm-up time that can help you to prepare your calibration <i>(prepare to turn on the reference device, if necessary)</i>.</li>
<li>Then, the calibration measurement starts for a given duration. For a better accuracy, the measurement duration should be the same both for the smartphone and for the reference device.</li>
</ul>
<li>Once the measurement is done, enter the <b>Reference value</b> <i>(from the reference device)</i> in the edit box and press the <b>APPLY</b> button.</li>
<li>If you do not want to apply the correction factor, you can press the <b>RESET</b> button to perform a new calibration or you can leave the Calibration activity.</li>
</ol>
</p>
</div><!-- col-lg-8 -->
<div class="col-lg-offset-2 col-lg-8">
<h3 class="centered">Testing the calibration</h3>
<p align="justify">
<ol>
<li>Once a correction factor is applied, you can test the calibration by checking the box 'Test gain' <i>("B" on the illustration)</i>.</li>
<li>Press the <b>START</b> button for performing a new measurement and turn on <i>(if necessary)</i> the calibrator.</li>
<li>At the end of the measurement, the Measured Leq should be equal or quite similar to the reference device.</li>
<li>Given the procedure and equipment involved, you may consider acceptable a difference up to 0.5dB between the two values. If the difference is not acceptable, restart the Calibration procedure. After several attempts, if you can not calibrate your smartphone phone with a difference of less than 0.5dB, you can restart with an error of 1dB.</li>
</ol>
</p>
<p align="justify">
When using a 'Global' value for the calibration, make sure that the <b>Reference value</b> will be obtained using the same frequency range that your smartphone.
</p>
<p align="justify">
The 'Calibration warm-up time' and the 'Calibration duration' can be modified in the <b>Settings</b>.
</p>
<p align="justify">
During calibration, the smartphone and the reference device must be used in a similar way.
</p>
</div><!-- col-lg -->
</div><!-- row -->
</div><!-- container -->
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- ==== Automatic calibration from a calibrated smartphone ==== -->
<div class="container" id="Calibration_auto" name="Calibration_auto">
<div class="row">
<h2 class="centered">Automatic calibration from a calibrated smartphone (4)</h2>
<hr>
<div class="col-lg-offset-2 col-lg-8">
<p align="justify">
In this method, a smartphone already calibrated with NoiseCapture, can calibrate one or more smartphones. On the side of the microphones to be calibrated, the procedure is fully automatic. The entire system is controlled by the reference smartphone.
</p>
<h3 class="centered">Performing the calibration</h3>
<p align="justify">
<ol>
<li>The reference smartphone must in "transmitter" mode.</li>
<li>The smartphones to be calibrated must be in "receiver" mode.</li>
<li>On the reference smartphone:</li>
<ol>
<li>Choose the source signal:</li>
<ol>
<li> "Pink noise" : in this case, the smartphone generates a reference signal. It is necessary to use a sound source connected wirelessly with the reference smartphone, the source being at equal distance from all smartphones;</li>
<li>"Ambient noise" : Environmental noise is used for calibration. The sound level must be sufficiently high and the sound field must be relatively "diffuse".</li>
</ol>
<li>Press <b>START</b>; the rest of the procedure is automatic. If needed, you can cancel the current calibration with the <b>CANCEL</b> button.</li>
</ol>
</ol>
</p>
</div><!-- col-lg -->
</div><!-- row -->
<div class="row">
<div class="col-lg-6">
<p align="center">Selection of the Transmitter (1) or Receiver (2) mode</p>
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_Auto_choice.png" alt="Auto Calibration menu" width="300px"></p>
</div><!-- col-lg-6 -->
<div class="col-lg-6">
<p align="center">Selection of the Pink (1) or Ambient (2) noise source</p>
<p align="center"><img class="img-responsive" src="./assets/img/noisecapture_calibration/NoiseCapture_Calibration_noise_type.png" alt="Noise type" width="300px"></p>
</div><!-- col-lg-6 -->
</div><!-- row -->
<br>
</div><!-- container -->
<!------------------------------------------------------------------------------------------------------------------------------------------------------------------>
<!-- FOOTER & CREDITS-->
<!-- Include content present in the "footer_credits.js" file -->
<script src="./footer_credits.js"></script>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="./assets/js/jquery.min.js"></script>
<script type="text/javascript" src="./assets/js/modernizr.custom.js"></script>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="./assets/js/html5shiv.js"></script>
<script src="./assets/js/respond.min.js"></script>
<![endif]-->
<!-- Transifex script -->
<script type="text/javascript">window.liveSettings={api_key:"4c31aac0398149cf971660ee00d6106b"};</script>
<script type="text/javascript" src="//cdn.transifex.com/live.js"></script>
<!-- for GitHub widget -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
<script type="text/javascript" src="./assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="./assets/js/retina.js"></script>
<script type="text/javascript" src="./assets/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="./assets/js/smoothscroll.js"></script>
<script type="text/javascript" src="./assets/js/jquery-func.js"></script>
</body>
</html>
|
gpl-3.0
|
dcoeurjo/ICTV
|
src/cpp/BlitFramebuffer.cpp
|
8912
|
/*
* Copyright 2015
* Hélène Perrier <helene.perrier@liris.cnrs.fr>
* Jérémy Levallois <jeremy.levallois@liris.cnrs.fr>
* David Coeurjolly <david.coeurjolly@liris.cnrs.fr>
* Jacques-Olivier Lachaud <jacques-olivier.lachaud@univ-savoie.fr>
* Jean-Philippe Farrugia <jean-philippe.farrugia@liris.cnrs.fr>
* Jean-Claude Iehl <jean-claude.iehl@liris.cnrs.fr>
*
* This file is part of ICTV.
*
* ICTV 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.
*
* ICTV 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 ICTV. If not, see <http://www.gnu.org/licenses/>
*/
#include "BlitFramebuffer.h"
#include "GL/GLQuery.h"
#include "GL/GLTexture.h"
#include "GL/GLVertexArray.h"
#include "GL/GLBuffer.h"
#include "ProgramManager.h"
#include "Format.h"
void updateFramebufferRegion()
{
float regionw = 0.5f * Parameters::getInstance()->g_window.width / Parameters::getInstance()->g_framebuffer_region.mag;
float regionh = 0.5f * Parameters::getInstance()->g_window.height / Parameters::getInstance()->g_framebuffer_region.mag;
gk::TVec2<float> min(regionw, regionh);
gk::TVec2<float> max(Parameters::getInstance()->g_window.width - regionw, Parameters::getInstance()->g_window.height - regionh);
Parameters::getInstance()->g_framebuffer_region.p[0] = std::max(Parameters::getInstance()->g_framebuffer_region.p[0], min[0]);
Parameters::getInstance()->g_framebuffer_region.p[1] = std::max(Parameters::getInstance()->g_framebuffer_region.p[1], min[1]);
Parameters::getInstance()->g_framebuffer_region.p[0] = std::min(Parameters::getInstance()->g_framebuffer_region.p[0], max[0]);
Parameters::getInstance()->g_framebuffer_region.p[1] = std::min(Parameters::getInstance()->g_framebuffer_region.p[1], max[1]);
glProgramUniform3f (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT],
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_VIEWPORT],
Parameters::getInstance()->g_framebuffer_region.p[0] - regionw,
Parameters::getInstance()->g_framebuffer_region.p[1] - regionh,
Parameters::getInstance()->g_framebuffer_region.mag);
}
void BlitFramebuffer::loadFramebuffersTextures()
{
fprintf (stderr, "Loading framebuffer textures... "); fflush (stderr);
if (glIsTexture (Parameters::getInstance()->g_textures[TEXTURE_Z]))
glDeleteTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_Z]);
if (glIsTexture (Parameters::getInstance()->g_textures[TEXTURE_RGBA]))
glDeleteTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glGenTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_Z]);
glGenTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
// TODO use ARB_texture_storage_multisample asap
if (Parameters::getInstance()->g_window.msaa_factor > 0) {
glBindTexture (GL_TEXTURE_2D_MULTISAMPLE, Parameters::getInstance()->g_textures[TEXTURE_Z]);
glTexImage2DMultisample (GL_TEXTURE_2D_MULTISAMPLE,
Parameters::getInstance()->g_window.msaa_factor,
GL_DEPTH24_STENCIL8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height,
Parameters::getInstance()->g_window.msaa_fixedsamplelocations);
glBindTexture (GL_TEXTURE_2D_MULTISAMPLE, Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glTexImage2DMultisample (GL_TEXTURE_2D_MULTISAMPLE,
Parameters::getInstance()->g_window.msaa_factor,
GL_RGBA8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height,
Parameters::getInstance()->g_window.msaa_fixedsamplelocations);
} else {
glBindTexture (GL_TEXTURE_2D, Parameters::getInstance()->g_textures[TEXTURE_Z]);
glTexStorage2D (GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
glBindTexture (GL_TEXTURE_2D, Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glTexStorage2D (GL_TEXTURE_2D, 1, GL_RGBA8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
}
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::loadFramebuffers()
{
fprintf (stderr, "Loading framebuffers... "); fflush (stderr);
if (glIsFramebuffer (Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]))
glDeleteFramebuffers(1, &Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glGenFramebuffers (1, &Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glBindFramebuffer (GL_FRAMEBUFFER, Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
Parameters::getInstance()->g_window.msaa_factor > 0 ? GL_TEXTURE_2D_MULTISAMPLE
: GL_TEXTURE_2D,
Parameters::getInstance()->g_textures[TEXTURE_RGBA],
0);
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_DEPTH_STENCIL_ATTACHMENT,
Parameters::getInstance()->g_window.msaa_factor > 0 ? GL_TEXTURE_2D_MULTISAMPLE
: GL_TEXTURE_2D,
Parameters::getInstance()->g_textures[TEXTURE_Z],
0);
glDrawBuffer (GL_COLOR_ATTACHMENT0);
if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus (GL_FRAMEBUFFER)) {
fprintf (stderr, "Failure\n");
exit(0);
}
glBindFramebuffer (GL_FRAMEBUFFER, 0);
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::loadProgram()
{
fprintf (stderr, "Loading framebuffer blit program... "); fflush (stderr);
gk::GLCompiler& c = gk::loadProgram(SHADER_PATH("framebuffer_blit.glsl"));
c.defineVertex("MSAA_FACTOR", Format("%i", Parameters::getInstance()->g_window.msaa_factor).text);
c.defineFragment("MSAA_FACTOR", Format("%i", Parameters::getInstance()->g_window.msaa_factor).text);
GLProgram* tmp = c.make();
if (tmp->errors)
exit(-1);
Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT] = tmp->name;
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_VIEWPORT] =
glGetUniformLocation (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT], "u_viewport");
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_SAMPLER] =
glGetUniformLocation (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT], "u_framebuffer_sampler");
glProgramUniform1i (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT],
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_SAMPLER],
TEXTURE_RGBA);
updateFramebufferRegion();
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::blit()
{
/** Blit the framebuffer on screen (done manually to allow MSAA) **/
glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_DEPTH_TEST);
glBindFramebuffer (GL_READ_FRAMEBUFFER, Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
glViewport (0, 0, Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
glUseProgram (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT]);
glBindVertexArray (Parameters::getInstance()->g_vertex_arrays[VERTEX_ARRAY_EMPTY]);
glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
glBindFramebuffer (GL_READ_FRAMEBUFFER, 0);
glBindVertexArray (0);
}
|
gpl-3.0
|
bd808/wikimedia-iegreview
|
src/Dao/AbstractDao.php
|
6999
|
<?php
/**
* @section LICENSE
* This file is part of Wikimedia IEG Grant Review application.
*
* Wikimedia IEG Grant Review application 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.
*
* Wikimedia IEG Grant Review application 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 Wikimedia IEG Grant Review application. If not, see
* <http://www.gnu.org/licenses/>.
*
* @file
* @copyright © 2014 Bryan Davis, Wikimedia Foundation and contributors.
*/
namespace Wikimedia\IEGReview\Dao;
use \PDO;
use \PDOException;
use Psr\Log\LoggerInterface;
/**
* Base class for data access objects.
*
* @author Bryan Davis <bd808@wikimedia.org>
* @copyright © 2014 Bryan Davis, Wikimedia Foundation and contributors.
*/
abstract class AbstractDao {
/**
* @var PDO $db
*/
protected $dbh;
/**
* @var LoggerInterface $logger
*/
protected $logger;
/**
* @param string $dsn PDO data source name
* @param string $user Database user
* @param string $pass Database password
* @param LoggerInterface $logger Log channel
*/
public function __construct( $dsn, $user, $pass, $logger = null ) {
$this->logger = $logger ?: new \Psr\Log\NullLogger();
$this->dbh = new PDO( $dsn, $user, $pass,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true, //FIXME: good idea?
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
}
/**
* Bind values to a prepared statement.
*
* If an associative array of values is provided, the data type to use when
* binding will be inferred by looking for a "<type>_" prefix at the
* beginning of the array key. This can come in very handy if you are using
* parameters in places like LIMIT clauses where binding as a string (the
* default type for PDO binds) will cause a syntax error.
*
* @param \PDOStatement $stmt Previously prepared statement
* @param array $values Values to bind
*/
protected function bind( $stmt, $values ) {
$values = $values ?: array();
if ( (bool)count( array_filter( array_keys( $values ), 'is_string' ) ) ) {
// associative array provided
foreach ( $values as $key => $value ) {
// infer bind type from key prefix
list( $prefix, $ignored ) = explode( '_', "{$key}_", 2 );
$type = \PDO::PARAM_STR;
switch ( $prefix ) {
case 'int':
$type = \PDO::PARAM_INT;
break;
case 'bool':
$type = \PDO::PARAM_BOOL;
break;
case 'null':
$type = \PDO::PARAM_NULL;
break;
default:
$type = \PDO::PARAM_STR;
}
$stmt->bindValue( $key, $value, $type );
}
} else {
// vector provided
$idx = 1;
foreach ( $values as $value ) {
$stmt->bindValue( $idx, $value );
$idx++;
}
}
}
/**
* Prepare and execute an SQL statement and return the first row of results.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return array First response row
*/
protected function fetch( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
$this->bind( $stmt, $params );
$stmt->execute();
return $stmt->fetch();
}
/**
* Prepare and execute an SQL statement and return all results.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return array Result rows
*/
protected function fetchAll( $sql, $params = null ) {
$this->logger->debug( $sql, $params ?: array() );
$stmt = $this->dbh->prepare( $sql );
$this->bind( $stmt, $params );
$stmt->execute();
return $stmt->fetchAll();
}
/**
* Prepare and execute an SQL statement and return all results plus the
* number of rows found on the server side.
*
* The SQL is expected to contain the "SQL_CALC_FOUND_ROWS" option in the
* select statement. If it does not, the number of found rows returned is
* dependent on MySQL's interpretation of the query.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return object StdClass with rows and found memebers
*/
protected function fetchAllWithFound( $sql, $params = null ) {
$ret = new \StdClass;
$ret->rows = $this->fetchAll( $sql, $params );
$ret->found = $this->fetch( 'SELECT FOUND_ROWS() AS found' );
$ret->found = $ret->found['found'];
return $ret;
}
/**
* Prepare and execute an SQL statement in a transaction.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return bool False if an exception was generated, true otherwise
*/
protected function update( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
try {
$this->dbh->begintransaction();
$stmt->execute( $params );
$this->dbh->commit();
return true;
} catch ( PDOException $e) {
$this->dbh->rollback();
$this->logger->error( 'Update failed.', array(
'method' => __METHOD__,
'exception' => $e,
'sql' => $sql,
'params' => $params,
) );
return false;
}
}
/**
* Prepare and execute an SQL statement in a transaction.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return int|bool Last insert id or false if an exception was generated
*/
protected function insert( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
try {
$this->dbh->beginTransaction();
$stmt->execute( $params );
$rowid = $this->dbh->lastInsertId();
$this->dbh->commit();
return $rowid;
} catch ( PDOException $e) {
$this->dbh->rollback();
$this->logger->error( 'Insert failed.', array(
'method' => __METHOD__,
'exception' => $e,
'sql' => $sql,
'params' => $params,
) );
return false;
}
}
/**
* Construct a where clause.
* @param array $where List of conditions
* @param string $conjunction Joining operation ('and' or 'or')
* @return string Where clause or empty string
*/
protected static function buildWhere( array $where, $conjunction = 'AND' ) {
if ( $where ) {
return 'WHERE (' . implode( ") {$conjunction} (", $where ) . ') ';
}
return '';
}
/**
* Create a string by joining all arguments with spaces.
*
* If one or more of the arguments are arrays each element of the array will
* be included independently.
*
* @return string New string
*/
protected static function concat( /*varags*/ ) {
$args = array();
foreach ( func_get_args() as $arg ) {
if ( is_array( $arg ) ) {
$args = array_merge( $args, $arg );
} else {
$args[] = $arg;
}
}
return implode( ' ', $args );
}
} //end AbstractDao
|
gpl-3.0
|
georgmichel/openEMS
|
python/setup.py
|
1466
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 23:48:22 2015
@author: thorsten
"""
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import os, sys
ROOT_DIR = os.path.dirname(__file__)
sys.path.append(os.path.join(ROOT_DIR,'..','..','CSXCAD','python'))
extensions = [
Extension("*", [os.path.join(os.path.dirname(__file__), "openEMS","*.pyx")],
language="c++", # generate C++ code
libraries = ['CSXCAD','openEMS', 'nf2ff']),
]
setup(
name="openEMS",
version = '0.0.33',
description = "Python interface for the openEMS FDTD library",
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Libraries :: Python Modules',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
],
author = 'Thorsten Liebig',
author_email = 'Thorsten.Liebig@gmx.de',
maintainer = 'Thorsten Liebig',
maintainer_email = 'Thorsten.Liebig@gmx.de',
url = 'http://openEMS.de',
packages=["openEMS", ],
package_data={'openEMS': ['*.pxd']},
ext_modules = cythonize(extensions)
)
|
gpl-3.0
|
manuelsc/Raven-Messenger
|
Raven App/src/main/java/at/flack/activity/SMSDefaultDelivery.java
|
1519
|
/*
Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek
contact@ravenapp.org
This file is part of Raven.
Raven 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.
Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>.
*/
package at.flack.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SMSDefaultDelivery extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("at.flack");
if (intent.hasExtra("smsto"))
launchIntent.putExtra("CONTACT_NUMBER", intent.getStringExtra("smsto"));
startActivity(launchIntent);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
|
gpl-3.0
|
Themaister/RetroArch
|
gfx/drivers/ps2_gfx.c
|
26338
|
/* RetroArch - A frontend for libretro.
* Copyright (C) 2018 - Francisco Javier Trujillo Mata - fjtrujy
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <kernel.h>
#include <gsKit.h>
#include <gsInline.h>
#include "../../driver.h"
#include "../../retroarch.h"
#include "../../verbosity.h"
#include "../../libretro-common/include/libretro_gskit_ps2.h"
/* Generic tint color */
#define GS_TEXT GS_SETREG_RGBA(0x80, 0x80, 0x80, 0x80)
/* turn black GS Screen */
#define GS_BLACK GS_SETREG_RGBA(0x00, 0x00, 0x00, 0x80)
#define NUM_RM_VMODES 7
#define PS2_RESOLUTION_LAST NUM_RM_VMODES - 1
#define RM_VMODE_AUTO 0
/* RM Vmode -> GS Vmode conversion table */
struct rm_mode
{
char mode;
short int width;
short int height;
short int VCK;
short int interlace;
short int field;
short int PAR1; /* Pixel Aspect Ratio 1 (For video modes with non-square pixels, like PAL/NTSC) */
short int PAR2; /* Pixel Aspect Ratio 2 (For video modes with non-square pixels, like PAL/NTSC) */
char *desc;
};
static struct rm_mode rm_mode_table[NUM_RM_VMODES] = {
/* SDTV modes */
{-1, 704, -1, 4, GS_INTERLACED, GS_FIELD, -1, 11, "AUTO"},
{GS_MODE_PAL, 704, 576, 4, GS_INTERLACED, GS_FIELD, 12, 11, "PAL@50Hz"},
{GS_MODE_NTSC, 704, 480, 4, GS_INTERLACED, GS_FIELD, 10, 11, "NTSC@60Hz"},
/* SDTV special modes */
{GS_MODE_PAL, 704, 288, 4, GS_NONINTERLACED, GS_FRAME, 12, 22, "PAL@50Hz-288p"},
{GS_MODE_NTSC, 704, 240, 4, GS_NONINTERLACED, GS_FRAME, 10, 22, "NTSC@60Hz-240p"},
/* EDTV modes (component cable!) */
{GS_MODE_DTV_480P, 704, 480, 2, GS_NONINTERLACED, GS_FRAME, 10, 11, "DTV480P@60Hz"},
{GS_MODE_DTV_576P, 704, 576, 2, GS_NONINTERLACED, GS_FRAME, 12, 11, "DTV576P@50Hz"},
};
typedef struct ps2_video
{
/* I need to create this additional field
* to be used in the font driver*/
bool clearVRAM_font;
bool menuVisible;
bool vsync;
int vsync_callback_id;
bool force_aspect;
int8_t vmode;
int video_window_offset_x;
int video_window_offset_y;
int PSM;
int tex_filter;
int menu_filter;
video_viewport_t vp;
/* Palette in the cores */
struct retro_hw_render_interface_gskit_ps2 iface;
GSGLOBAL *gsGlobal;
GSTEXTURE *menuTexture;
GSTEXTURE *coreTexture;
/* Last scaling state, for detecting changes */
int iTextureWidth;
int iTextureHeight;
float fDAR;
bool bScaleInteger;
struct retro_hw_ps2_insets padding;
/* Current scaling calculation result */
int iDisplayWidth;
int iDisplayHeight;
} ps2_video_t;
static int vsync_sema_id;
/* PRIVATE METHODS */
static int vsync_handler()
{
iSignalSema(vsync_sema_id);
ExitHandler();
return 0;
}
static void rmEnd(ps2_video_t *ps2)
{
if (!ps2->gsGlobal)
return;
gsKit_deinit_global(ps2->gsGlobal);
gsKit_remove_vsync_handler(ps2->vsync_callback_id);
}
static void updateOffSetsIfNeeded(ps2_video_t *ps2)
{
bool shouldUpdate = false;
settings_t *settings = config_get_ptr();
int video_window_offset_x = settings->ints.video_window_offset_x;
int video_window_offset_y = settings->ints.video_window_offset_y;
if (video_window_offset_x != ps2->video_window_offset_x || video_window_offset_y != ps2->video_window_offset_y)
shouldUpdate = true;
if (!shouldUpdate)
return;
ps2->video_window_offset_x = video_window_offset_x;
ps2->video_window_offset_y = video_window_offset_y;
gsKit_set_display_offset(ps2->gsGlobal, ps2->video_window_offset_x * rm_mode_table[ps2->vmode].VCK, ps2->video_window_offset_y);
RARCH_LOG("PS2_GFX Change offset: %d, %d\n", ps2->video_window_offset_x, ps2->video_window_offset_y);
}
/* Copy of gsKit_sync_flip, but without the 'flip' */
static void gsKit_sync(GSGLOBAL *gsGlobal)
{
if (!gsGlobal->FirstFrame)
WaitSema(vsync_sema_id);
while (PollSema(vsync_sema_id) >= 0)
;
}
/* Copy of gsKit_sync_flip, but without the 'sync' */
static void gsKit_flip(GSGLOBAL *gsGlobal)
{
if (!gsGlobal->FirstFrame)
{
if (gsGlobal->DoubleBuffering == GS_SETTING_ON)
{
GS_SET_DISPFB2(gsGlobal->ScreenBuffer[gsGlobal->ActiveBuffer & 1] / 8192,
gsGlobal->Width / 64, gsGlobal->PSM, 0, 0);
gsGlobal->ActiveBuffer ^= 1;
}
}
gsKit_setactive(gsGlobal);
}
static void rmSetMode(ps2_video_t *ps2, int force)
{
struct rm_mode *mode;
global_t *global = global_get_ptr();
/* we don't want to set the vmode without a reason... */
if (ps2->vmode == global->console.screen.resolutions.current.id && force == 0)
return;
/* Cleanup previous gsKit instance */
if (ps2->vmode >= 0)
{
rmEnd(ps2);
/* Set new mode */
global->console.screen.resolutions.current.id = ps2->vmode;
}
else
/* first driver init */
ps2->vmode = global->console.screen.resolutions.current.id;
mode = &rm_mode_table[ps2->vmode];
/* Invalidate scaling state */
ps2->iTextureWidth = 0;
ps2->iTextureHeight = 0;
ps2->gsGlobal = gsKit_init_global();
gsKit_TexManager_setmode(ps2->gsGlobal, ETM_DIRECT);
ps2->vsync_callback_id = gsKit_add_vsync_handler(vsync_handler);
ps2->gsGlobal->Mode = mode->mode;
ps2->gsGlobal->Width = mode->width;
ps2->gsGlobal->Height = mode->height;
ps2->gsGlobal->Interlace = mode->interlace;
ps2->gsGlobal->Field = mode->field;
ps2->gsGlobal->PSM = GS_PSM_CT16;
ps2->gsGlobal->PSMZ = GS_PSMZ_16S;
ps2->gsGlobal->DoubleBuffering = GS_SETTING_ON;
ps2->gsGlobal->ZBuffering = GS_SETTING_OFF;
ps2->gsGlobal->PrimAlphaEnable = GS_SETTING_OFF;
if ((ps2->gsGlobal->Interlace == GS_INTERLACED) && (ps2->gsGlobal->Field == GS_FRAME))
ps2->gsGlobal->Height /= 2;
/* Coordinate space ranges from 0 to 4096 pixels
* Center the buffer in the coordinate space */
ps2->gsGlobal->OffsetX = ((4096 - ps2->gsGlobal->Width) / 2) * 16;
ps2->gsGlobal->OffsetY = ((4096 - ps2->gsGlobal->Height) / 2) * 16;
gsKit_init_screen(ps2->gsGlobal);
gsKit_mode_switch(ps2->gsGlobal, GS_ONESHOT);
gsKit_set_test(ps2->gsGlobal, GS_ZTEST_OFF);
gsKit_set_test(ps2->gsGlobal, GS_ATEST_OFF);
/* reset the contents of the screen to avoid garbage being displayed */
gsKit_clear(ps2->gsGlobal, GS_BLACK);
gsKit_sync(ps2->gsGlobal);
gsKit_flip(ps2->gsGlobal);
RARCH_LOG("PS2_GFX New vmode: %d, %d x %d\n", ps2->vmode, ps2->gsGlobal->Width, ps2->gsGlobal->Height);
updateOffSetsIfNeeded(ps2);
}
static void rmInit(ps2_video_t *ps2)
{
ee_sema_t sema;
sema.init_count = 0;
sema.max_count = 1;
sema.option = 0;
vsync_sema_id = CreateSema(&sema);
short int mode = gsKit_check_rom();
rm_mode_table[RM_VMODE_AUTO].mode = mode;
rm_mode_table[RM_VMODE_AUTO].height = (mode == GS_MODE_PAL) ? 576 : 480;
rm_mode_table[RM_VMODE_AUTO].PAR1 = (mode == GS_MODE_PAL) ? 12 : 10;
dmaKit_init(D_CTRL_RELE_OFF, D_CTRL_MFD_OFF, D_CTRL_STS_UNSPEC,
D_CTRL_STD_OFF, D_CTRL_RCYC_8, 1 << DMA_CHANNEL_GIF);
/* Initialize the DMAC */
dmaKit_chan_init(DMA_CHANNEL_GIF);
rmSetMode(ps2, 1);
}
static GSTEXTURE *prepare_new_texture(void)
{
GSTEXTURE *texture = (GSTEXTURE *)calloc(1, sizeof(GSTEXTURE));
return texture;
}
static void init_ps2_video(ps2_video_t *ps2)
{
ps2->vmode = -1;
rmInit(ps2);
ps2->vp.x = 0;
ps2->vp.y = 0;
ps2->vp.width = ps2->gsGlobal->Width;
ps2->vp.height = ps2->gsGlobal->Height;
ps2->vp.full_width = ps2->gsGlobal->Width;
ps2->vp.full_height = ps2->gsGlobal->Height;
ps2->menuTexture = prepare_new_texture();
ps2->coreTexture = prepare_new_texture();
ps2->video_window_offset_x = 0;
ps2->video_window_offset_y = 0;
/* Used for cores that supports palette */
ps2->iface.interface_type = RETRO_HW_RENDER_INTERFACE_GSKIT_PS2;
ps2->iface.interface_version = RETRO_HW_RENDER_INTERFACE_GSKIT_PS2_VERSION;
ps2->iface.coreTexture = ps2->coreTexture;
}
static void ps2_gfx_deinit_texture(GSTEXTURE *texture)
{
texture->Mem = NULL;
texture->Clut = NULL;
}
static void set_texture(GSTEXTURE *texture, const void *frame,
int width, int height, int PSM, int filter)
{
texture->Width = width;
texture->Height = height;
texture->PSM = PSM;
texture->Filter = filter;
texture->Mem = (void *)frame;
}
static int ABS(int v)
{
return (v >= 0) ? v : -v;
}
static void setupScalingMode(ps2_video_t *ps2, int iWidth, int iHeight, float fDAR, bool bScaleInteger)
{
GSGLOBAL *gsGlobal = ps2->gsGlobal;
struct rm_mode *currMode = &rm_mode_table[ps2->vmode];
int iBestFBWidth = currMode->width;
int iBestMagH = currMode->VCK - 1;
float fPAR;
/* Calculate the pixel aspect ratio (PAR) */
fPAR = (float)currMode->PAR2 / (float)currMode->PAR1;
#if defined(DEBUG)
printf("Aspect ratio: %.4f x %.4f = %.4f\n", fDAR, fPAR, fDAR * fPAR);
#endif
if (bScaleInteger == false)
{
/* Assume black bars left/right */
ps2->iDisplayHeight = currMode->height;
ps2->iDisplayWidth = (int)((float)ps2->iDisplayHeight * fDAR * fPAR + 0.5f);
if (ps2->iDisplayWidth > currMode->width)
{
/* Really wide screen, black bars top/bottom */
ps2->iDisplayWidth = currMode->width;
ps2->iDisplayHeight = (int)((float)ps2->iDisplayWidth / (fDAR * fPAR) + 0.5f);
}
}
else
{
/* Best match the framebuffer width/height to a multiple of the texture
* Width, rounded down so it always fits */
int iHeightScale = MAX(1, currMode->height / iHeight);
ps2->iDisplayHeight = iHeight * iHeightScale;
/* Height, rounded */
int iWidthScale = MAX(1, (int)((float)ps2->iDisplayHeight * fDAR * fPAR + (float)(iWidth / 2)) / iWidth);
ps2->iDisplayWidth = iWidth * iWidthScale;
#if defined(DEBUG)
printf("Integer scaling:\n");
printf("- Width = %d x %d = %d\n", iWidth, iWidthScale, ps2->iDisplayWidth);
printf("- Height = %d x %d = %d\n", iHeight, iHeightScale, ps2->iDisplayHeight);
#endif
if (currMode->VCK > 1 && ps2->iDisplayWidth < currMode->width)
{
/* We try to best match the number of "VCK" units, for the best output
* For 576i/480i: 1 pixel = 4 VCK (4x super-resolution)
* For 576p/480p: 1 pixel = 2 VCK (2x super-resolution) */
int iTargetVCK = (int)((float)ps2->iDisplayHeight * fDAR * fPAR * (float)currMode->VCK + 0.5f);
int iBestVCK = ps2->iDisplayWidth * currMode->VCK;
/* Try all possible framebuffer widths */
#if defined(DEBUG)
printf("Find match for %d * SCALE * MagH = %d VCK (current = %d VCK)\n", iWidth, iTargetVCK, iBestVCK);
#endif
int iFBWidth;
for (iFBWidth = 64; iFBWidth <= currMode->width; iFBWidth += 64)
{
/* Ignore too small framebuffers */
if (iFBWidth < iWidth)
continue;
iWidthScale = iFBWidth / iWidth;
/* Try all possible magnifications */
int iMagH;
for (iMagH = 0; iMagH < 15; iMagH++)
{
int iVCK = iWidth * iWidthScale * (iMagH + 1);
if (ABS(iTargetVCK - iVCK) < ABS(iTargetVCK - iBestVCK))
{
#if defined(DEBUG)
printf("- found %d * %d * %d = %d\n", iWidth, iWidthScale, iMagH + 1, iVCK);
#endif
/* Better match */
iBestVCK = iVCK;
iBestFBWidth = iFBWidth;
iBestMagH = iMagH;
ps2->iDisplayWidth = iWidth * iWidthScale;
}
}
}
}
}
if ((gsGlobal->Interlace == GS_INTERLACED) && (gsGlobal->Field == GS_FRAME))
ps2->iDisplayHeight /= 2;
#if defined(DEBUG)
printf("Texture resolution:\n");
printf("- Width = %d x %.2f = %d\n", iWidth, (float)ps2->iDisplayWidth / (float)iWidth, ps2->iDisplayWidth);
printf("- Height = %d x %.2f = %d\n", iHeight, (float)ps2->iDisplayHeight / (float)iHeight, ps2->iDisplayHeight);
printf("Setting custom framebuffer:\n");
printf("- Width = %d x %d / %d = %d\n", iBestFBWidth, iBestMagH + 1, currMode->VCK, iBestFBWidth * (iBestMagH + 1) / currMode->VCK);
printf("- Height = %d x %d = %d\n", currMode->height, gsGlobal->MagV + 1, currMode->height * (gsGlobal->MagV + 1));
#endif
/* Center on screen by adding the difference (in VCK units). */
gsGlobal->StartX += (gsGlobal->Width * (gsGlobal->MagH + 1) - iBestFBWidth * (iBestMagH + 1)) / 2;
/* Calculate the actual display width and height, again */
gsGlobal->DW = (iBestMagH + 1) * iBestFBWidth;
/* Override magh */
gsGlobal->MagH = iBestMagH;
/* Reset VRAM allocation */
gsGlobal->CurrentPointer = 0;
/* Allocate new framebuffer(s) */
gsGlobal->ScreenBuffer[0] = gsKit_vram_alloc(gsGlobal, gsKit_texture_size(iBestFBWidth, currMode->height, gsGlobal->PSM), GSKIT_ALLOC_SYSBUFFER);
if (gsGlobal->DoubleBuffering == GS_SETTING_ON)
gsGlobal->ScreenBuffer[1] = gsKit_vram_alloc(gsGlobal, gsKit_texture_size(iBestFBWidth, currMode->height, gsGlobal->PSM), GSKIT_ALLOC_SYSBUFFER);
/* Set the new framebuffer as display buffer */
gsGlobal->Width = iBestFBWidth;
gsKit_display_buffer(gsGlobal);
/* Update DISPLAY1/2 register (code from gsKit) */
GS_SET_DISPLAY1(
gsGlobal->StartX + gsGlobal->StartXOffset,
gsGlobal->StartY + gsGlobal->StartYOffset,
gsGlobal->MagH,
gsGlobal->MagV,
gsGlobal->DW - 1,
gsGlobal->DH - 1);
GS_SET_DISPLAY2(
gsGlobal->StartX + gsGlobal->StartXOffset,
gsGlobal->StartY + gsGlobal->StartYOffset,
gsGlobal->MagH,
gsGlobal->MagV,
gsGlobal->DW - 1,
gsGlobal->DH - 1);
}
static void *ps2_gfx_init(const video_info_t *video,
input_driver_t **input, void **input_data)
{
void *ps2input = NULL;
ps2_video_t *ps2 = (ps2_video_t *)calloc(1, sizeof(ps2_video_t));
*input_data = NULL;
if (!ps2)
return NULL;
init_ps2_video(ps2);
if (video->font_enable)
font_driver_init_osd(ps2,
video,
false,
video->is_threaded,
FONT_DRIVER_RENDER_PS2);
ps2->PSM = (video->rgb32 ? GS_PSM_CT32 : GS_PSM_CT16);
ps2->tex_filter = video->smooth ? GS_FILTER_LINEAR : GS_FILTER_NEAREST;
ps2->force_aspect = video->force_aspect;
ps2->vsync = video->vsync;
if (input && input_data)
{
settings_t *settings = config_get_ptr();
ps2input = input_driver_init_wrap(&input_ps2,
settings->arrays.input_joypad_driver);
*input = ps2input ? &input_ps2 : NULL;
*input_data = ps2input;
}
return ps2;
}
static bool ps2_gfx_frame(void *data, const void *frame,
unsigned width, unsigned height, uint64_t frame_count,
unsigned pitch, const char *msg, video_frame_info_t *video_info)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
GSGLOBAL *gsGlobal = ps2->gsGlobal;
struct font_params *osd_params = (struct font_params *)&video_info->osd_stat_params;
bool statistics_show = video_info->statistics_show;
settings_t *settings = config_get_ptr();
GSTEXTURE *tex = ps2->coreTexture;
if (!width || !height)
return false;
#if defined(DEBUG)
if (frame_count % 180 == 0)
printf("ps2_gfx_frame %llu\n", frame_count);
#endif
/* Check if user change offset values */
updateOffSetsIfNeeded(ps2);
if (frame)
{
/* New frame from core, update */
float fDAR = ps2->force_aspect ? video_driver_get_aspect_ratio() : 0;
bool bScaleInteger = settings->bools.video_scale_integer;
/* Checking if the transfer is done in the core */
if (frame != RETRO_HW_FRAME_BUFFER_VALID)
{
/* SW rendered texture */
int shifh_per_bytes = (ps2->PSM == GS_PSM_CT32) ? 2 : 1;
int real_width = pitch >> shifh_per_bytes;
set_texture(tex, frame, real_width, height, ps2->PSM, ps2->tex_filter);
/* Padding */
ps2->padding = empty_ps2_insets;
ps2->padding.right = real_width - width;
}
else
{
/* "HW" rendered texture */
/* Set current filter mode */
tex->Filter = ps2->tex_filter;
/* Padding */
ps2->padding = ps2->iface.padding;
}
/* Texture dimensions */
int iTextureWidth = tex->Width - ps2->padding.left - ps2->padding.right;
int iTextureHeight = tex->Height - ps2->padding.top - ps2->padding.bottom;
if (ps2->iTextureWidth != iTextureWidth ||
ps2->iTextureHeight != iTextureHeight ||
ps2->fDAR != fDAR ||
ps2->bScaleInteger != bScaleInteger)
{
/* Scaling changed, try to find best matching output mode */
ps2->iTextureWidth = iTextureWidth;
ps2->iTextureHeight = iTextureHeight;
ps2->fDAR = fDAR;
ps2->bScaleInteger = bScaleInteger;
setupScalingMode(ps2, iTextureWidth, iTextureHeight, fDAR, bScaleInteger);
}
gsKit_TexManager_invalidate(ps2->gsGlobal, tex);
}
/* Center texture on framebuffer */
float fDisplayOffsetX = (gsGlobal->Width - ps2->iDisplayWidth + 1) / 2 - 0.5f;
float fDisplayOffsetY = (gsGlobal->Height - ps2->iDisplayHeight + 1) / 2 - 0.5f;
/* Draw */
gsGlobal->PrimAlphaEnable = GS_SETTING_OFF;
gsKit_TexManager_bind(gsGlobal, tex);
gsKit_prim_sprite_texture(gsGlobal, tex,
fDisplayOffsetX, /* X1 */
fDisplayOffsetY, /* Y1 */
ps2->padding.left, /* U1 */
ps2->padding.top, /* V1 */
fDisplayOffsetX + ps2->iDisplayWidth, /* X2 */
fDisplayOffsetY + ps2->iDisplayHeight, /* Y2 */
ps2->padding.left + ps2->iTextureWidth, /* U2 */
ps2->padding.top + ps2->iTextureHeight, /* V2 */
1,
GS_TEXT);
if (ps2->menuVisible)
{
bool texture_empty = !ps2->menuTexture->Width || !ps2->menuTexture->Height;
if (!texture_empty)
{
#define A_COLOR_SOURCE 0
#define A_COLOR_DEST 1
#define A_COLOR_NULL 2
#define A_ALPHA_SOURCE 0
#define A_ALPHA_DEST 1
#define A_ALPHA_FIX 2
/* (A - B) * C + D */
gsKit_set_primalpha(gsGlobal, GS_SETREG_ALPHA(A_COLOR_DEST, A_COLOR_NULL, A_ALPHA_FIX, A_COLOR_SOURCE, 0x20), 0);
gsGlobal->PrimAlphaEnable = GS_SETTING_ON;
gsKit_prim_sprite_texture(gsGlobal, ps2->menuTexture,
-0.5f, /* X1 */
-0.5f, /* Y1 */
0, /* U1 */
0, /* V1 */
-0.5f + (float)gsGlobal->Width, /* X2 */
-0.5f + (float)gsGlobal->Height, /* Y2 */
ps2->menuTexture->Width, /* U2 */
ps2->menuTexture->Height, /* V2 */
2,
GS_TEXT);
}
}
else if (statistics_show)
{
if (osd_params)
font_driver_render_msg(ps2, video_info->stat_text, osd_params, NULL);
}
if (!string_is_empty(msg))
font_driver_render_msg(ps2, msg, NULL, NULL);
if (gsGlobal->DoubleBuffering == GS_SETTING_OFF)
{
/* Without double buffering:
* - Wait for VSync
* - Draw to front buffer (during VSync, so it's not visible to the user) */
if (ps2->vsync)
gsKit_sync(gsGlobal);
gsKit_queue_exec(gsGlobal);
}
else
{
/* With double buffering:
* - Draw to back buffer (invisible to user)
* - Make sure drawing is completed (gsKit_finish)
* - Wait for VSync
* - Flip (back and front) buffers */
gsKit_queue_exec(gsGlobal);
gsKit_finish();
if (ps2->vsync)
gsKit_sync(gsGlobal);
gsKit_flip(gsGlobal);
}
gsKit_TexManager_nextFrame(gsGlobal);
gsKit_clear(gsGlobal, GS_BLACK);
return true;
}
static void ps2_gfx_set_nonblock_state(void *data, bool toggle,
bool adaptive_vsync_enabled, unsigned swap_interval)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (ps2)
ps2->vsync = !toggle;
}
static bool ps2_gfx_alive(void *data) { return true; }
static bool ps2_gfx_focus(void *data) { return true; }
static bool ps2_gfx_suppress_screensaver(void *data, bool enable) { return false; }
static bool ps2_gfx_has_windowed(void *data) { return false; }
static void ps2_gfx_free(void *data)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
gsKit_clear(ps2->gsGlobal, GS_BLACK);
gsKit_vram_clear(ps2->gsGlobal);
font_driver_free_osd();
ps2_gfx_deinit_texture(ps2->menuTexture);
ps2_gfx_deinit_texture(ps2->coreTexture);
free(ps2->menuTexture);
free(ps2->coreTexture);
rmEnd(ps2);
if (vsync_sema_id >= 0)
DeleteSema(vsync_sema_id);
free(data);
}
static bool ps2_gfx_set_shader(void *data,
enum rarch_shader_type type, const char *path) { return false; }
static void ps2_set_video_mode(void *data, unsigned fbWidth, unsigned lines,
bool fullscreen)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (!ps2)
return;
rmSetMode(ps2, 0);
}
static void ps2_set_filtering(void *data, unsigned index, bool smooth, bool ctx_scaling)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
ps2->menu_filter = smooth ? GS_FILTER_LINEAR : GS_FILTER_NEAREST;
}
static void ps2_get_video_output_size(void *data,
unsigned *width, unsigned *height, char *desc, size_t desc_len)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (!ps2)
return;
/* If the current index is out of bound default it to zero */
if (ps2->vmode > PS2_RESOLUTION_LAST || ps2->vmode < 0)
ps2->vmode = 0;
*width = rm_mode_table[ps2->vmode].width;
*height = rm_mode_table[ps2->vmode].height;
strlcpy(desc, rm_mode_table[ps2->vmode].desc, desc_len);
}
static void ps2_get_video_output_prev(void *data)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (!ps2)
return;
if (ps2->vmode == 0)
ps2->vmode = PS2_RESOLUTION_LAST;
else
ps2->vmode--;
}
static void ps2_get_video_output_next(void *data)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (!ps2)
return;
if (ps2->vmode >= PS2_RESOLUTION_LAST)
ps2->vmode = 0;
else
ps2->vmode++;
}
static void ps2_set_texture_frame(void *data, const void *frame, bool rgb32,
unsigned width, unsigned height, float alpha)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
int PSM = (rgb32 ? GS_PSM_CT32 : GS_PSM_CT16);
set_texture(ps2->menuTexture, frame, width, height, PSM, ps2->menu_filter);
gsKit_TexManager_invalidate(ps2->gsGlobal, ps2->menuTexture);
gsKit_TexManager_bind(ps2->gsGlobal, ps2->menuTexture);
}
static void ps2_set_texture_enable(void *data, bool enable, bool fullscreen)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
ps2->menuVisible = enable;
}
static void ps2_set_osd_msg(void *data,
const char *msg,
const void *params, void *font)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
if (ps2)
font_driver_render_msg(data, msg, params, font);
}
static bool ps2_get_hw_render_interface(void *data,
const struct retro_hw_render_interface **iface)
{
ps2_video_t *ps2 = (ps2_video_t *)data;
ps2->iface.padding = empty_ps2_insets;
*iface =
(const struct retro_hw_render_interface *)&ps2->iface;
return true;
}
static const video_poke_interface_t ps2_poke_interface = {
NULL, /* get_flags */
NULL, /* load_texture */
NULL, /* unload_texture */
ps2_set_video_mode,
NULL, /* get_refresh_rate */
ps2_set_filtering,
ps2_get_video_output_size,
ps2_get_video_output_prev,
ps2_get_video_output_next,
NULL, /* get_current_framebuffer */
NULL, /* get_proc_address */
NULL, /* set_aspect_ratio */
NULL, /* apply_state_changes */
ps2_set_texture_frame,
ps2_set_texture_enable,
ps2_set_osd_msg,
NULL, /* show_mouse */
NULL, /* grab_mouse_toggle */
NULL, /* get_current_shader */
NULL, /* get_current_software_framebuffer */
ps2_get_hw_render_interface,
NULL, /* set_hdr_max_nits */
NULL, /* set_hdr_paper_white_nits */
NULL, /* set_hdr_contrast */
NULL /* set_hdr_expand_gamut */
};
static void ps2_gfx_get_poke_interface(void *data,
const video_poke_interface_t **iface)
{
(void)data;
*iface = &ps2_poke_interface;
}
video_driver_t video_ps2 = {
ps2_gfx_init,
ps2_gfx_frame,
ps2_gfx_set_nonblock_state,
ps2_gfx_alive,
ps2_gfx_focus,
ps2_gfx_suppress_screensaver,
ps2_gfx_has_windowed,
ps2_gfx_set_shader,
ps2_gfx_free,
"ps2",
NULL, /* set_viewport */
NULL, /* set_rotation */
NULL, /* viewport_info */
NULL, /* read_viewport */
NULL, /* read_frame_raw */
#ifdef HAVE_OVERLAY
NULL, /* overlay_interface */
#endif
#ifdef HAVE_VIDEO_LAYOUT
NULL,
#endif
ps2_gfx_get_poke_interface,
};
|
gpl-3.0
|
naiaden/SLM
|
RescoreModule.cpp
|
1725
|
/*
* RescoreModule.cpp
*
* Created on: Feb 21, 2017
* Author: louis
*/
#include "RescoreModule.h"
#include "Logging.h"
namespace SLM {
RescoreModule::RescoreModule(SLM::BackoffStrategy* bo, const std::string& outputDirectory)
: backoffStrategy(bo), outputDirectory(outputDirectory)
{
// TODO Auto-generated constructor stub
}
RescoreModule::~RescoreModule() {
// TODO Auto-generated destructor stub
}
void RescoreModule::nextFile(const std::string& originalFileName)
{
this->originalFileName = originalFileName;
nbestList = SLM::NBestList();
}
void RescoreModule::addLine(const std::string& originalSentenceString, int originalRank, double acousticModelScore, double languageModelScore, int numberOfWords)
{
currentLine = new SLM::NBestItem(originalSentenceString, originalRank, acousticModelScore, languageModelScore, numberOfWords);
lprob = 0.0;
oovs = 0;
usedPatternsForLine = 0;
}
void RescoreModule::rescoreLine()
{
L_V << "RescoreModule: rescore ppl =" << pow(2, (-lprob)/usedPatternsForLine) << " P:" << lprob << " U:" << usedPatternsForLine << "\n";
// currentLine->setRescore(pow(2, lprob/usedPatternsForLine));
currentLine->setRescore(lprob);
nbestList.add(currentLine);
}
void RescoreModule::rescoreFile()
{
nbestList.determineNewRanks();
nbestList.printToFile(originalFileName, outputDirectory);
}
void RescoreModule::evaluatePattern(const Pattern& focus, const Pattern& context, bool isOOV)
{
double prob = backoffStrategy->prob(context, focus, isOOV);
if(isOOV)
{
L_P << "RescoreModule: ***";
++oovs;
} else
{
L_P << "RescoreModule: ";
++usedPatterns;
++usedPatternsForLine;
lprob += prob;
}
L_P << "prob =" << prob << "\n";
}
} /* namespace SLM */
|
gpl-3.0
|
HallLinux/Hall_Launcher
|
hall_launcher.py
|
3662
|
#!/usr/bin/env python3
import gi
import os
import webbrowser
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class ButtonWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Hall Launcher")
self.set_border_width(10)
hbox = Gtk.Box(spacing=100)
hbox.set_homogeneous(False)
vbox_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_top.set_homogeneous(False)
vbox_bottom = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_bottom.set_homogeneous(False)
vbox_next = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_next.set_homogeneous(False)
hbox.pack_start(vbox_top, True, True, 0)
hbox.pack_start(vbox_bottom, True, True, 0)
hbox.pack_start(vbox_next, True, True, 0)
button1 = Gtk.Button.new_with_label("HallLinux")
button1.connect("clicked", self.on_halllinux_clicked)
button2 = Gtk.Button.new_with_mnemonic("Mousepad Text Editor")
button2.connect("clicked", self.open_mousepad_clicked)
button_google_chrome = Gtk.Button.new_with_mnemonic("Google Chromium")
button_google_chrome.connect("clicked", self.google_chromium)
button_google_firefox = Gtk.Button.new_with_mnemonic("Google Firefox")
button_google_firefox.connect("clicked", self.google_firefox)
button_youtube_chrome = Gtk.Button.new_with_mnemonic("Youtube Chromium")
button_youtube_chrome.connect("clicked", self.youtube_chromium)
button_youtube_firefox = Gtk.Button.new_with_mnemonic("Youtube Firefox")
button_youtube_firefox.connect("clicked", self.youtube_firefox)
button_drive = Gtk.Button.new_with_mnemonic("Google Drive")
button_drive.connect("clicked", self.google_drive)
button_keep = Gtk.Button.new_with_mnemonic("Google Keep")
button_keep.connect("clicked", self.google_keep)
button_quit = Gtk.Button.new_with_mnemonic("QUIT")
button_quit.connect("clicked", self.quit_clicked)
vbox_top.pack_start(button1, True, True, 0)
vbox_top.pack_start(button2, True, True, 0)
vbox_top.pack_start(button_google_chrome, True, True, 0)
vbox_top.pack_start(button_google_firefox, True, True, 0)
vbox_bottom.pack_start(button_youtube_chrome, True, True, 0)
vbox_bottom.pack_start(button_youtube_firefox, True, True, 0)
vbox_bottom.pack_start(button_drive, True, True, 0)
vbox_bottom.pack_start(button_keep, True, True, 0)
vbox_next.pack_start(button_quit, True, True, 0)
self.add(hbox)
def on_halllinux_clicked(self, button):
webbrowser.get('chromium').open('www.halllinux.com')
def google_chromium(self, button):
webbrowser.get('chromium').open('www.google.com')
def google_firefox(self, button):
webbrowser.get('firefox').open('www.google.com')
def youtube_chromium(self, button):
webbrowser.get('chromium').open('www.youtube.com')
def youtube_firefox(self, button):
webbrowser.get('firefox').open('www.youtube.com')
def google_drive(self, button):
webbrowser.get('chromium').open('drive.google.com')
def google_keep(self, button):
webbrowser.get('chromium').open('keep.google.com')
def open_mousepad_clicked(self, button):
os.system("mousepad&!")
def quit_clicked(self, button):
print("Closing application")
Gtk.main_quit()
win = ButtonWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
gpl-3.0
|