code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Delux address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
| deluxcoin/delux | src/qt/editaddressdialog.cpp | C++ | mit | 3,729 |
package org.csap.agent.stats.service ;
import java.util.concurrent.TimeUnit ;
import javax.management.MBeanServerConnection ;
import javax.management.ObjectName ;
import org.csap.agent.CsapApis ;
import org.csap.agent.model.ServiceAlertsEnum ;
import org.csap.agent.stats.ServiceCollector ;
import org.csap.helpers.CSAP ;
import org.csap.helpers.CsapApplication ;
//import org.javasimon.CounterSample ;
//import org.javasimon.SimonManager ;
//import org.javasimon.Split ;
//import org.javasimon.StopwatchSample ;
//import org.javasimon.jmx.SimonManagerMXBean ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import com.fasterxml.jackson.databind.ObjectMapper ;
import com.fasterxml.jackson.databind.node.ObjectNode ;
public class JmxCustomCollector {
public static final String TOMCAT_SERVLET_CONTEXT_TOKEN = "__CONTEXT__" ;
final Logger logger = LoggerFactory.getLogger( getClass( ) ) ;
ObjectMapper jacksonMapper = new ObjectMapper( ) ;
private ObjectNode deltaLastCollected = jacksonMapper.createObjectNode( ) ;
private ServiceCollector serviceCollector ;
CsapApis csapApis ;
public JmxCustomCollector ( ServiceCollector serviceCollector, CsapApis csapApis ) {
this.serviceCollector = serviceCollector ;
this.csapApis = csapApis ;
}
/**
*
* Each JVM can optionally specify additional attributes to collect
*
* @param instance
* @param serviceNamePort
* @param collectionResults
* @param mbeanConn
*/
public void collect (
MBeanServerConnection mbeanConn ,
ServiceCollectionResults collectionResults ) {
// System.err.println( "\n\n xxx logging issues\n\n " );
logger.debug( "\n\n ============================ Getting JMX Custom Metrics for {} \n\n",
collectionResults.getServiceInstance( ).getServiceName_Port( ) ) ;
collectionResults
.getServiceInstance( )
.getServiceMeters( )
.stream( )
.filter( meter -> ! meter.getMeterType( ).isHttp( ) )
.forEach( serviceMeter -> {
Object attributeCollected = 0 ;
var jmxAttributeTimer = csapApis.metrics( ).startTimer( ) ;
boolean isCollectionSuccesful = false ;
try {
logger.debug( "serviceMeter: {}", serviceMeter ) ;
if ( serviceMeter.getMeterType( ).isMbean( ) ) {
attributeCollected = collectCustomMbean( serviceMeter,
collectionResults, mbeanConn ) ;
// } else if ( serviceMeter.getMeterType().isSimon() ) {
//
// attributeCollected = collectCustomSimon( serviceMeter, simonMgrMxBean,
// mbeanConn, collectionResults ) ;
} else {
logger.warn( "Unexpected meter type: {}", serviceMeter.toString( ) ) ;
throw new Exception( "Unknown metric type" ) ;
}
isCollectionSuccesful = true ;
} catch ( Throwable e ) {
if ( ! serviceMeter.isIgnoreErrors( ) ) {
// SLA will monitor counts
csapApis.metrics( ).incrementCounter( "csap.collect-jmx.service.failures" ) ;
csapApis.metrics( ).incrementCounter( "collect-jmx.service.failures."
+ collectionResults.getServiceInstance( ).getName( ) ) ;
csapApis.metrics( ).incrementCounter( "collect-jmx.service-failures." +
collectionResults.getServiceInstance( ).getName( )
+ "-" + serviceMeter.getCollectionId( ) ) ;
if ( serviceCollector.isShowWarnings( ) ) {
String reason = e.getMessage( ) ;
if ( reason != null && reason.length( ) > 60 ) {
reason = e
.getClass( )
.getName( ) ;
}
logger.warn( CsapApplication.header(
"Failed to collect {} for service {}\n Reason: {}, Cause: {}" ),
serviceMeter.getCollectionId( ), collectionResults.getServiceInstance( )
.getServiceName_Port( ), reason,
e.getCause( ) ) ;
logger.debug( "{}", CSAP.buildCsapStack( e ) ) ;
}
}
logger.debug( "{} Failed getting custom metrics for: {}, reason: {}",
collectionResults.getServiceInstance( ).getServiceName_Port( ),
serviceMeter.getCollectionId( ),
CSAP.buildCsapStack( e ) ) ;
} finally {
long resultLong = -1l ;
if ( attributeCollected instanceof Long ) {
resultLong = (Long) attributeCollected ;
} else if ( attributeCollected instanceof Integer ) {
resultLong = (Integer) attributeCollected ;
} else if ( attributeCollected instanceof Double ) {
Double d = (Double) attributeCollected ;
d = d * serviceMeter.getMultiplyBy( ) ;
if ( serviceMeter.getCollectionId( ).equals( "SystemCpuLoad" )
|| serviceMeter.getCollectionId( ).equals( "ProcessCpuLoad" ) ) {
logger.debug( "Adding multiple by for cpu values: {}", serviceMeter
.getCollectionId( ) ) ;
d = d * 100 ;
} else if ( d < 1 ) {
logger.debug( "{}: Multiplying {} by 1000 to store. Add divideBy 1000",
collectionResults.getServiceInstance( ).getServiceName_Port( ),
serviceMeter.getCollectionId( ) ) ;
d = d * 1000 ;
}
resultLong = Math.round( d ) ;
} else if ( attributeCollected instanceof Boolean ) {
logger.debug( "Got a boolean result" ) ;
Boolean b = (Boolean) attributeCollected ;
if ( b ) {
resultLong = 1 ;
} else {
resultLong = 0 ;
}
}
logger.debug( "{} metric: {} , jmxResultObject: {} , resultLong: {}",
collectionResults.getServiceInstance( ).getName( ),
serviceMeter.getCollectionId( ), attributeCollected, resultLong ) ;
if ( serviceMeter.getCollectionId( ).equalsIgnoreCase( ServiceAlertsEnum.JAVA_HEARTBEAT ) ) {
// for hearbeats, store the time IF it has passed
if ( resultLong == 1 ) {
var nanos = csapApis.metrics( ).stopTimer( jmxAttributeTimer,
"collect-jmx.service-attribute" ) ;
resultLong = TimeUnit.NANOSECONDS.toMillis( nanos ) ;
// some apps return very quickly due to not actually
// implementing. return 1 if that happens
if ( resultLong == 0 ) {
resultLong = 1 ; // minimum of 1 to indicate success
} // for checks.
}
collectionResults
.getServiceInstance( )
.getDefaultContainer( ).setJmxHeartbeatMs( resultLong ) ;
}
if ( ! ( attributeCollected instanceof Double ) ) {
resultLong = resultLong * serviceMeter.getMultiplyBy( ) ;
}
resultLong = Math.round( resultLong / serviceMeter.getDivideBy( serviceCollector
.getCollectionIntervalSeconds( ) ) ) ;
// simon delta is handled in simon collection
if ( serviceMeter.isDelta( ) ) {
long last = resultLong ;
String key = collectionResults.getServiceInstance( ).getServiceName_Port( ) + serviceMeter
.getCollectionId( ) ;
if ( deltaLastCollected.has( key ) && isCollectionSuccesful ) {
resultLong = resultLong - deltaLastCollected.get( key ).asLong( ) ;
if ( resultLong < 0 ) {
resultLong = 0 ;
}
} else {
resultLong = 0 ;
}
// Only update the delta when collection is successful;
// otherwise leave last collected in place
if ( isCollectionSuccesful ) {
deltaLastCollected.put( key, last ) ;
}
}
logger.debug( "\n\n{} ====> metricId: {}, resultLong: {} \n\n",
collectionResults.getServiceInstance( ).getName( ), serviceMeter.getCollectionId( ),
resultLong ) ;
collectionResults.addCustomResultLong( serviceMeter.getCollectionId( ), resultLong ) ;
}
} ) ;
}
private Object collectCustomMbean (
ServiceMeter serviceMeter ,
ServiceCollectionResults jmxResults ,
MBeanServerConnection mbeanConn )
throws Exception {
Object jmxResultObject = 0 ;
String mbeanNameCustom = serviceMeter.getMbeanName( ) ;
if ( mbeanNameCustom.contains( TOMCAT_SERVLET_CONTEXT_TOKEN ) ) {
// Some servlet metrics require version string in name
// logger.info("****** version: " +
// jmxResults.getInstanceConfig().getMavenVersion());
String version = jmxResults
.getServiceInstance( )
.getMavenVersion( ) ;
if ( jmxResults
.getServiceInstance( )
.isScmDeployed( ) ) {
version = jmxResults
.getServiceInstance( )
.getScmVersion( ) ;
version = version.split( " " )[0] ; // first word of
// scm
// scmVersion=3.5.6-SNAPSHOT
// Source build
// by ...
}
// WARNING: version must be updated when testing.
String serviceContext = "//localhost/" + jmxResults
.getServiceInstance( )
.getContext( ) ;
// if ( !jmxResults.getServiceInstance().is_springboot_server() ) {
// serviceContext += "##" + version ;
// }
mbeanNameCustom = mbeanNameCustom.replaceAll( TOMCAT_SERVLET_CONTEXT_TOKEN, serviceContext ) ;
logger.debug( "Using custom name: {} ", mbeanNameCustom ) ;
}
String mbeanAttributeName = serviceMeter.getMbeanAttribute( ) ;
if ( mbeanAttributeName.equals( "SystemCpuLoad" ) ) {
// Reuse already collected values (load is stateful)
jmxResultObject = Long.valueOf( serviceCollector.getCollected_HostCpu( ).get( 0 ).asLong( ) ) ;
} else if ( mbeanAttributeName.equals( "ProcessCpuLoad" ) ) {
// Reuse already collected values
jmxResultObject = Long.valueOf( jmxResults.getCpuPercent( ) ) ;
} else if ( serviceMeter.getCollectionId( ).equalsIgnoreCase( ServiceAlertsEnum.JAVA_HEARTBEAT )
&& ! serviceCollector.isPublishSummaryAndPerformHeartBeat( ) && ! serviceCollector
.isTestHeartBeat( ) ) {
// special case to avoid double heartbeats
// reUse collected value from earlier interval.
jmxResultObject = Long.valueOf( jmxResults.getServiceInstance( ).getDefaultContainer( )
.getJmxHeartbeatMs( ) ) ;
} else {
logger.debug( "Collecting mbean: {}, attribute: {}", mbeanNameCustom, mbeanAttributeName ) ;
jmxResultObject = mbeanConn.getAttribute( new ObjectName( mbeanNameCustom ),
mbeanAttributeName ) ;
}
logger.debug( "Result for {} is: {}", mbeanAttributeName, jmxResultObject ) ;
return jmxResultObject ;
}
}
| csap-platform/csap-core | csap-core-service/src/main/java/org/csap/agent/stats/service/JmxCustomCollector.java | Java | mit | 10,207 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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
* AUTHORS OR COPYRIGHT HOLDERS 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# ifdef _WIN32
# define _WINSOCK_DEPRECATED_NO_WARNINGS 1
# include <Winsock2.h>
# include <ws2tcpip.h>
# include <Windows.h>
# pragma comment(lib, "ws2_32.lib")
# else
# include <sys/socket.h>
# include <netdb.h>
# include <ifaddrs.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# if defined(__FreeBSD__)
# include <netinet/in.h>
# endif
# endif
# include <dsn/internal/ports.h>
# include <dsn/service_api_c.h>
# include <dsn/cpp/address.h>
# include <dsn/internal/task.h>
# include "group_address.h"
# include "uri_address.h"
namespace dsn
{
const rpc_address rpc_group_address::_invalid;
}
#ifdef _WIN32
static void net_init()
{
static std::once_flag flag;
static bool flag_inited = false;
if (!flag_inited)
{
std::call_once(flag, [&]()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
flag_inited = true;
});
}
}
#endif
// name to ip etc.
DSN_API uint32_t dsn_ipv4_from_host(const char* name)
{
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))
{
hostent* hp = ::gethostbyname(name);
int err =
# ifdef _WIN32
(int)::WSAGetLastError()
# else
h_errno
# endif
;
if (hp == nullptr)
{
derror("gethostbyname failed, name = %s, err = %d.", name, err);
return 0;
}
else
{
memcpy(
(void*)&(addr.sin_addr.s_addr),
(const void*)hp->h_addr,
(size_t)hp->h_length
);
}
}
// converts from network byte order to host byte order
return (uint32_t)ntohl(addr.sin_addr.s_addr);
}
// if network_interface is "", then return the first "eth" prefixed non-loopback ipv4 address.
DSN_API uint32_t dsn_ipv4_local(const char* network_interface)
{
uint32_t ret = 0;
# ifndef _WIN32
static const char loopback[4] = { 127, 0, 0, 1 };
struct ifaddrs* ifa = nullptr;
if (getifaddrs(&ifa) == 0)
{
struct ifaddrs* i = ifa;
while (i != nullptr)
{
if (i->ifa_name != nullptr &&
i->ifa_addr != nullptr &&
i->ifa_addr->sa_family == AF_INET
)
{
if (strcmp(i->ifa_name, network_interface) == 0 ||
(network_interface[0] == '\0'
&& strncmp(i->ifa_name, "eth", 3) == 0
&& strncmp((const char*)&((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr, loopback, 4) != 0)
)
ret = (uint32_t)ntohl(((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr);
break;
}
i = i->ifa_next;
}
if (i == nullptr)
{
derror("get local ip from network interfaces failed, network_interface = %s\n", network_interface);
}
if (ifa != nullptr)
{
// remember to free it
freeifaddrs(ifa);
}
}
#endif
return ret;
}
DSN_API const char* dsn_address_to_string(dsn_address_t addr)
{
char* p = dsn::tls_dsn.scratch_next();
auto sz = sizeof(dsn::tls_dsn.scratch_buffer[0]);
struct in_addr net_addr;
# ifdef _WIN32
char* ip_str;
# else
int ip_len;
# endif
switch (addr.u.v4.type)
{
case HOST_TYPE_IPV4:
net_addr.s_addr = htonl((uint32_t)addr.u.v4.ip);
# ifdef _WIN32
ip_str = inet_ntoa(net_addr);
snprintf_p(p, sz, "%s:%hu", ip_str, (uint16_t)addr.u.v4.port);
# else
inet_ntop(AF_INET, &net_addr, p, sz);
ip_len = strlen(p);
snprintf_p(p + ip_len, sz - ip_len, ":%hu", (uint16_t)addr.u.v4.port);
# endif
break;
case HOST_TYPE_URI:
p = (char*)(uintptr_t)addr.u.uri.uri;
break;
case HOST_TYPE_GROUP:
p = (char*)(((dsn::rpc_group_address*)(uintptr_t)(addr.u.group.group))->name());
break;
default:
p = (char*)"invalid address";
break;
}
return (const char*)p;
}
DSN_API dsn_address_t dsn_address_build(
const char* host,
uint16_t port
)
{
dsn::rpc_address addr(host, port);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_ipv4(
uint32_t ipv4,
uint16_t port
)
{
dsn::rpc_address addr(ipv4, port);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_group(
dsn_group_t g
)
{
dsn::rpc_address addr;
addr.assign_group(g);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_uri(
dsn_uri_t uri
)
{
dsn::rpc_address addr;
addr.assign_uri(uri);
return addr.c_addr();
}
DSN_API dsn_group_t dsn_group_build(const char* name) // must be paired with release later
{
auto g = new ::dsn::rpc_group_address(name);
return g;
}
DSN_API bool dsn_group_add(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->add(addr);
}
DSN_API void dsn_group_set_leader(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
grp->set_leader(addr);
}
DSN_API dsn_address_t dsn_group_get_leader(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->leader().c_addr();
}
DSN_API bool dsn_group_is_leader(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->leader() == ep;
}
DSN_API bool dsn_group_is_update_leader_on_rpc_forward(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->is_update_leader_on_rpc_forward();
}
DSN_API void dsn_group_set_update_leader_on_rpc_forward(dsn_group_t g, bool v)
{
auto grp = (::dsn::rpc_group_address*)(g);
grp->set_update_leader_on_rpc_forward(v);
}
DSN_API dsn_address_t dsn_group_next(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->next(addr).c_addr();
}
DSN_API dsn_address_t dsn_group_forward_leader(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
grp->leader_forward();
return grp->leader().c_addr();
}
DSN_API bool dsn_group_remove(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->remove(addr);
}
DSN_API void dsn_group_destroy(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
delete grp;
}
DSN_API dsn_uri_t dsn_uri_build(const char* url) // must be paired with destroy later
{
return (dsn_uri_t)new ::dsn::rpc_uri_address(url);
}
DSN_API void dsn_uri_destroy(dsn_uri_t uri)
{
delete (::dsn::rpc_uri_address*)(uri);
}
| ykwd/rDSN | src/core/core/address.cpp | C++ | mit | 8,222 |
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <stdio.h>
using namespace std;
//Proxy-class for [][] operation
template <typename T>
class Matrix_Row
{
private:
T *row;
size_t m;
public:
Matrix_Row<T>(T* a, size_t cnt) {
row = a;
m = cnt;
}
T& operator[](size_t i) {
if (i >= m) {
assert(!"index out of range");
exit(1);
}
return row[i];
}
};
template <typename T>
class Matrix
{
private:
size_t n; //rows count
size_t m; //columns count
T **arr;
public:
Matrix (int row, int col)
{
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
}
size_t columns()
{
return m;
}
size_t rows()
{
return n;
}
Matrix<T>(const Matrix& mt)
{
int row = mt.n, col = mt.m;
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = mt.arr[i][j];
}
}
}
Matrix<T>& operator=(Matrix& mt)
{
if (this == &mt)
return *this;
int row = mt.n, col = mt.m;
free(arr);
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = mt.arr[i][j];
}
}
return *this;
}
Matrix(Matrix&& mt)
{
n = mt.n;
m = mt.m;
arr = mt.arr;
mt.arr = nullptr;
}
Matrix& operator=(Matrix&& movied)
{
if (this == &movied)
return *this;
free(arr);
arr = movied.arr;
n = movied.n;
m = movied.m;
movied.arr = nullptr;
return *this;
}
Matrix_Row<T> operator[](size_t i)
{
if (i >= n) {
assert(!"index out of range");
exit(1);
}
return Matrix_Row<T>(arr[i], m); //m for check if column index our of range
}
Matrix& operator*=(vector <T> &v)
{
if (m != v.size()) {
assert(!"the vector has an unsuitable length"); //during matrix multiplication on vector from right, vector size must be equal to matrix colimn count
exit(1);
}
Matrix res = Matrix(n, 1);
for (size_t i = 0; i < n; ++i) {
res[i][0] = 0;
for (size_t j = 0; j < m; ++j){
res[i][0] += arr[i][j] * v[j];
}
}
int row = res.n, col = res.m;
free(arr);
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = res.arr[i][j];
}
}
return *this;
}
Matrix& operator*=(T k)
{
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] *= k;
}
}
return *this;
}
int operator==(Matrix& mt)
{
if (n != mt.rows() || m != mt.columns())
return 0;
int flag = 1;
for (size_t i = 0; i < n && flag; ++i) {
for (size_t j = 0; j < m && flag; ++j) {
flag = (arr[i][j] == mt[i][j]);
}
}
return flag;
}
int operator!=(Matrix& mt)
{
return !(*this == mt);
}
//with_size - flag of outputing matrix sizes
//format - format string for 1 element of matrix
void print(int with_size, char *format)
{
if (with_size) {
printf("%lu %lu\n", n, m);
}
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
printf(format, arr[i][j]);
}
printf("\n");
}
}
//print version with standart format of each element outputing
void print(int with_size)
{
char c[] = "%lf ";
print(with_size, c);
}
~Matrix() {
free(arr);
}
};
| mtrempoltsev/msu_cpp_autumn_2017 | homework/Zimnyukov/05/Matrix.cpp | C++ | mit | 4,826 |
<?php
include('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = "Xarafire";
$mail->Password = "symwe!@#123";
$fromname = "Asiimwe Apollo Abraham";
$To = trim($email,"\r\n");
$tContent = '';
$abcd="Stuff is Hard";
$tContent .="<table width='550px' colspan='2' cellpadding='4'>
<tr><td align='center'><img src='imgpath' width='100' height='100'></td></tr>
<tr><td height='20'> </td></tr>
<tr>
<td>
<table cellspacing='1' cellpadding='1' width='100%' height='100%'>
<tr><td align='center'><h2>Hello World<h2></td></tr/>
<tr><td> </td></tr>
<tr><td align='center'>Name: ".trim(NAME,"\r\n")."</td></tr>
<tr><td align='center'>ABCD TEXT: ".$abcd."</td></tr>
<tr><td> </td></tr>
</table>
</td>
</tr>
</table>";
$mail->From = "aasiimwe@dcareug.com";
$mail->FromName = $fromname;
$mail->Subject = "John Doe";
$mail->Body = $tContent;
$mail->AddAddress($To);
$mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low
$mail->Send(); | aasiimweDataCare/Dev_ftf | Dev_CPM/testMail.php | PHP | mit | 1,437 |
export namespace StorageUtils {
let hasLocalStorageCache: boolean;
export function hasLocalStorage(): boolean {
if (hasLocalStorageCache) {
return hasLocalStorageCache;
}
// hasLocalStorage is used to safely ensure we can use localStorage
// taken from https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Feature-detecting_localStorage
let storage: any = { length: 0 };
try {
storage = window['localStorage'];
let x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
hasLocalStorageCache = true;
}
catch (e) {
hasLocalStorageCache = e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
return hasLocalStorageCache;
}
/**
* Stores a string item into localStorage.
* @param key the item's key
* @param data the item's data
*/
export function setItem(key: string, data: string): void {
if (StorageUtils.hasLocalStorage()) {
window.localStorage.setItem(key, data);
}
}
/**
* Gets an item's string value from the localStorage.
* @param key the key to look up its associated value
* @return {string | null} Returns the string if found, null if there is no data stored for the key
*/
export function getItem(key: string): string | null {
if (StorageUtils.hasLocalStorage()) {
return window.localStorage.getItem(key);
} else {
return null;
}
}
/**
* Stores an object into localStorage. The object will be serialized to JSON. The following types are supported
* in addition to the default types:
* - ColorUtils.Color
*
* @param key the key to store the data to
* @param data the object to store
*/
export function setObject<T>(key: string, data: T): void {
if (StorageUtils.hasLocalStorage()) {
let json = JSON.stringify(data);
setItem(key, json);
}
}
/**
* Gets an object for the given key from localStorage. The object will be deserialized from JSON. Beside the
* default types, the following types are supported:
* - ColorUtils.Color
*
* @param key the key to look up its associated object
* @return {any} Returns the object if found, null otherwise
*/
export function getObject<T>(key: string): T {
if (StorageUtils.hasLocalStorage()) {
let json = getItem(key);
if (key) {
let object = JSON.parse(json);
return <T>object;
}
}
return null;
}
}
| bitmovin/bitmovin-player-ui | src/ts/storageutils.ts | TypeScript | mit | 2,905 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Text;
namespace BrowserNatives {
class Maximize {
//Consts
const int SW_SHOWMAXIMIZED = 3;
//Imports
[DllImport("user32.dll")]
static extern bool IsZoomed (IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
//Methods
static void MaximizeWindow (IntPtr hWnd) {
using (new ForegroundWindowGuard())
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
}
static void CheckIsWindowMaximized (IntPtr hWnd) {
Console.Out.WriteLine(IsZoomed(hWnd));
}
static void Main (string[] args) {
if (args.Length == 0 || args.Length > 2) {
Console.Error.Write("Incorrect arguments");
Environment.Exit(1);
}
IntPtr hWnd = (IntPtr)int.Parse(args[0]);
bool isStatusQuery = false;
if (args.Length == 2) {
if (args[1] == "status")
isStatusQuery = true;
else {
Console.Error.Write("Incorrect arguments");
Environment.Exit(1);
}
}
if (isStatusQuery)
CheckIsWindowMaximized(hWnd);
else
MaximizeWindow(hWnd);
}
}
}
| AndreyBelym/testcafe-browser-tools | src/natives/maximize/win/Maximize.cs | C# | mit | 1,625 |
package fr.rohichi.engine3d;
public class Pair {
public int x;
public int y;
}
| Rohichi/3DEngine | src/fr/rohichi/engine3d/Pair.java | Java | mit | 88 |
package info.pinlab.ttada.dbcache;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteConnectionWrapper {
private final String url;
Connection conn = null;
Statement statement = null;
private String tableName = "pinjson";
private SqliteConnectionWrapper(String url) throws SQLException{
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("DB can't be loaded!");
}
this.url = url;
conn = DriverManager.getConnection(this.url);
this.statement = conn.createStatement();
if(isTableExists()){
//-- great, do nothing --//
}else{
this.statement.executeUpdate("create table " + tableName +" (id integer, json string)");
}
}
private boolean isTableExists() throws SQLException{
DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, null, new String[] {"TABLE"});
while(tables.next()){
if(tableName.equals(tables.getString("TABLE_NAME"))){
return true;
}
}
return false;
}
public String readJsonString(String id){
return null;
}
/**
* Updates or creates json data with given id.
*
* @param id for json string
* @param json the json string (escaped)
* @return the id
*/
public String updateJsonString(String id, String json){
return null;
}
public boolean close(){
try{
if(!conn.isClosed()){
conn.close();
return true;
}
}catch(SQLException log){
//-- ignore --//
}
return false;
}
public static class SqliteConnectionBuilder{
String name = null;
String path = null; //-- DB save path - if exists
public SqliteConnectionBuilder setDbName(String name){
this.name = name;
return this;
}
public SqliteConnectionBuilder setDbPath(String path){
this.path = path;
return this;
}
public SqliteConnectionWrapper build(){
if (name == null){
throw new IllegalStateException("DB name can't be null!");
}
SqliteConnectionWrapper conn = null;
try{
conn = new SqliteConnectionWrapper("jdbc:sqlite:sample.db" + name);
}catch(SQLException e){
throw new IllegalStateException("DB error: '" + e.getMessage() + "'");
}
return conn;
}
}
}
| kinokocchi/Ttada | parent/dbcache/src/main/java/info/pinlab/ttada/dbcache/SqliteConnectionWrapper.java | Java | mit | 2,370 |
'use strict';
// 서비스 단위 테스트
describe('서비스 단위 테스트', function() {
beforeEach(module('myApp.services'));
describe('버전 서비스 테스트', function() {
it('현재 버전 반환', inject(function(version) {
expect(version).toEqual('0.1');
}));
});
});
| eu81273/angularjs-testing-example | test/unit/servicesSpec.js | JavaScript | mit | 313 |
<?php
namespace AMQPy;
use AMQPEnvelope;
use AMQPQueue;
use AMQPy\Client\Delivery;
use AMQPy\Serializers\Exceptions\SerializerException;
use AMQPy\Serializers\SerializersPool;
use AMQPy\Support\DeliveryBuilder;
use Exception;
abstract class AbstractListener
{
private $queue;
private $serializers;
private $builder;
private $read_timeout;
public function __construct(AMQPQueue $queue, SerializersPool $serializers_pool, DeliveryBuilder $delivery_builder)
{
$this->serializers = $serializers_pool;
$this->queue = $queue;
$this->builder = $delivery_builder;
}
public function getQueue()
{
return $this->queue;
}
public function getSerializers()
{
return $this->serializers;
}
public function getBuilder()
{
return $this->builder;
}
public function isEndless()
{
return !$this->queue->getConnection()->getReadTimeout();
}
public function setEndless($is_endless)
{
$is_endless = (bool)$is_endless;
if ($this->isEndless() === $is_endless) {
return $is_endless;
}
if ($is_endless) {
$this->read_timeout = $this->queue->getConnection()->getReadTimeout();
$this->queue->getConnection()->setReadTimeout(0);
} else {
if ($this->read_timeout) {
$this->queue->getConnection()->setReadTimeout($this->read_timeout);
$this->read_timeout = null;
}
}
return $is_endless;
}
public function get($auto_ack = false)
{
$envelope = $this->queue->get($auto_ack ? AMQP_AUTOACK : AMQP_NOPARAM);
if ($envelope) {
$delivery = $this->builder->build($envelope);
} else {
$delivery = null;
}
return $delivery;
}
/**
* Attach consumer to process payload from queue
*
* @param AbstractConsumer $consumer Consumer to process payload and handle possible errors
* @param bool $auto_ack Should message been acknowledged upon receive
*
* @return mixed
*
* @throws SerializerException
* @throws Exception Any exception from pre/post-consume handlers and from exception handler
*/
public function consume(AbstractConsumer $consumer, $auto_ack = false)
{
if (!$consumer->active()) {
// prevent dirty consumer been listening on queue
return;
}
$outside_error = null;
try {
$consumer->begin($this);
$this->queue->consume(
function (AMQPEnvelope $envelope /*, AMQPQueue $queue*/) use ($consumer) {
$delivery = $this->builder->build($envelope);
$this->feed($delivery, $consumer);
return $consumer->active();
}, $auto_ack ? AMQP_AUTOACK : AMQP_NOPARAM
);
} catch (Exception $e) {
$outside_error = $e;
}
try {
$this->queue->cancel();
} catch (Exception $e) {
}
$consumer->end($this, $outside_error);
if ($outside_error) {
throw $outside_error;
}
}
abstract public function feed(Delivery $delivery, AbstractConsumer $consumer);
public function accept(Delivery $delivery)
{
return $this->queue->ack($delivery->getEnvelope()->getDeliveryTag());
}
public function resend(Delivery $delivery)
{
$this->queue->nack($delivery->getEnvelope()->getDeliveryTag(), AMQP_REQUEUE);
}
public function drop(Delivery $delivery)
{
$this->queue->nack($delivery->getEnvelope()->getDeliveryTag());
}
}
| pinepain/amqpy | src/AMQPy/AbstractListener.php | PHP | mit | 3,816 |
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the marsExploration function below.
static int marsExploration(String s) {
int count = 0;
char[] c = s.toCharArray();
for(int i=0;i<c.length-2;i+=3) {
if(c[i]!='S') count++;
if(c[i+1]!='O') count++;
if(c[i+2]!='S') count++;
}
return count;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = scanner.nextLine();
int result = marsExploration(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
| dusadpiyush96/Competetive | HackerRank/Algorithm/Strings/MarsExploration.java | Java | mit | 1,004 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using Common;
namespace CustomControls
{
public partial class PasswordMeter : UserControl
{
private string password;
private LinearGradientBrush brush = null;
#region Color Array
private Color[] Colors = {
Color.FromArgb(255,255,0,0),
Color.FromArgb(255,255,1,0),
Color.FromArgb(255,255,2,0),
Color.FromArgb(255,255,4,0),
Color.FromArgb(255,255,5,0),
Color.FromArgb(255,255,6,0),
Color.FromArgb(255,255,7,0),
Color.FromArgb(255,255,8,0),
Color.FromArgb(255,255,10,0),
Color.FromArgb(255,255,11,0),
Color.FromArgb(255,255,12,0),
Color.FromArgb(255,255,13,0),
Color.FromArgb(255,255,15,0),
Color.FromArgb(255,255,16,0),
Color.FromArgb(255,255,17,0),
Color.FromArgb(255,255,19,0),
Color.FromArgb(255,255,20,0),
Color.FromArgb(255,255,21,0),
Color.FromArgb(255,255,22,0),
Color.FromArgb(255,255,23,0),
Color.FromArgb(255,255,25,0),
Color.FromArgb(255,255,26,0),
Color.FromArgb(255,255,27,0),
Color.FromArgb(255,255,28,0),
Color.FromArgb(255,255,30,0),
Color.FromArgb(255,255,31,0),
Color.FromArgb(255,255,32,0),
Color.FromArgb(255,255,34,0),
Color.FromArgb(255,255,35,0),
Color.FromArgb(255,255,36,0),
Color.FromArgb(255,255,37,0),
Color.FromArgb(255,255,38,0),
Color.FromArgb(255,255,40,0),
Color.FromArgb(255,255,41,0),
Color.FromArgb(255,255,42,0),
Color.FromArgb(255,255,43,0),
Color.FromArgb(255,255,44,0),
Color.FromArgb(255,255,46,0),
Color.FromArgb(255,255,47,0),
Color.FromArgb(255,255,48,0),
Color.FromArgb(255,255,49,0),
Color.FromArgb(255,255,51,0),
Color.FromArgb(255,255,52,0),
Color.FromArgb(255,255,53,0),
Color.FromArgb(255,255,55,0),
Color.FromArgb(255,255,56,0),
Color.FromArgb(255,255,57,0),
Color.FromArgb(255,255,58,0),
Color.FromArgb(255,255,59,0),
Color.FromArgb(255,255,61,0),
Color.FromArgb(255,255,62,0),
Color.FromArgb(255,255,63,0),
Color.FromArgb(255,255,64,0),
Color.FromArgb(255,255,66,0),
Color.FromArgb(255,255,67,0),
Color.FromArgb(255,255,68,0),
Color.FromArgb(255,255,70,0),
Color.FromArgb(255,255,71,0),
Color.FromArgb(255,255,72,0),
Color.FromArgb(255,255,73,0),
Color.FromArgb(255,255,74,0),
Color.FromArgb(255,255,76,0),
Color.FromArgb(255,255,77,0),
Color.FromArgb(255,255,78,0),
Color.FromArgb(255,255,80,0),
Color.FromArgb(255,255,81,0),
Color.FromArgb(255,255,82,0),
Color.FromArgb(255,255,83,0),
Color.FromArgb(255,255,85,0),
Color.FromArgb(255,255,86,0),
Color.FromArgb(255,255,87,0),
Color.FromArgb(255,255,88,0),
Color.FromArgb(255,255,89,0),
Color.FromArgb(255,255,91,0),
Color.FromArgb(255,255,92,0),
Color.FromArgb(255,255,93,0),
Color.FromArgb(255,255,95,0),
Color.FromArgb(255,255,96,0),
Color.FromArgb(255,255,97,0),
Color.FromArgb(255,255,98,0),
Color.FromArgb(255,255,100,0),
Color.FromArgb(255,255,101,0),
Color.FromArgb(255,255,102,0),
Color.FromArgb(255,255,103,0),
Color.FromArgb(255,255,104,0),
Color.FromArgb(255,255,106,0),
Color.FromArgb(255,255,107,0),
Color.FromArgb(255,255,108,0),
Color.FromArgb(255,255,110,0),
Color.FromArgb(255,255,111,0),
Color.FromArgb(255,255,112,0),
Color.FromArgb(255,255,113,0),
Color.FromArgb(255,255,115,0),
Color.FromArgb(255,255,116,0),
Color.FromArgb(255,255,117,0),
Color.FromArgb(255,255,118,0),
Color.FromArgb(255,255,119,0),
Color.FromArgb(255,255,121,0),
Color.FromArgb(255,255,122,0),
Color.FromArgb(255,255,123,0),
Color.FromArgb(255,255,124,0),
Color.FromArgb(255,255,125,0),
Color.FromArgb(255,255,127,0),
Color.FromArgb(255,255,128,0),
Color.FromArgb(255,255,129,0),
Color.FromArgb(255,255,131,0),
Color.FromArgb(255,255,132,0),
Color.FromArgb(255,255,133,0),
Color.FromArgb(255,255,134,0),
Color.FromArgb(255,255,136,0),
Color.FromArgb(255,255,137,0),
Color.FromArgb(255,255,138,0),
Color.FromArgb(255,255,139,0),
Color.FromArgb(255,255,140,0),
Color.FromArgb(255,255,142,0),
Color.FromArgb(255,255,143,0),
Color.FromArgb(255,255,144,0),
Color.FromArgb(255,255,146,0),
Color.FromArgb(255,255,147,0),
Color.FromArgb(255,255,148,0),
Color.FromArgb(255,255,149,0),
Color.FromArgb(255,255,151,0),
Color.FromArgb(255,255,152,0),
Color.FromArgb(255,255,153,0),
Color.FromArgb(255,255,154,0),
Color.FromArgb(255,255,155,0),
Color.FromArgb(255,255,155,0),
Color.FromArgb(255,255,156,0),
Color.FromArgb(255,255,157,0),
Color.FromArgb(255,255,158,0),
Color.FromArgb(255,255,159,0),
Color.FromArgb(255,255,159,0),
Color.FromArgb(255,255,160,0),
Color.FromArgb(255,255,161,0),
Color.FromArgb(255,255,162,0),
Color.FromArgb(255,255,163,0),
Color.FromArgb(255,255,163,0),
Color.FromArgb(255,255,164,0),
Color.FromArgb(255,255,165,0),
Color.FromArgb(255,255,166,0),
Color.FromArgb(255,255,167,0),
Color.FromArgb(255,255,167,0),
Color.FromArgb(255,255,168,0),
Color.FromArgb(255,255,169,0),
Color.FromArgb(255,255,170,0),
Color.FromArgb(255,255,171,0),
Color.FromArgb(255,255,171,0),
Color.FromArgb(255,255,172,0),
Color.FromArgb(255,255,173,0),
Color.FromArgb(255,255,174,0),
Color.FromArgb(255,255,175,0),
Color.FromArgb(255,255,175,0),
Color.FromArgb(255,255,176,0),
Color.FromArgb(255,255,177,0),
Color.FromArgb(255,255,178,0),
Color.FromArgb(255,255,179,0),
Color.FromArgb(255,255,179,0),
Color.FromArgb(255,255,180,0),
Color.FromArgb(255,255,181,0),
Color.FromArgb(255,255,181,0),
Color.FromArgb(255,255,182,0),
Color.FromArgb(255,255,183,0),
Color.FromArgb(255,255,184,0),
Color.FromArgb(255,255,185,0),
Color.FromArgb(255,255,185,0),
Color.FromArgb(255,255,186,0),
Color.FromArgb(255,255,187,0),
Color.FromArgb(255,255,188,0),
Color.FromArgb(255,255,189,0),
Color.FromArgb(255,255,189,0),
Color.FromArgb(255,255,190,0),
Color.FromArgb(255,255,191,0),
Color.FromArgb(255,255,192,0),
Color.FromArgb(255,255,193,0),
Color.FromArgb(255,255,193,0),
Color.FromArgb(255,255,194,0),
Color.FromArgb(255,255,195,0),
Color.FromArgb(255,255,196,0),
Color.FromArgb(255,255,197,0),
Color.FromArgb(255,255,197,0),
Color.FromArgb(255,255,198,0),
Color.FromArgb(255,255,199,0),
Color.FromArgb(255,255,200,0),
Color.FromArgb(255,255,201,0),
Color.FromArgb(255,255,201,0),
Color.FromArgb(255,255,202,0),
Color.FromArgb(255,255,203,0),
Color.FromArgb(255,255,204,0),
Color.FromArgb(255,255,205,0),
Color.FromArgb(255,255,205,0),
Color.FromArgb(255,255,206,0),
Color.FromArgb(255,255,207,0),
Color.FromArgb(255,255,208,0),
Color.FromArgb(255,255,209,0),
Color.FromArgb(255,255,209,0),
Color.FromArgb(255,255,210,0),
Color.FromArgb(255,255,211,0),
Color.FromArgb(255,255,212,0),
Color.FromArgb(255,255,213,0),
Color.FromArgb(255,255,213,0),
Color.FromArgb(255,255,214,0),
Color.FromArgb(255,255,215,0),
Color.FromArgb(255,255,216,0),
Color.FromArgb(255,255,217,0),
Color.FromArgb(255,255,217,0),
Color.FromArgb(255,255,218,0),
Color.FromArgb(255,255,219,0),
Color.FromArgb(255,255,220,0),
Color.FromArgb(255,255,221,0),
Color.FromArgb(255,255,221,0),
Color.FromArgb(255,255,222,0),
Color.FromArgb(255,255,223,0),
Color.FromArgb(255,255,224,0),
Color.FromArgb(255,255,225,0),
Color.FromArgb(255,255,225,0),
Color.FromArgb(255,255,226,0),
Color.FromArgb(255,255,227,0),
Color.FromArgb(255,255,228,0),
Color.FromArgb(255,255,229,0),
Color.FromArgb(255,255,229,0),
Color.FromArgb(255,255,230,0),
Color.FromArgb(255,255,231,0),
Color.FromArgb(255,255,232,0),
Color.FromArgb(255,255,233,0),
Color.FromArgb(255,255,233,0),
Color.FromArgb(255,255,234,0),
Color.FromArgb(255,255,235,0),
Color.FromArgb(255,255,236,0),
Color.FromArgb(255,255,237,0),
Color.FromArgb(255,255,237,0),
Color.FromArgb(255,255,238,0),
Color.FromArgb(255,255,239,0),
Color.FromArgb(255,255,240,0),
Color.FromArgb(255,255,241,0),
Color.FromArgb(255,255,241,0),
Color.FromArgb(255,255,242,0),
Color.FromArgb(255,255,243,0),
Color.FromArgb(255,255,244,0),
Color.FromArgb(255,255,245,0),
Color.FromArgb(255,255,245,0),
Color.FromArgb(255,255,246,0),
Color.FromArgb(255,255,247,0),
Color.FromArgb(255,255,248,0),
Color.FromArgb(255,255,249,0),
Color.FromArgb(255,255,249,0),
Color.FromArgb(255,255,250,0),
Color.FromArgb(255,255,251,0),
Color.FromArgb(255,255,252,0),
Color.FromArgb(255,255,253,0),
Color.FromArgb(255,255,253,0),
Color.FromArgb(255,255,254,0),
Color.FromArgb(255,255,255,0),
Color.FromArgb(255,255,255,0),
Color.FromArgb(255,254,254,1),
Color.FromArgb(255,253,254,1),
Color.FromArgb(255,252,254,1),
Color.FromArgb(255,251,253,2),
Color.FromArgb(255,251,253,2),
Color.FromArgb(255,250,252,3),
Color.FromArgb(255,249,252,3),
Color.FromArgb(255,248,252,3),
Color.FromArgb(255,247,251,4),
Color.FromArgb(255,247,251,4),
Color.FromArgb(255,246,250,5),
Color.FromArgb(255,245,250,5),
Color.FromArgb(255,244,250,5),
Color.FromArgb(255,243,249,6),
Color.FromArgb(255,243,249,6),
Color.FromArgb(255,242,248,7),
Color.FromArgb(255,241,248,7),
Color.FromArgb(255,240,248,7),
Color.FromArgb(255,239,247,8),
Color.FromArgb(255,239,247,8),
Color.FromArgb(255,238,247,8),
Color.FromArgb(255,237,246,9),
Color.FromArgb(255,237,246,9),
Color.FromArgb(255,236,245,10),
Color.FromArgb(255,235,245,10),
Color.FromArgb(255,234,245,10),
Color.FromArgb(255,233,244,11),
Color.FromArgb(255,233,244,11),
Color.FromArgb(255,232,243,12),
Color.FromArgb(255,231,243,12),
Color.FromArgb(255,230,243,12),
Color.FromArgb(255,230,242,13),
Color.FromArgb(255,229,242,13),
Color.FromArgb(255,228,242,13),
Color.FromArgb(255,227,241,14),
Color.FromArgb(255,227,241,14),
Color.FromArgb(255,226,240,15),
Color.FromArgb(255,225,240,15),
Color.FromArgb(255,224,240,15),
Color.FromArgb(255,223,239,16),
Color.FromArgb(255,223,239,16),
Color.FromArgb(255,222,238,17),
Color.FromArgb(255,221,238,17),
Color.FromArgb(255,220,238,17),
Color.FromArgb(255,219,237,18),
Color.FromArgb(255,219,237,18),
Color.FromArgb(255,218,236,19),
Color.FromArgb(255,217,236,19),
Color.FromArgb(255,216,236,19),
Color.FromArgb(255,215,235,20),
Color.FromArgb(255,215,235,20),
Color.FromArgb(255,214,234,21),
Color.FromArgb(255,213,234,21),
Color.FromArgb(255,213,234,21),
Color.FromArgb(255,212,233,22),
Color.FromArgb(255,211,233,22),
Color.FromArgb(255,210,233,22),
Color.FromArgb(255,209,232,23),
Color.FromArgb(255,209,232,23),
Color.FromArgb(255,208,231,24),
Color.FromArgb(255,207,231,24),
Color.FromArgb(255,206,231,24),
Color.FromArgb(255,205,230,25),
Color.FromArgb(255,205,230,25),
Color.FromArgb(255,204,229,26),
Color.FromArgb(255,203,229,26),
Color.FromArgb(255,202,229,26),
Color.FromArgb(255,201,228,27),
Color.FromArgb(255,201,228,27),
Color.FromArgb(255,200,227,28),
Color.FromArgb(255,199,227,28),
Color.FromArgb(255,198,227,28),
Color.FromArgb(255,197,226,29),
Color.FromArgb(255,197,226,29),
Color.FromArgb(255,196,226,29),
Color.FromArgb(255,195,225,30),
Color.FromArgb(255,195,225,30),
Color.FromArgb(255,194,224,31),
Color.FromArgb(255,193,224,31),
Color.FromArgb(255,192,224,31),
Color.FromArgb(255,191,223,32),
Color.FromArgb(255,191,223,32),
Color.FromArgb(255,190,222,33),
Color.FromArgb(255,189,222,33),
Color.FromArgb(255,188,222,33),
Color.FromArgb(255,187,221,34),
Color.FromArgb(255,187,221,34),
Color.FromArgb(255,186,220,35),
Color.FromArgb(255,185,220,35),
Color.FromArgb(255,184,220,35),
Color.FromArgb(255,183,219,36),
Color.FromArgb(255,183,219,36),
Color.FromArgb(255,182,219,36),
Color.FromArgb(255,181,218,37),
Color.FromArgb(255,181,218,37),
Color.FromArgb(255,180,217,38),
Color.FromArgb(255,179,217,38),
Color.FromArgb(255,178,217,38),
Color.FromArgb(255,177,216,39),
Color.FromArgb(255,177,216,39),
Color.FromArgb(255,176,215,40),
Color.FromArgb(255,175,215,40),
Color.FromArgb(255,174,215,40),
Color.FromArgb(255,173,214,41),
Color.FromArgb(255,173,214,41),
Color.FromArgb(255,172,213,42),
Color.FromArgb(255,171,213,42),
Color.FromArgb(255,171,213,42),
Color.FromArgb(255,170,212,43),
Color.FromArgb(255,169,212,43),
Color.FromArgb(255,168,212,43),
Color.FromArgb(255,167,211,44),
Color.FromArgb(255,167,211,44),
Color.FromArgb(255,166,210,45),
Color.FromArgb(255,165,210,45),
Color.FromArgb(255,164,210,45),
Color.FromArgb(255,163,209,46),
Color.FromArgb(255,163,209,46),
Color.FromArgb(255,162,208,47),
Color.FromArgb(255,161,208,47),
Color.FromArgb(255,160,208,47),
Color.FromArgb(255,159,207,48),
Color.FromArgb(255,159,207,48),
Color.FromArgb(255,158,206,49),
Color.FromArgb(255,157,206,49),
Color.FromArgb(255,156,206,49),
Color.FromArgb(255,155,205,50),
Color.FromArgb(255,155,205,50),
Color.FromArgb(255,154,205,50),
Color.FromArgb(255,153,204,51),
Color.FromArgb(255,152,203,51),
Color.FromArgb(255,151,202,50),
Color.FromArgb(255,149,202,50),
Color.FromArgb(255,148,201,49),
Color.FromArgb(255,146,200,49),
Color.FromArgb(255,145,199,48),
Color.FromArgb(255,144,198,48),
Color.FromArgb(255,143,197,48),
Color.FromArgb(255,141,196,47),
Color.FromArgb(255,140,195,47),
Color.FromArgb(255,139,194,46),
Color.FromArgb(255,137,194,46),
Color.FromArgb(255,136,193,45),
Color.FromArgb(255,134,192,45),
Color.FromArgb(255,133,191,44),
Color.FromArgb(255,132,190,44),
Color.FromArgb(255,131,189,44),
Color.FromArgb(255,129,188,43),
Color.FromArgb(255,128,187,43),
Color.FromArgb(255,127,186,42),
Color.FromArgb(255,125,186,42),
Color.FromArgb(255,124,184,41),
Color.FromArgb(255,122,184,41),
Color.FromArgb(255,121,183,40),
Color.FromArgb(255,120,182,40),
Color.FromArgb(255,119,181,40),
Color.FromArgb(255,118,180,39),
Color.FromArgb(255,116,179,39),
Color.FromArgb(255,115,178,38),
Color.FromArgb(255,113,178,38),
Color.FromArgb(255,112,177,37),
Color.FromArgb(255,111,176,37),
Color.FromArgb(255,109,175,36),
Color.FromArgb(255,108,174,36),
Color.FromArgb(255,107,173,36),
Color.FromArgb(255,106,172,35),
Color.FromArgb(255,104,171,35),
Color.FromArgb(255,103,170,34),
Color.FromArgb(255,101,170,34),
Color.FromArgb(255,100,169,33),
Color.FromArgb(255,98,168,33),
Color.FromArgb(255,97,167,32),
Color.FromArgb(255,96,166,32),
Color.FromArgb(255,95,165,32),
Color.FromArgb(255,93,164,31),
Color.FromArgb(255,92,163,31),
Color.FromArgb(255,91,162,30),
Color.FromArgb(255,89,162,30),
Color.FromArgb(255,88,160,29),
Color.FromArgb(255,86,160,29),
Color.FromArgb(255,85,159,28),
Color.FromArgb(255,84,158,28),
Color.FromArgb(255,83,157,28),
Color.FromArgb(255,81,156,27),
Color.FromArgb(255,80,155,27),
Color.FromArgb(255,79,154,26),
Color.FromArgb(255,77,154,26),
Color.FromArgb(255,76,152,25),
Color.FromArgb(255,74,152,25),
Color.FromArgb(255,73,151,24),
Color.FromArgb(255,72,150,24),
Color.FromArgb(255,70,149,23),
Color.FromArgb(255,69,148,23),
Color.FromArgb(255,68,147,23),
Color.FromArgb(255,67,146,22),
Color.FromArgb(255,65,145,22),
Color.FromArgb(255,64,144,21),
Color.FromArgb(255,62,144,21),
Color.FromArgb(255,61,143,20),
Color.FromArgb(255,59,142,20),
Color.FromArgb(255,58,141,19),
Color.FromArgb(255,57,140,19),
Color.FromArgb(255,56,139,19),
Color.FromArgb(255,54,138,18),
Color.FromArgb(255,53,137,18),
Color.FromArgb(255,52,136,17),
Color.FromArgb(255,50,136,17),
Color.FromArgb(255,49,135,16),
Color.FromArgb(255,47,134,16),
Color.FromArgb(255,46,133,15),
Color.FromArgb(255,45,132,15),
Color.FromArgb(255,44,131,15),
Color.FromArgb(255,42,130,14),
Color.FromArgb(255,41,129,14),
Color.FromArgb(255,40,128,13),
Color.FromArgb(255,38,128,13),
Color.FromArgb(255,37,126,12),
Color.FromArgb(255,35,126,12),
Color.FromArgb(255,34,125,11),
Color.FromArgb(255,33,124,11),
Color.FromArgb(255,32,123,11),
Color.FromArgb(255,31,122,10),
Color.FromArgb(255,29,122,10),
Color.FromArgb(255,28,120,9),
Color.FromArgb(255,26,120,9),
Color.FromArgb(255,25,119,8),
Color.FromArgb(255,24,118,8),
Color.FromArgb(255,22,117,7),
Color.FromArgb(255,21,116,7),
Color.FromArgb(255,20,115,7),
Color.FromArgb(255,19,114,6),
Color.FromArgb(255,17,113,6),
Color.FromArgb(255,16,112,5),
Color.FromArgb(255,14,112,5),
Color.FromArgb(255,13,111,4),
Color.FromArgb(255,11,110,4),
Color.FromArgb(255,10,109,3),
Color.FromArgb(255,9,108,3),
Color.FromArgb(255,8,107,3),
Color.FromArgb(255,6,106,2),
Color.FromArgb(255,5,105,2),
Color.FromArgb(255,4,104,1),
Color.FromArgb(255,2,104,1),
Color.FromArgb(255,1,102,0),
Color.FromArgb(255,0,102,0),
Color.FromArgb(255,0,102,0),
Color.FromArgb(255,0,102,0)};
#endregion
public PasswordMeter()
{
InitializeComponent();
password = "";
UpdateControl();
}
public void SetPassword(String pwd)
{
password = pwd;
UpdateControl();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (brush != null)
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
private void UpdateControl()
{
int score = PasswordUtils.ComputePasswordScore(password);
lbText.Text = PasswordUtils.GetPasswordStrengthText(score);
int x1 = score * 4;
int x2 = x1 + 99;
if (x2 >= 500) x2 = 499;
Color clr1 = Colors[x1];
Color clr2 = Colors[x2];
if (brush != null)
{
brush.Dispose();
brush = null;
}
brush = new LinearGradientBrush(
new Point(0, 0),
new Point(this.Width, this.Height),
clr1,
clr2);
Refresh();
}
private void PasswordMeter_Load(object sender, EventArgs e)
{
// Needed to ensure control is drawn correctly at start up.
SetPassword("");
}
}
}
| sassy224/PasswordTextBox | CustomControls/PasswordMeter.cs | C# | mit | 33,534 |
try:
print 'Importing ....'
from base import * # noqa
from local import * # noqa
except ImportError:
import traceback
print traceback.format_exc()
print 'Unable to find moderation/settings/local.py'
try:
from post_env_commons import * # noqa
except ImportError:
pass
| CareerVillage/slack-moderation | src/moderation/settings/__init__.py | Python | mit | 305 |
using Autofac;
using AutoMapper;
using Miningcore.Blockchain.Ergo.Configuration;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Payments;
using Miningcore.Persistence;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using Miningcore.Time;
using Miningcore.Util;
using Block = Miningcore.Persistence.Model.Block;
using Contract = Miningcore.Contracts.Contract;
using static Miningcore.Util.ActionUtils;
namespace Miningcore.Blockchain.Ergo;
[CoinFamily(CoinFamily.Ergo)]
public class ErgoPayoutHandler : PayoutHandlerBase,
IPayoutHandler
{
public ErgoPayoutHandler(
IComponentContext ctx,
IConnectionFactory cf,
IMapper mapper,
IShareRepository shareRepo,
IBlockRepository blockRepo,
IBalanceRepository balanceRepo,
IPaymentRepository paymentRepo,
IMasterClock clock,
IMessageBus messageBus) :
base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, messageBus)
{
Contract.RequiresNonNull(ctx, nameof(ctx));
Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));
this.ctx = ctx;
}
protected readonly IComponentContext ctx;
protected ErgoClient ergoClient;
private string network;
private ErgoPaymentProcessingConfigExtra extraPoolPaymentProcessingConfig;
protected override string LogCategory => "Ergo Payout Handler";
private class PaymentException : Exception
{
public PaymentException(string msg) : base(msg)
{
}
}
private void ReportAndRethrowApiError(string action, Exception ex, bool rethrow = true)
{
var error = ex.Message;
if(ex is ApiException<ApiError> apiException)
error = apiException.Result.Detail ?? apiException.Result.Reason;
logger.Warn(() => $"{action}: {error}");
if(rethrow)
throw ex;
}
private async Task UnlockWallet(CancellationToken ct)
{
logger.Info(() => $"[{LogCategory}] Unlocking wallet");
var walletPassword = extraPoolPaymentProcessingConfig.WalletPassword ?? string.Empty;
await Guard(() => ergoClient.WalletUnlockAsync(new Body4 {Pass = walletPassword}, ct), ex =>
{
if (ex is ApiException<ApiError> apiException)
{
var error = apiException.Result.Detail;
if (error != null && !error.ToLower().Contains("already unlocked"))
throw new PaymentException($"Failed to unlock wallet: {error}");
}
else
throw ex;
});
logger.Info(() => $"[{LogCategory}] Wallet unlocked");
}
private async Task LockWallet(CancellationToken ct)
{
logger.Info(() => $"[{LogCategory}] Locking wallet");
await Guard(() => ergoClient.WalletLockAsync(ct),
ex => ReportAndRethrowApiError("Failed to lock wallet", ex));
logger.Info(() => $"[{LogCategory}] Wallet locked");
}
#region IPayoutHandler
public virtual async Task ConfigureAsync(ClusterConfig clusterConfig, PoolConfig poolConfig, CancellationToken ct)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
logger = LogUtil.GetPoolScopedLogger(typeof(ErgoPayoutHandler), poolConfig);
this.poolConfig = poolConfig;
this.clusterConfig = clusterConfig;
extraPoolPaymentProcessingConfig = poolConfig.PaymentProcessing.Extra.SafeExtensionDataAs<ErgoPaymentProcessingConfigExtra>();
ergoClient = ErgoClientFactory.CreateClient(poolConfig, clusterConfig, null);
// detect chain
var info = await ergoClient.GetNodeInfoAsync(ct);
network = ErgoConstants.RegexChain.Match(info.Name).Groups[1].Value.ToLower();
}
public virtual async Task<Block[]> ClassifyBlocksAsync(IMiningPool pool, Block[] blocks, CancellationToken ct)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
Contract.RequiresNonNull(blocks, nameof(blocks));
if(blocks.Length == 0)
return blocks;
var coin = poolConfig.Template.As<ErgoCoinTemplate>();
var pageSize = 100;
var pageCount = (int) Math.Ceiling(blocks.Length / (double) pageSize);
var result = new List<Block>();
var minConfirmations = extraPoolPaymentProcessingConfig?.MinimumConfirmations ?? (network == "mainnet" ? 720 : 72);
var minerRewardsPubKey = await ergoClient.MiningReadMinerRewardPubkeyAsync(ct);
var minerRewardsAddress = await ergoClient.MiningReadMinerRewardAddressAsync(ct);
for(var i = 0; i < pageCount; i++)
{
// get a page full of blocks
var page = blocks
.Skip(i * pageSize)
.Take(pageSize)
.ToArray();
// fetch header ids for blocks in page
var headerBatch = page.Select(block => ergoClient.GetFullBlockAtAsync((int) block.BlockHeight, ct)).ToArray();
await Guard(()=> Task.WhenAll(headerBatch),
ex=> logger.Debug(ex));
for(var j = 0; j < page.Length; j++)
{
var block = page[j];
var headerTask = headerBatch[j];
if(!headerTask.IsCompletedSuccessfully)
{
if(headerTask.IsFaulted)
logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Exception?.InnerException?.Message ?? headerTask.Exception?.Message}");
else
logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Status.ToString().ToLower()}");
continue;
}
var headerIds = headerTask.Result;
// fetch blocks
var blockBatch = headerIds.Select(x=> ergoClient.GetFullBlockByIdAsync(x, ct)).ToArray();
await Guard(()=> Task.WhenAll(blockBatch),
ex=> logger.Debug(ex));
var blockHandled = false;
var pkMismatchCount = 0;
var nonceMismatchCount = 0;
var coinbaseNonWalletTxCount = 0;
foreach (var blockTask in blockBatch)
{
if(blockHandled)
break;
if(!blockTask.IsCompletedSuccessfully)
continue;
var fullBlock = blockTask.Result;
// only consider blocks with pow-solution pk matching ours
if(fullBlock.Header.PowSolutions.Pk != minerRewardsPubKey.RewardPubKey)
{
pkMismatchCount++;
continue;
}
// only consider blocks with pow-solution nonce matching what we have on file
if(fullBlock.Header.PowSolutions.N != block.TransactionConfirmationData)
{
nonceMismatchCount++;
continue;
}
var coinbaseWalletTxFound = false;
// reset block reward
block.Reward = 0;
foreach(var blockTx in fullBlock.BlockTransactions.Transactions)
{
var walletTx = await Guard(()=> ergoClient.WalletGetTransactionAsync(blockTx.Id, ct));
var coinbaseOutput = walletTx?.Outputs?.FirstOrDefault(x => x.Address == minerRewardsAddress.RewardAddress);
if(coinbaseOutput != null)
{
coinbaseWalletTxFound = true;
block.ConfirmationProgress = Math.Min(1.0d, (double) walletTx.NumConfirmations / minConfirmations);
block.Reward += coinbaseOutput.Value / ErgoConstants.SmallestUnit;
block.Hash = fullBlock.Header.Id;
if(walletTx.NumConfirmations >= minConfirmations)
{
// matured and spendable coinbase transaction
block.Status = BlockStatus.Confirmed;
block.ConfirmationProgress = 1;
}
}
}
blockHandled = coinbaseWalletTxFound;
if(blockHandled)
{
result.Add(block);
if(block.Status == BlockStatus.Confirmed)
{
logger.Info(() => $"[{LogCategory}] Unlocked block {block.BlockHeight} worth {FormatAmount(block.Reward)}");
messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
}
else
messageBus.NotifyBlockConfirmationProgress(poolConfig.Id, block, coin);
}
else
coinbaseNonWalletTxCount++;
}
if(!blockHandled)
{
string orphanReason = null;
if(pkMismatchCount == blockBatch.Length)
orphanReason = "pk mismatch";
else if(nonceMismatchCount == blockBatch.Length)
orphanReason = "nonce mismatch";
else if(coinbaseNonWalletTxCount == blockBatch.Length)
orphanReason = "no related coinbase tx found in wallet";
if(!string.IsNullOrEmpty(orphanReason))
{
block.Status = BlockStatus.Orphaned;
block.Reward = 0;
result.Add(block);
logger.Info(() => $"[{LogCategory}] Block {block.BlockHeight} classified as orphaned due to {orphanReason}");
messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
}
}
}
}
return result.ToArray();
}
public virtual Task CalculateBlockEffortAsync(IMiningPool pool, Block block, double accumulatedBlockShareDiff, CancellationToken ct)
{
block.Effort = accumulatedBlockShareDiff * ErgoConstants.ShareMultiplier / block.NetworkDifficulty;
return Task.FromResult(true);
}
public override double AdjustShareDifficulty(double difficulty)
{
return difficulty * ErgoConstants.ShareMultiplier;
}
public virtual async Task PayoutAsync(IMiningPool pool, Balance[] balances, CancellationToken ct)
{
Contract.RequiresNonNull(balances, nameof(balances));
// build args
var amounts = balances
.Where(x => x.Amount > 0)
.ToDictionary(x => x.Address, x => Math.Round(x.Amount, 4));
if(amounts.Count == 0)
return;
var balancesTotal = amounts.Sum(x => x.Value);
try
{
logger.Info(() => $"[{LogCategory}] Paying {FormatAmount(balances.Sum(x => x.Amount))} to {balances.Length} addresses");
// get wallet status
var status = await ergoClient.GetWalletStatusAsync(ct);
if(!status.IsInitialized)
throw new PaymentException($"Wallet is not initialized");
if(!status.IsUnlocked)
await UnlockWallet(ct);
// get balance
var walletBalances = await ergoClient.WalletBalancesAsync(ct);
var walletTotal = walletBalances.Balance / ErgoConstants.SmallestUnit;
logger.Info(() => $"[{LogCategory}] Current wallet balance is {FormatAmount(walletTotal)}");
// bail if balance does not satisfy payments
if(walletTotal < balancesTotal)
{
logger.Warn(() => $"[{LogCategory}] Wallet balance currently short of {FormatAmount(balancesTotal - walletTotal)}. Will try again.");
return;
}
// validate addresses
logger.Info("Validating addresses ...");
foreach(var pair in amounts)
{
var validity = await Guard(() => ergoClient.CheckAddressValidityAsync(pair.Key, ct));
if(validity == null || !validity.IsValid)
logger.Warn(()=> $"Address {pair.Key} is not valid!");
}
// Create request batch
var requests = amounts.Select(x => new PaymentRequest
{
Address = x.Key,
Value = (long) (x.Value * ErgoConstants.SmallestUnit),
}).ToArray();
var txId = await Guard(()=> ergoClient.WalletPaymentTransactionGenerateAndSendAsync(requests, ct), ex =>
{
if(ex is ApiException<ApiError> apiException)
{
var error = apiException.Result.Detail ?? apiException.Result.Reason;
if(error.Contains("reason:"))
error = error.Substring(error.IndexOf("reason:"));
throw new PaymentException($"Payment transaction failed: {error}");
}
else
throw ex;
});
if(string.IsNullOrEmpty(txId))
throw new PaymentException("Payment transaction failed to return a transaction id");
// payment successful
logger.Info(() => $"[{LogCategory}] Payment transaction id: {txId}");
await PersistPaymentsAsync(balances, txId);
NotifyPayoutSuccess(poolConfig.Id, balances, new[] {txId}, null);
}
catch(PaymentException ex)
{
logger.Error(() => $"[{LogCategory}] {ex.Message}");
NotifyPayoutFailure(poolConfig.Id, balances, ex.Message, null);
}
finally
{
await LockWallet(ct);
}
}
#endregion // IPayoutHandler
}
| coinfoundry/miningcore | src/Miningcore/Blockchain/Ergo/ErgoPayoutHandler.cs | C# | mit | 14,286 |
<?php
Breadcrumbs::for('admin.email-templates.index', function ($trail) {
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.index'));
});
Breadcrumbs::for('admin.email-templates.create', function ($trail) {
$trail->parent('admin.email-templates.index');
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.create'));
});
Breadcrumbs::for('admin.email-templates.edit', function ($trail, $id) {
$trail->parent('admin.email-templates.index');
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.edit', $id));
});
| viralsolani/laravel-adminpanel | routes/breadcrumbs/backend/email-templates/email-template.php | PHP | mit | 673 |
package gosquare
type Meta struct {
Code int `json:"code"`
ErrorType string `json:"errorType"`
ErrorDetails string `json:"errorDetails"`
}
type Notifications []Notification
type Notification struct {
Type string `json:"type"`
Item interface{} `json:"item"`
}
| aykutaras/gosquare | base.go | GO | mit | 286 |
package Mod.Items;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import Mod.Lib.Refrence;
import Mod.Main.Main;
import Mod.Misc.MiscDamage;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ModItemSilverSword extends ItemSword {
public ModItemSilverSword(int i, EnumToolMaterial enumToolMaterial){
super(i, enumToolMaterial);
setCreativeTab(Main.CreativeTab);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister)
{
this.itemIcon = par1IconRegister.registerIcon(Refrence.Mod_Id + ":" + "SilverSword");
}
public boolean hitEntity(ItemStack itemstack, EntityLivingBase EntityHit, EntityLivingBase EntityAttacker)
{
if(EntityHit instanceof EntityDragon || EntityHit instanceof EntityWither || EntityHit instanceof EntityPlayer){
}else{
EntityHit.attackEntityFrom(new MiscDamage("Silver Sword", StatCollector.translateToLocal("string.death.silversword").replace("%Killed", EntityHit.getTranslatedEntityName().replace("%Killer", EntityAttacker.getTranslatedEntityName()))), 80F);
EntityHit.attackEntityAsMob(EntityHit);
if (itemstack.stackTagCompound == null){
itemstack.setTagCompound(new NBTTagCompound());
}
if(itemstack.stackTagCompound.getInteger("Kills") == 0){
itemstack.stackTagCompound.setInteger("Kills", 1);
}else{
itemstack.stackTagCompound.setInteger("Kills", itemstack.stackTagCompound.getInteger("Kills") + 1);
}
itemstack.stackTagCompound.setString("LastMob", EntityHit.getTranslatedEntityName());
itemstack.attemptDamageItem(1, EntityHit.worldObj.rand);
}
return false;
}
public void onCreated(ItemStack item, World world, EntityPlayer player) {
if (item.stackTagCompound == null){
item.setTagCompound(new NBTTagCompound());
}
item.stackTagCompound.setString("MadeBy", player.username);
}
@Override
public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean par4)
{
list.add(StatCollector.translateToLocal("items.desc.silversword.1"));
if(itemstack.stackTagCompound != null){
list.add(StatCollector.translateToLocal("items.desc.silversword.2") + ": " + itemstack.stackTagCompound.getInteger("Kills"));
if(itemstack.stackTagCompound.getString("LastMob") == null)
list.add(StatCollector.translateToLocal("items.desc.silversword.4"));
else
list.add(StatCollector.translateToLocal("items.desc.silversword.3") + ": " + itemstack.stackTagCompound.getString("LastMob"));
if(itemstack.stackTagCompound.getString("MadeBy") == null)
list.add(StatCollector.translateToLocal("items.desc.silversword.6"));
else
list.add(StatCollector.translateToLocal("items.desc.silversword.5") + ": " + itemstack.stackTagCompound.getString("MadeBy"));
}else{
list.add(StatCollector.translateToLocal("items.desc.silversword.2") + ": 0");
list.add(StatCollector.translateToLocal("items.desc.silversword.4"));
list.add(StatCollector.translateToLocal("items.desc.silversword.6"));
}
}
public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack)
{
return false;
}
} | tm1990/MiscItemsAndBlocks | common/Mod/Items/ModItemSilverSword.java | Java | mit | 4,575 |
<?php
namespace Dflydev\EncryptedFigCookies\Encryption\Adapter;
use Dflydev\EncryptedFigCookies\Encryption\Encryption;
use Zend\Filter\Decrypt;
use Zend\Filter\Encrypt;
class ZendCryptEncryption implements Encryption
{
/**
* @var Decrypt
*/
private $decrypt;
/**
* @var Encrypt
*/
private $encrypt;
public function __construct(Decrypt $decrypt, Encrypt $encrypt)
{
$this->decrypt = $decrypt;
$this->encrypt = $encrypt;
}
public function decrypt($value)
{
return $this->decrypt->filter($value);
}
public function encrypt($value)
{
return $this->encrypt->filter($value);
}
}
| dflydev/dflydev-encrypted-fig-cookies | src/Dflydev/EncryptedFigCookies/Encryption/Adapter/ZendCryptEncryption.php | PHP | mit | 684 |
<?php
namespace Lyra;
use Lyra\Interfaces\Widget;
class WidgetRegistry implements \Lyra\Interfaces\WidgetRegistry
{
/**
* {@inheritdoc}
*/
protected $widgets;
public function __construct()
{
$this->widgets = [];
}
/**
* {@inheritdoc}
*/
public function addWidget(\Lyra\Interfaces\Widget $widget)
{
return $this->widgets[$widget->getName()] = $widget;
}
/**
* {@inheritdoc}
*/
public function getWidget($alias)
{
if (!isset($this->widgets[$alias])) {
throw new ServiceNotFoundException(sprintf('Widget %s is actually not load into the WidgetRegistry'),
$alias);
}
return $this->widgets[$alias];
}
}
| uaktags/lyraEngine | src/WidgetRegistry.php | PHP | mit | 754 |
package com.tactfactory.harmony.platform.android.updater;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import com.tactfactory.harmony.generator.BaseGenerator;
import com.tactfactory.harmony.platform.IAdapter;
import com.tactfactory.harmony.updater.IAddEntityField;
import com.tactfactory.harmony.utils.ConsoleUtils;
import com.tactfactory.harmony.utils.TactFileUtils;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class AddEntityFieldAndroid implements IAddEntityField{
private final String templatePath;
private final String sourceFile;
public AddEntityFieldAndroid(
String templatePath,
String sourceFile) {
this.templatePath = templatePath;
this.sourceFile = sourceFile;
}
@Override
public void execute(BaseGenerator<? extends IAdapter> generator) {
File file = new File(this.sourceFile);
if (file != null && file.isFile()) {
String strFile = TactFileUtils.fileToString(file);
try {
final Template tpl = generator.getCfg().getTemplate(this.templatePath);
StringWriter out = new StringWriter();
tpl.process(generator.getDatamodel(), out);
strFile = strFile.substring(0,
strFile.lastIndexOf('}'));
strFile = strFile.concat(out.toString() + "\n}");
TactFileUtils.writeStringToFile(file, strFile);
} catch (IOException | TemplateException e) {
ConsoleUtils.displayError(e);
}
}
}
}
| TACTfactory/harmony-core | src/com/tactfactory/harmony/platform/android/updater/AddEntityFieldAndroid.java | Java | mit | 1,647 |
<?php
namespace Sideclick\EntityHelperBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SideclickEntityHelperBundle extends Bundle
{
}
| Sideclick/EntityHelperBundle | src/SideclickEntityHelperBundle.php | PHP | mit | 150 |
#ifndef COMPONENT_HPP
#define COMPONENT_HPP
#include "messages/spa_subscription_reply.hpp"
#include "messages/spa_subscription_request.hpp"
#include "messages/spa_data.hpp"
#include "spa_communicator.hpp"
#include "spa_message.hpp"
#include <iostream>
#include <memory>
#include <vector>
struct Subscriber
{
Subscriber(LogicalAddress la, uint16_t d)
: subscriberAddress(la), deliveryRateDivisor(d) {}
LogicalAddress subscriberAddress;
uint16_t deliveryRateDivisor;
};
class Component
{
public:
typedef std::shared_ptr<SpaCommunicator> Com;
Component(Com communicator = nullptr, LogicalAddress address = LogicalAddress(0, 0))
: communicator(communicator),
address(address),
dialogId(0),
publishIter(1)
{
subscribers.reserve(8); // Default to 8 subscribers
}
virtual ~Component() {}
//virtual void appShutdown() = 0;
void publish();
virtual void sendSpaData(LogicalAddress) = 0;
virtual void handleSpaData(std::shared_ptr<SpaMessage>) = 0;
virtual void appInit() = 0;
void sendMsg(std::shared_ptr<SpaMessage> message)
{
if (message == nullptr || communicator == nullptr)
{
return;
}
communicator->send(message);
}
void receiveMessage(std::shared_ptr<SpaMessage>);
void handleSubscriptionReply(std::shared_ptr<SpaMessage>);
void registerSubscriptionRequest(std::shared_ptr<SpaMessage>);
void subscribe(
LogicalAddress producer,
uint8_t priority,
uint32_t leasePeriod,
uint16_t deliveryRateDivisor);
Com communicator;
protected:
LogicalAddress address;
uint8_t publishIter;
uint16_t dialogId;
std::vector<Subscriber> subscribers; // Should we make this a vector of pointers?
};
#endif
| SmallSatGasTeam/OpenSPA | lib/component.hpp | C++ | mit | 1,736 |
<!-- Replaced strings -->
<form class="form-signin form-horizontal" id="replaced_strings_form" role="form">
<div class="col-sm-10 col-sm-offset-4">
<h2 class="form-signin-heading"><?= $this->lang->line("replaced_string_settings"); ?></h2>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<input type="text" id="alert_word_count" name="alert_word_count" class="form-control" placeholder="<?= $this->lang->line("username"); ?>" required autofocus>
</div>
</div>
</div>
</form> | boh1996/TwitterAnalytics | v1/application/views/admin_strings_view.php | PHP | mit | 511 |
/*
* Message.cc
*
* Created on: Apr 13, 2014
* Author: wilfeli
*/
#include "Message.h"
Message::Message(std::string s_):type(s_){};
MessagePSSendPayment::MessagePSSendPayment(IPSAgent* a_, double q_, std::string type_):
Message(type_), getter(a_), q(q_){};
MessagePSSendPayment::MessagePSSendPayment(double q_, std::string type_):
Message(type_), q(q_){};
//MessageSellC::MessageSellC(Message* inf_, Contract<Agent, Agent>* c_): inf(inf_), contract(c_){
// type = "SellC";
//};
MessageMarketLSellC::MessageMarketLSellC
(MarketL* _sender, IBuyerL* _buyer, double _p, double _q):
sender(_sender), buyer(_buyer), p(_p), q(_q) {
type = "MarketLSellC";
};
MessageMarketCSellGoodC::MessageMarketCSellGoodC
(MarketC* _sender, IBuyerC* _buyer, double _p, double _q):
sender(_sender), buyer(_buyer), p(_p), q(_q) {
type = "MarketCSellGoodC";
};
MessageMarketLCheckAsk::MessageMarketLCheckAsk
(MarketL* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketLCheckAsk";
};
MessageMarketLCheckBid::MessageMarketLCheckBid
(MarketL* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketLCheckBid";
};
MessageMarketCCheckAsk::MessageMarketCCheckAsk
(MarketC* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketCCheckAsk";
};
MessageMarketCCheckBid::MessageMarketCCheckBid
(MarketC* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketCCheckBid";
};
MessageGoodC::MessageGoodC(double q_, double p_): q(q_), p(p_){
type = "asGC";
};
MessageBankruptcy::MessageBankruptcy(F* agent_): agent(agent_){
type = "Bankruptcy";
};
MessageBankruptcyH::MessageBankruptcyH(H* agent_): agent(agent_){
type = "Bankruptcy";
};
MessageMakeDec::MessageMakeDec(){
type = "MakeDec";
};
MessageStatus::MessageStatus(double status_): status(status_){
type = "Status";
};
| wilfeli/DMGameBasic | src/Message.cpp | C++ | mit | 1,845 |
import React, { PropTypes, Component } from 'react';
import cx from 'classnames';
import Modal from '../Modal';
import FontIcon from '../FontIcon';
import s from './AssignTo.scss';
class AssignTo extends Component {
state = {
nodeIdx: null,
treeData: [],
};
componentDidMount = () => this.setState({
nodeIdx: this.props.document.tags,
treeData: this.props.treeData.map(node =>
this.props.document.tags.indexOf(node.id) !== -1
? Object.assign({}, node, { isTarget: true })
: Object.assign({}, node, { isTarget: false })
),
});
/**
* Handles dismiss
*/
handleOnDismiss = () => this.props.onCancel();
/**
* Handles confirmation
*/
handleOnConfirm = () => {
this.props.onConfirm(this.props.document._id, this.state.nodeIdx);
this.handleOnDismiss();
};
/**
* Handles click on tree view's element
* @param {String} id - Current Tree Node
* @param {Event} event - Event
* @param isDisabled {Boolean}
*/
handleOnClickOnTreeItem = (id, event, isDisabled) => {
event.stopPropagation();
if (!isDisabled) {
const { nodeIdx } = this.state;
const newNodeIdx = nodeIdx.indexOf(id) !== -1
? nodeIdx.filter(node => node !== id) // remove if already added
: [...new Set([...this.state.nodeIdx, id])];
this.setState({
nodeIdx: newNodeIdx,
isRoot: false,
treeData: this.state.treeData.map(node =>
newNodeIdx.indexOf(node.id) !== -1
? Object.assign({}, node, { isTarget: true })
: Object.assign({}, node, { isTarget: false })
),
});
}
};
/**
* Handles key down on tree view's element
* @param {String} id - Current Tree Node ID
* @param {Event} event - Event
* @param isDisabled {Boolean}
*/
handleOnKeyDownOnTreeItem = (id, event, isDisabled) => {
if (!isDisabled) {
if (event.keyCode === 13 || event.keyCode === 32) {
this.handleOnClickOnTreeItem(id, event, isDisabled); // enter or space
}
}
};
/**
* Render tree item
* @param {Object} [node] Tree Node
* @param {number} [key]
* @return {XML} Tree Item.
*/
renderChild = (node) => {
const { treeData } = this.state;
const { canAssignSystemTags } = this.props;
const isDisabled = !canAssignSystemTags && node.isSystem;
const children = node
? treeData.map(child => child.parentId === node.id ? this.renderChild(child) : null)
: null;
return node.id === '0' ? null : (
<li
role="treeitem" key={node.id} tabIndex="0"
onClick={(event) => this.handleOnClickOnTreeItem(node.id, event, isDisabled)}
onKeyDown={(event) => this.handleOnKeyDownOnTreeItem(node.id, event)}
className={cx(s.child, {
[s.child_target]: node.isTarget,
[s.child_disabled]: isDisabled,
})}
>
<div className={s.item}>
<FontIcon
name={cx({
['folder']: node.isTarget,
['folder-o']: !node.isTarget,
})}
/>
<span>{node.name}</span>
</div>
<ul className={s.node} role="group">
{ children }
</ul>
</li>
);
};
render() {
const { strCancelLabel, strCaption, strSaveLabel } = this.props;
const { nodeIdx, treeData } = this.state;
return (
<Modal
caption={strCaption}
confirmText={strSaveLabel}
customBodyClassName={s.muted}
dismissText={strCancelLabel}
isConfirmDisabled={nodeIdx === null}
onConfirm={this.handleOnConfirm}
onDismiss={this.handleOnDismiss}
>
<div className={s.tree}>
<ul className={s.node} role="tree">
{ treeData.map(node =>
node.isRoot
? this.renderChild(node)
: null
)}
</ul>
</div>
</Modal>
);
}
}
AssignTo.propTypes = {
canAssignSystemTags: PropTypes.bool,
document: PropTypes.object,
message: PropTypes.string,
onCancel: PropTypes.func,
onConfirm: PropTypes.func,
onMount: PropTypes.func,
strCancelLabel: PropTypes.string,
strCaption: PropTypes.string,
strSaveLabel: PropTypes.string,
tagId: PropTypes.string,
tagName: PropTypes.string,
treeData: PropTypes.array,
};
AssignTo.defaultProps = {
canAssignSystemTags: false,
message: '',
treeData: [],
};
export default AssignTo;
| peinanshow/react-redux-samples | src/components/common/AssignTo/AssignTo.js | JavaScript | mit | 4,465 |
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AppConfig, AppRequest } from '../shared/index';
import { UserModel } from '../+users/user.interface';
import { TranslationComponent } from '../shared/translation/translation.component';
import { CacheComponent } from '../shared/cache/cache.component';
import { AlertComponent } from 'ng2-bootstrap/ng2-bootstrap';
@Component({
moduleId: module.id,
selector: 'sd-profile',
templateUrl: 'profile.component.html',
directives: [AlertComponent],
providers: [AppConfig, AppRequest]
})
export class ProfileComponent {
private _apiUrl = "user";
private _errorMessage: any;
hostUpload: string;
tr: any;
alerts: any = {};
model: UserModel;
userBack: any;
constructor(
private _tr: TranslationComponent,
private _cache: CacheComponent,
private _appRequest: AppRequest
) {
this.tr = _tr.getTranslation(_cache.getItem('lang'));
_cache.dataAdded$.subscribe((data: any) => {
if (data.hasOwnProperty('user')) this.model = data['user'];
this.model.chpassword = false;
this.model.password = "";
this.model.newpassword = "";
this.model.newrepassword = "";
this.userBack = this.model;
if (data.hasOwnProperty('lang')) {
this.tr = _tr.getTranslation(data['lang']);
}
});
}
isValid() {
let valid = true;
if (!this.model.email || !this.model.role) {
valid = false;
}
if (this.model.chpassword && (
!this.model.password || this.model.password.length < 5 ||
!this.model.newpassword || this.model.newpassword.length < 5 ||
!this.model.newrepassword || this.model.newrepassword.length < 5
)) {
valid = false;
}
return valid;
}
/**
* Send update request to API
*/
changeProfile() {
let sendData = [this.model];
this._appRequest.putAction(this._apiUrl, sendData)
.subscribe((res: any) => {
if (res.hasOwnProperty("warning")) {
this.alerts.warning = this.tr[res.warning];
}
if (res.hasOwnProperty("info")) {
if (res.info === 1) {
this.alerts.info = this.tr.profileChanged;
}
if (res.info === 0) {
this.alerts.warning = this.tr.profileNotChanged;
this.model = this.userBack;
}
}
},
(error: any) => this._errorMessage = error
);
}
/**
* Close profile info alert
*/
closeAlert(alert: string) {
this.alerts[alert] = null;
}
}
| martinsvb/Angular2_bootstrap_seed | src/client/app/+profile/profile.component.ts | TypeScript | mit | 2,850 |
/*
The MIT License (MIT)
Copyright (c) 2014 Harun Hasdal
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 AUTHORS OR
COPYRIGHT HOLDERS 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.
*/
package com.github.harunhasdal.livecycle.sftp;
public class SFTPParameterException extends RuntimeException {
public SFTPParameterException() {
super();
}
public SFTPParameterException(String s) {
super(s);
}
public SFTPParameterException(String s, Throwable throwable) {
super(s, throwable);
}
public SFTPParameterException(Throwable throwable) {
super(throwable);
}
}
| harunhasdal/sftp-connector | src/main/java/com/github/harunhasdal/livecycle/sftp/SFTPParameterException.java | Java | mit | 1,476 |
/*
Copyright (c) 2007 Danny Chapman
http://www.rowlhouse.co.uk
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/**
* @author Muzer(muzerly@gmail.com)
* @link http://code.google.com/p/jiglibflash
*/
(function(jigLib){
var Vector3D=jigLib.Vector3D;
var JConfig=jigLib.JConfig;
var Vector3D=jigLib.Vector3D;
var Matrix3D=jigLib.Matrix3D;
var JMatrix3D=jigLib.JMatrix3D;
var JNumber3D=jigLib.JNumber3D;
var MaterialProperties=jigLib.MaterialProperties;
var PhysicsState=jigLib.PhysicsState;
var PhysicsSystem=jigLib.PhysicsSystem;
var JAABox=jigLib.JAABox;
var RigidBody=function(skin){
this._useDegrees = (JConfig.rotationType == "DEGREES") ? true : false;
this._id = RigidBody.idCounter++;
this._skin = skin;
this._material = new MaterialProperties();
this._bodyInertia = new Matrix3D();
this._bodyInvInertia = JMatrix3D.getInverseMatrix(this._bodyInertia);
this._currState = new PhysicsState();
this._oldState = new PhysicsState();
this._storeState = new PhysicsState();
this._invOrientation = JMatrix3D.getInverseMatrix(this._currState.get_orientation());
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
this._force = new Vector3D();
this._torque = new Vector3D();
this._linVelDamping = new Vector3D(0.995, 0.995, 0.995);
this._rotVelDamping = new Vector3D(0.5, 0.5, 0.5);
this._maxLinVelocities = 500;
this._maxRotVelocities = 50;
this._velChanged = false;
this._inactiveTime = 0;
this.isActive = this._activity = true;
this._movable = true;
this._origMovable = true;
this.collisions = [];
this._constraints = [];
this._nonCollidables = [];
this._storedPositionForActivation = new Vector3D();
this._bodiesToBeActivatedOnMovement = [];
this._lastPositionForDeactivation = this._currState.position.clone();
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this._type = "Object3D";
this._boundingSphere = 0;
this._boundingBox = new JAABox(new Vector3D(), new Vector3D());
this._boundingBox.clear();
}
RigidBody.idCounter = 0;
RigidBody.prototype._id=null;
RigidBody.prototype._skin=null;
RigidBody.prototype._type=null;
RigidBody.prototype._boundingSphere=null;
RigidBody.prototype._boundingBox=null;
RigidBody.prototype._currState=null;
RigidBody.prototype._oldState=null;
RigidBody.prototype._storeState=null;
RigidBody.prototype._invOrientation=null;
RigidBody.prototype._currLinVelocityAux=null;
RigidBody.prototype._currRotVelocityAux=null;
RigidBody.prototype._mass=null;
RigidBody.prototype._invMass=null;
RigidBody.prototype._bodyInertia=null;
RigidBody.prototype._bodyInvInertia=null;
RigidBody.prototype._worldInertia=null;
RigidBody.prototype._worldInvInertia=null;
RigidBody.prototype._force=null;
RigidBody.prototype._torque=null;
RigidBody.prototype._linVelDamping=null;
RigidBody.prototype._rotVelDamping=null;
RigidBody.prototype._maxLinVelocities=null;
RigidBody.prototype._maxRotVelocities=null;
RigidBody.prototype._velChanged=null;
RigidBody.prototype._activity=null;
RigidBody.prototype._movable=null;
RigidBody.prototype._origMovable=null;
RigidBody.prototype._inactiveTime=null;
// The list of bodies that need to be activated when we move away from our stored position
RigidBody.prototype._bodiesToBeActivatedOnMovement=null;
RigidBody.prototype._storedPositionForActivation=null;// The position stored when we need to notify other bodies
RigidBody.prototype._lastPositionForDeactivation=null;// last position for when trying the deactivate
RigidBody.prototype._lastOrientationForDeactivation=null;// last orientation for when trying to deactivate
RigidBody.prototype._material=null;
RigidBody.prototype._rotationX = 0;
RigidBody.prototype._rotationY = 0;
RigidBody.prototype._rotationZ = 0;
RigidBody.prototype._useDegrees=null;
RigidBody.prototype._nonCollidables=null;
RigidBody.prototype._constraints=null;
RigidBody.prototype.collisions=null;
RigidBody.prototype.isActive=null;
RigidBody.prototype.radiansToDegrees=function(rad){
return rad * 180 / Math.PI;
}
RigidBody.prototype.degreesToRadians=function(deg){
return deg * Math.PI / 180;
}
RigidBody.prototype.get_rotationX=function(){
return this._rotationX;//(_useDegrees) ? radiansToDegrees(_rotationX) : _rotationX;
}
RigidBody.prototype.get_rotationY=function(){
return this._rotationY;//(_useDegrees) ? radiansToDegrees(_rotationY) : _rotationY;
}
RigidBody.prototype.get_rotationZ=function(){
return this._rotationZ;//(_useDegrees) ? radiansToDegrees(_rotationZ) : _rotationZ;
}
/**
* px - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationX=function(px){
//var rad:Number = (_useDegrees) ? degreesToRadians(px) : px;
this._rotationX = px;
this.setOrientation(this.createRotationMatrix());
}
/**
* py - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationY=function(py){
//var rad:Number = (_useDegrees) ? degreesToRadians(py) : py;
this._rotationY = py;
this.setOrientation(this.createRotationMatrix());
}
/**
* pz - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationZ=function(pz){
//var rad:Number = (_useDegrees) ? degreesToRadians(pz) : pz;
this._rotationZ = pz;
this.setOrientation(this.createRotationMatrix());
}
RigidBody.prototype.pitch=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.X_AXIS)));
}
RigidBody.prototype.yaw=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.Y_AXIS)));
}
RigidBody.prototype.roll=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.Z_AXIS)));
}
RigidBody.prototype.createRotationMatrix=function(){
var matrix3D = new Matrix3D();
matrix3D.appendRotation(this._rotationX, Vector3D.X_AXIS);
matrix3D.appendRotation(this._rotationY, Vector3D.Y_AXIS);
matrix3D.appendRotation(this._rotationZ, Vector3D.Z_AXIS);
return matrix3D;
}
RigidBody.prototype.setOrientation=function(orient){
//this._currState.get_orientation() = orient.clone();
this._currState.set_orientation(orient.clone());
this.updateInertia();
this.updateState();
}
RigidBody.prototype.get_x=function(){
return this._currState.position.x;
}
RigidBody.prototype.get_y=function(){
return this._currState.position.y;
}
RigidBody.prototype.get_z=function(){
return this._currState.position.z;
}
RigidBody.prototype.set_x=function(px){
this._currState.position.x = px;
this.updateState();
}
RigidBody.prototype.set_y=function(py){
this._currState.position.y = py;
this.updateState();
}
RigidBody.prototype.set_z=function(pz){
this._currState.position.z = pz;
this.updateState();
}
RigidBody.prototype.moveTo=function(pos){
this._currState.position = pos.clone();
this.updateState();
}
RigidBody.prototype.updateState=function(){
this._currState.linVelocity = new Vector3D();
this._currState.rotVelocity = new Vector3D();
this.copyCurrentStateToOld();
this.updateBoundingBox();
}
RigidBody.prototype.setVelocity=function(vel){
this._currState.linVelocity = vel.clone();
}
RigidBody.prototype.setAngVel=function(angVel){
this._currState.rotVelocity = angVel.clone();
}
RigidBody.prototype.setVelocityAux=function(vel){
this._currLinVelocityAux = vel.clone();
}
RigidBody.prototype.setAngVelAux=function(angVel){
this._currRotVelocityAux = angVel.clone();
}
RigidBody.prototype.addGravity=function(){
if (!this._movable){
return;
}
this._force = this._force.add(JNumber3D.getScaleVector(jigLib.PhysicsSystem.getInstance().get_gravity(), this._mass));
this._velChanged = true;
}
RigidBody.prototype.addExternalForces=function(dt){
this.addGravity();
}
RigidBody.prototype.addWorldTorque=function(t){
if (!this._movable){
return;
}
this._torque = this._torque.add(t);
this._velChanged = true;
this.setActive();
}
RigidBody.prototype.addBodyTorque=function(t){
if (!this._movable){
return;
}
JMatrix3D.multiplyVector(this._currState.get_orientation(), t);
this.addWorldTorque(t);
}
// functions to add forces in the world coordinate frame
RigidBody.prototype.addWorldForce=function(f, p){
if (!this._movable){
return;
}
this._force = this._force.add(f);
this.addWorldTorque(p.subtract(this._currState.position).crossProduct(f));
this._velChanged = true;
this.setActive();
}
// functions to add forces in the body coordinate frame
RigidBody.prototype.addBodyForce=function(f, p){
if (!this._movable){
return;
}
JMatrix3D.multiplyVector(this._currState.get_orientation(), f);
JMatrix3D.multiplyVector(this._currState.get_orientation(), p);
this.addWorldForce(f, this._currState.position.add(p));
}
// This just sets all forces etc to zero
RigidBody.prototype.clearForces=function(){
this._force = new Vector3D();
this._torque = new Vector3D();
}
// functions to add impulses in the world coordinate frame
RigidBody.prototype.applyWorldImpulse=function(impulse, pos){
if (!this._movable){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = pos.subtract(this._currState.position).crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currState.rotVelocity = this._currState.rotVelocity.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.applyWorldImpulseAux=function(impulse, pos){
if (!this._movable){
return;
}
this._currLinVelocityAux = this._currLinVelocityAux.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = pos.subtract(this._currState.position).crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currRotVelocityAux = this._currRotVelocityAux.add(rotImpulse);
this._velChanged = true;
}
// functions to add impulses in the body coordinate frame
RigidBody.prototype.applyBodyWorldImpulse=function(impulse, delta){
if (!this._movable){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = delta.crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currState.rotVelocity = this._currState.rotVelocity.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.applyBodyWorldImpulseAux=function(impulse, delta){
if (!this._movable){
return;
}
this._currLinVelocityAux = this._currLinVelocityAux.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = delta.crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currRotVelocityAux = this._currRotVelocityAux.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.addConstraint=function(constraint){
if (!this.findConstraint(constraint)){
this._constraints.push(constraint);
}
}
RigidBody.prototype.removeConstraint=function(constraint){
if (this.findConstraint(constraint)){
this._constraints.splice(this._constraints.indexOf(constraint), 1);
}
}
RigidBody.prototype.removeAllConstraints=function(){
this._constraints = [];
}
RigidBody.prototype.findConstraint=function(constraint){
for(var i=0; i<this._constraints.length;i++){
if (constraint == this._constraints[i]){
return true;
}
}
return false;
}
// implementation updates the velocity/angular rotation with the force/torque.
RigidBody.prototype.updateVelocity=function(dt){
if (!this._movable || !this._activity){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(this._force, this._invMass * dt));
var rac = JNumber3D.getScaleVector(this._torque, dt);
JMatrix3D.multiplyVector(this._worldInvInertia, rac);
this._currState.rotVelocity = this._currState.rotVelocity.add(rac);
}
// Updates the position with the auxiliary velocities, and zeros them
RigidBody.prototype.updatePositionWithAux=function(dt){
if (!this._movable || !this._activity){
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
return;
}
var ga = jigLib.PhysicsSystem.getInstance().get_gravityAxis();
if (ga != -1){
var arr = JNumber3D.toArray(this._currLinVelocityAux);
arr[(ga + 1) % 3] *= 0.1;
arr[(ga + 2) % 3] *= 0.1;
JNumber3D.copyFromArray(this._currLinVelocityAux, arr);
}
var angMomBefore = this._currState.rotVelocity.clone();
JMatrix3D.multiplyVector(this._worldInertia, angMomBefore);
this._currState.position = this._currState.position.add(JNumber3D.getScaleVector(this._currState.linVelocity.add(this._currLinVelocityAux), dt));
var dir = this._currState.rotVelocity.add(this._currRotVelocityAux);
var ang = dir.get_length() * 180 / Math.PI;
if (ang > 0){
dir.normalize();
ang *= dt;
var rot = JMatrix3D.getRotationMatrix(dir.x, dir.y, dir.z, ang);
this._currState.set_orientation(JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), rot));
this.updateInertia();
}
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
JMatrix3D.multiplyVector(this._worldInvInertia, angMomBefore);
this._currState.rotVelocity = angMomBefore.clone();
this.updateBoundingBox();
}
RigidBody.prototype.postPhysics=function(dt){
}
// function provided for the use of Physics system
RigidBody.prototype.tryToFreeze=function(dt){
if (!this._movable || !this._activity){
return;
}
if (this._currState.position.subtract(this._lastPositionForDeactivation).get_length() > JConfig.posThreshold){
this._lastPositionForDeactivation = this._currState.position.clone();
this._inactiveTime = 0;
return;
}
var ot = JConfig.orientThreshold;
var deltaMat = JMatrix3D.getSubMatrix(this._currState.get_orientation(), this._lastOrientationForDeactivation);
var cols = JMatrix3D.getCols(deltaMat);
if (cols[0].get_length() > ot || cols[1].get_length() > ot || cols[2].get_length() > ot){
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this._inactiveTime = 0;
return;
}
if (this.getShouldBeActive()){
return;
}
this._inactiveTime += dt;
if (this._inactiveTime > JConfig.deactivationTime){
this._lastPositionForDeactivation = this._currState.position.clone();
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this.setInactive();
}
}
RigidBody.prototype.set_mass=function(m){
this._mass = m;
this._invMass = 1 / m;
this.setInertia(this.getInertiaProperties(m));
}
RigidBody.prototype.setInertia=function(matrix3D){
this._bodyInertia = matrix3D.clone();
this._bodyInvInertia = JMatrix3D.getInverseMatrix(this._bodyInertia.clone());
this.updateInertia();
}
RigidBody.prototype.updateInertia=function(){
this._invOrientation = JMatrix3D.getTransposeMatrix(this._currState.get_orientation());
this._worldInertia = JMatrix3D.getAppendMatrix3D(
this._invOrientation,
JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), this._bodyInertia)
);
this._worldInvInertia = JMatrix3D.getAppendMatrix3D(
this._invOrientation,
JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), this._bodyInvInertia)
);
}
// prevent velocity updates etc
RigidBody.prototype.get_movable=function(){
return this._movable;
}
RigidBody.prototype.set_movable=function(mov){
if (this._type == "PLANE" || this._type == "TERRAIN") {
return;
}
this._movable = mov;
this.isActive = this._activity = mov;
this._origMovable = mov;
}
RigidBody.prototype.internalSetImmovable=function(){
this._origMovable = this._movable;
this._movable = false;
}
RigidBody.prototype.internalRestoreImmovable=function(){
this._movable = this._origMovable;
}
RigidBody.prototype.getVelChanged=function(){
return this._velChanged;
}
RigidBody.prototype.clearVelChanged=function(){
this._velChanged = false;
}
RigidBody.prototype.setActive=function(activityFactor){
if(!activityFactor) activityFactor=1;
if (this._movable){
this.isActive = this._activity = true;
this._inactiveTime = (1 - activityFactor) * JConfig.deactivationTime;
}
}
RigidBody.prototype.setInactive=function(){
if (this._movable){
this.isActive = this._activity = false;
}
}
// Returns the velocity of a point at body-relative position
RigidBody.prototype.getVelocity=function(relPos){
return this._currState.linVelocity.add(this._currState.rotVelocity.crossProduct(relPos));
}
// As GetVelocity but just uses the aux velocities
RigidBody.prototype.getVelocityAux=function(relPos){
return this._currLinVelocityAux.add(this._currRotVelocityAux.crossProduct(relPos));
}
// indicates if the velocity is above the threshold for freezing
RigidBody.prototype.getShouldBeActive=function(){
return ((this._currState.linVelocity.get_length() > JConfig.velThreshold) || (this._currState.rotVelocity.get_length() > JConfig.angVelThreshold));
}
RigidBody.prototype.getShouldBeActiveAux=function(){
return ((this._currLinVelocityAux.get_length() > JConfig.velThreshold) || (this._currRotVelocityAux.get_length() > JConfig.angVelThreshold));
}
// damp movement as the body approaches deactivation
RigidBody.prototype.dampForDeactivation=function(){
this._currState.linVelocity.x *= this._linVelDamping.x;
this._currState.linVelocity.y *= this._linVelDamping.y;
this._currState.linVelocity.z *= this._linVelDamping.z;
this._currState.rotVelocity.x *= this._rotVelDamping.x;
this._currState.rotVelocity.y *= this._rotVelDamping.y;
this._currState.rotVelocity.z *= this._rotVelDamping.z;
this._currLinVelocityAux.x *= this._linVelDamping.x;
this._currLinVelocityAux.y *= this._linVelDamping.y;
this._currLinVelocityAux.z *= this._linVelDamping.z;
this._currRotVelocityAux.x *= this._rotVelDamping.x;
this._currRotVelocityAux.y *= this._rotVelDamping.y;
this._currRotVelocityAux.z *= this._rotVelDamping.z;
var r = 0.5;
var frac = this._inactiveTime / JConfig.deactivationTime;
if (frac < r){
return;
}
var scale = 1 - ((frac - r) / (1 - r));
if (scale < 0){
scale = 0;
}else if (scale > 1){
scale = 1;
}
this._currState.linVelocity = JNumber3D.getScaleVector(this._currState.linVelocity, scale);
this._currState.rotVelocity = JNumber3D.getScaleVector(this._currState.rotVelocity, scale);
}
// function provided for use of physics system. Activates any
// body in its list if it's moved more than a certain distance,
// in which case it also clears its list.
RigidBody.prototype.doMovementActivations=function(){
if (this._bodiesToBeActivatedOnMovement.length == 0 || this._currState.position.subtract(this._storedPositionForActivation).get_length() < JConfig.posThreshold){
return;
}
for (var i = 0; i < this._bodiesToBeActivatedOnMovement.length; i++){
jigLib.PhysicsSystem.getInstance().activateObject(this._bodiesToBeActivatedOnMovement[i]);
}
this._bodiesToBeActivatedOnMovement = [];
}
// adds the other body to the list of bodies to be activated if
// this body moves more than a certain distance from either a
// previously stored position, or the position passed in.
RigidBody.prototype.addMovementActivation=function(pos, otherBody){
var len = this._bodiesToBeActivatedOnMovement.length;
for (var i = 0; i < len; i++){
if (this._bodiesToBeActivatedOnMovement[i] == otherBody){
return;
}
}
if (this._bodiesToBeActivatedOnMovement.length == 0){
this._storedPositionForActivation = pos;
}
this._bodiesToBeActivatedOnMovement.push(otherBody);
}
// Marks all constraints/collisions as being unsatisfied
RigidBody.prototype.setConstraintsAndCollisionsUnsatisfied=function(){
for(var i=0;i<this._constraints.length;i++){
this._constraints[i].set_satisfied(false);
}
for(var i=0;i<this.collisions.length;i++){
this.collisions[i].satisfied = false;
}
}
RigidBody.prototype.segmentIntersect=function(out, seg, state){
return false;
}
RigidBody.prototype.getInertiaProperties=function(m){
return new Matrix3D();
}
RigidBody.prototype.updateBoundingBox=function(){
}
RigidBody.prototype.hitTestObject3D=function(obj3D){
var num1 = this._currState.position.subtract(obj3D.get_currentState().position).get_length();
var num2 = this._boundingSphere + obj3D.get_boundingSphere();
if (num1 <= num2){
return true;
}
return false;
}
RigidBody.prototype.findNonCollidablesBody=function(body){
for(var i=0;i<this._nonCollidables.length;i++){
if (body == this._nonCollidables[i]){
return true;
}
}
return false;
}
RigidBody.prototype.disableCollisions=function(body){
if (!this.findNonCollidablesBody(body)){
this._nonCollidables.push(body);
}
}
RigidBody.prototype.enableCollisions=function(body){
if (this.findNonCollidablesBody(body)){
this._nonCollidables.splice(this._nonCollidables.indexOf(body), 1);
}
}
// copies the current position etc to old - normally called only by physicsSystem.
RigidBody.prototype.copyCurrentStateToOld=function(){
this._oldState.position = this._currState.position.clone();
this._oldState.set_orientation(this._currState.get_orientation().clone());
this._oldState.linVelocity = this._currState.linVelocity.clone();
this._oldState.rotVelocity = this._currState.rotVelocity.clone();
}
// Copy our current state into the stored state
RigidBody.prototype.storeState=function(){
this._storeState.position = this._currState.position.clone();
this._storeState.set_orientation(this._currState.get_orientation().clone());
this._storeState.linVelocity = this._currState.linVelocity.clone();
this._storeState.rotVelocity = this._currState.rotVelocity.clone();
}
// restore from the stored state into our current state.
RigidBody.prototype.restoreState=function(){
this._currState.position = this._storeState.position.clone();
this._currState.set_orientation(this._storeState.get_orientation().clone());
this._currState.linVelocity = this._storeState.linVelocity.clone();
this._currState.rotVelocity = this._storeState.rotVelocity.clone();
}
// the "working" state
RigidBody.prototype.get_currentState=function(){
return this._currState;
}
// the previous state - copied explicitly using copyCurrentStateToOld
RigidBody.prototype.get_oldState=function(){
return this._oldState;
}
RigidBody.prototype.get_id=function(){
return this._id;
}
RigidBody.prototype.get_type=function(){
return this._type;
}
RigidBody.prototype.get_skin=function(){
return this._skin;
}
RigidBody.prototype.get_boundingSphere=function(){
return this._boundingSphere;
}
RigidBody.prototype.get_boundingBox=function(){
return this._boundingBox;
}
// force in world frame
RigidBody.prototype.get_force=function(){
return this._force;
}
// torque in world frame
RigidBody.prototype.get_mass=function(){
return this._mass;
}
RigidBody.prototype.get_invMass=function(){
return this._invMass;
}
// inertia tensor in world space
RigidBody.prototype.get_worldInertia=function(){
return this._worldInertia;
}
// inverse inertia in world frame
RigidBody.prototype.get_worldInvInertia=function(){
return this._worldInvInertia;
}
RigidBody.prototype.get_nonCollidables=function(){
return this._nonCollidables;
}
//every dimension should be set to 0-1;
RigidBody.prototype.set_linVelocityDamping=function(vel){
this._linVelDamping.x = JNumber3D.getLimiteNumber(vel.x, 0, 1);
this._linVelDamping.y = JNumber3D.getLimiteNumber(vel.y, 0, 1);
this._linVelDamping.z = JNumber3D.getLimiteNumber(vel.z, 0, 1);
}
RigidBody.prototype.get_linVelocityDamping=function(){
return this._linVelDamping;
}
//every dimension should be set to 0-1;
RigidBody.prototype.set_rotVelocityDamping=function(vel){
this._rotVelDamping.x = JNumber3D.getLimiteNumber(vel.x, 0, 1);
this._rotVelDamping.y = JNumber3D.getLimiteNumber(vel.y, 0, 1);
this._rotVelDamping.z = JNumber3D.getLimiteNumber(vel.z, 0, 1);
}
RigidBody.prototype.get_rotVelocityDamping=function(){
return this._rotVelDamping;
}
//limit the max value of body's line velocity
RigidBody.prototype.set_maxLinVelocities=function(vel){
this._maxLinVelocities = JNumber3D.getLimiteNumber(Math.abs(vel), 0, 500);
}
RigidBody.prototype.get_maxLinVelocities=function(){
return this._maxLinVelocities;
}
//limit the max value of body's angle velocity
RigidBody.prototype.set_maxRotVelocities=function(vel){
this._maxRotVelocities = JNumber3D.getLimiteNumber(Math.abs(vel), JNumber3D.NUM_TINY, 50);
}
RigidBody.prototype.get_maxRotVelocities=function(){
return this._maxRotVelocities;
}
RigidBody.prototype.limitVel=function(){
this._currState.linVelocity.x = JNumber3D.getLimiteNumber(this._currState.linVelocity.x, -this._maxLinVelocities, this._maxLinVelocities);
this._currState.linVelocity.y = JNumber3D.getLimiteNumber(this._currState.linVelocity.y, -this._maxLinVelocities, this._maxLinVelocities);
this._currState.linVelocity.z = JNumber3D.getLimiteNumber(this._currState.linVelocity.z, -this._maxLinVelocities, this._maxLinVelocities);
}
RigidBody.prototype.limitAngVel=function(){
var fx = Math.abs(this._currState.rotVelocity.x) / this._maxRotVelocities;
var fy = Math.abs(this._currState.rotVelocity.y) / this._maxRotVelocities;
var fz = Math.abs(this._currState.rotVelocity.z) / this._maxRotVelocities;
var f = Math.max(fx, fy, fz);
if (f > 1){
this._currState.rotVelocity = JNumber3D.getDivideVector(this._currState.rotVelocity, f);
}
}
RigidBody.prototype.getTransform=function(){
if (this._skin != null){
return this._skin.get_transform();
}else{
return null;
}
}
//update skin
RigidBody.prototype.updateObject3D=function(){
if (this._skin != null){
this._skin.set_transform(JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), JMatrix3D.getTranslationMatrix(this._currState.position.x, this._currState.position.y, this._currState.position.z)));
}
}
RigidBody.prototype.get_material=function(){
return this._material;
}
//coefficient of elasticity
RigidBody.prototype.get_restitution=function(){
return this._material.get_restitution();
}
RigidBody.prototype.set_restitution=function(restitution){
this._material.set_restitution(JNumber3D.getLimiteNumber(restitution, 0, 1));
}
//coefficient of friction
RigidBody.prototype.get_friction=function(){
return this._material.get_friction();
}
RigidBody.prototype.set_friction=function(friction){
this._material.set_friction(JNumber3D.getLimiteNumber(friction, 0, 1));
}
jigLib.RigidBody=RigidBody;
})(jigLib)
| Pervasive/Lively3D | Dropbox/Lively3D/Resources/MiniGolf/scripts/rigid_body.js | JavaScript | mit | 29,886 |
<?php
namespace Admingenerator\GeneratorBundle\QueryFilter;
interface QueryFilterInterface
{
/**
* @param object $query the query object interface depend of the ORM
*
* @api
*/
function setQuery($query);
/**
* @return the query object interface depend of the ORM
*
* @api
*/
function getQuery();
/**
* Add filter for Default db types (types, not found
* by others add*Filter() methods
*
* @param string $field the db field
* @param string $value the search value
*
* @api
*/
function addDefaultFilter($field, $value);
}
| marius1092/test | vendor/bundles/Admingenerator/GeneratorBundle/QueryFilter/QueryFilterInterface.php | PHP | mit | 629 |
package model;
/**
* Тип дорожки.
*/
public enum LineType {
/**
* Верхняя. Проходит через левый нижний, левый верхний и правый верхний углы карты.
*/
TOP,
/**
* Центральная. Напрямую соединяет левый нижний и правый верхний углы карты.
*/
MIDDLE,
/**
* Нижняя. Проходит через левый нижний, правый нижний и правый верхний углы карты.
*/
BOTTOM
}
| spookiecookie/russianaicup | codewizards2016/java-cgdk/src/main/java/model/LineType.java | Java | mit | 606 |
app.factory('Pizza', ['$resource', 'LoginService', function ($resource, LoginService) {
const headers = {
token: getToken
};
return $resource('./api/pizzas/:id', { id: '@_id' },
{
query: {
method: 'GET',
isArray: true,
headers
},
save: {
method: 'POST',
headers
},
update: {
method: 'PUT',
headers
},
remove: {
method: 'DELETE',
headers,
params: {
id: '@id'
}
}
}
);
function getToken() {
return LoginService.getToken();
}
}]); | auromota/easy-pizza-api | src/public/js/factories/pizzaFactory.js | JavaScript | mit | 778 |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Stephen Connolly, Tom Huybrechts, InfraDNA, Inc.
*
* 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
* AUTHORS OR COPYRIGHT HOLDERS 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.
*/
package hudson.model;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.BulkChange;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.Initializer;
import static hudson.init.InitMilestone.JOB_LOADED;
import static hudson.util.Iterators.reverse;
import hudson.cli.declarative.CLIResolver;
import hudson.model.labels.LabelAssignmentAction;
import hudson.model.queue.AbstractQueueTask;
import hudson.model.queue.Executables;
import hudson.model.queue.QueueListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.ScheduleResult;
import hudson.model.queue.ScheduleResult.Created;
import hudson.model.queue.SubTask;
import hudson.model.queue.FutureImpl;
import hudson.model.queue.MappingWorksheet;
import hudson.model.queue.MappingWorksheet.Mapping;
import hudson.model.queue.QueueSorter;
import hudson.model.queue.QueueTaskDispatcher;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.model.Node.Mode;
import hudson.model.listeners.SaveableListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.FoldableAction;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsBusy;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy;
import hudson.model.queue.WorkUnitContext;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import jenkins.security.QueueItemAuthenticatorProvider;
import jenkins.util.Timer;
import hudson.triggers.SafeTimerTask;
import java.util.concurrent.TimeUnit;
import hudson.util.XStream2;
import hudson.util.ConsistentHash;
import hudson.util.ConsistentHash.Hash;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.security.QueueItemAuthenticator;
import jenkins.util.AtmostOneTaskExecutor;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.jenkinsci.bytecode.AdaptField;
import org.jenkinsci.remoting.RoleChecker;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.model.queue.CompositeCauseOfBlockage;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Build queue.
*
* <p>
* This class implements the core scheduling logic. {@link Task} represents the executable
* task that are placed in the queue. While in the queue, it's wrapped into {@link Item}
* so that we can keep track of additional data used for deciding what to execute when.
*
* <p>
* Items in queue goes through several stages, as depicted below:
* <pre>{@code
* (enter) --> waitingList --+--> blockedProjects
* | ^
* | |
* | v
* +--> buildables ---> pending ---> left
* ^ |
* | |
* +---(rarely)---+
* }</pre>
*
* <p>
* Note: In the normal case of events pending items only move to left. However they can move back
* if the node they are assigned to execute on disappears before their {@link Executor} thread
* starts, where the node is removed before the {@link Executable} has been instantiated it
* is safe to move the pending item back to buildable. Once the {@link Executable} has been
* instantiated the only option is to let the {@link Executable} bomb out as soon as it starts
* to try an execute on the node that no longer exists.
*
* <p>
* In addition, at any stage, an item can be removed from the queue (for example, when the user
* cancels a job in the queue.) See the corresponding field for their exact meanings.
*
* @author Kohsuke Kawaguchi
* @see QueueListener
* @see QueueTaskDispatcher
*/
@ExportedBean
public class Queue extends ResourceController implements Saveable {
/**
* Items that are waiting for its quiet period to pass.
*
* <p>
* This consists of {@link Item}s that cannot be run yet
* because its time has not yet come.
*/
private final Set<WaitingItem> waitingList = new TreeSet<WaitingItem>();
/**
* {@link Task}s that can be built immediately
* but blocked because another build is in progress,
* required {@link Resource}s are not available,
* blocked via {@link QueueTaskDispatcher#canRun(Item)},
* or otherwise blocked by {@link Task#isBuildBlocked()}.
*/
private final ItemList<BlockedItem> blockedProjects = new ItemList<BlockedItem>();
/**
* {@link Task}s that can be built immediately
* that are waiting for available {@link Executor}.
* This list is sorted in such a way that earlier items are built earlier.
*/
private final ItemList<BuildableItem> buildables = new ItemList<BuildableItem>();
/**
* {@link Task}s that are being handed over to the executor, but execution
* has not started yet.
*/
private final ItemList<BuildableItem> pendings = new ItemList<BuildableItem>();
private transient volatile Snapshot snapshot = new Snapshot(waitingList, blockedProjects, buildables, pendings);
/**
* Items that left queue would stay here for a while to enable tracking via {@link Item#getId()}.
*
* This map is forgetful, since we can't remember everything that executed in the past.
*/
private final Cache<Long,LeftItem> leftItems = CacheBuilder.newBuilder().expireAfterWrite(5*60, TimeUnit.SECONDS).build();
/**
* Data structure created for each idle {@link Executor}.
* This is a job offer from the queue to an executor.
*
* <p>
* For each idle executor, this gets created to allow the scheduling logic
* to assign a work. Once a work is assigned, the executor actually gets
* started to carry out the task in question.
*/
public static class JobOffer extends MappingWorksheet.ExecutorSlot {
public final Executor executor;
/**
* The work unit that this {@link Executor} is going to handle.
*/
private WorkUnit workUnit;
private JobOffer(Executor executor) {
this.executor = executor;
}
@Override
protected void set(WorkUnit p) {
assert this.workUnit == null;
this.workUnit = p;
assert executor.isParking();
executor.start(workUnit);
// LOGGER.info("Starting "+executor.getName());
}
@Override
public Executor getExecutor() {
return executor;
}
/**
* @deprecated discards information; prefer {@link #getCauseOfBlockage}
*/
@Deprecated
public boolean canTake(BuildableItem item) {
return getCauseOfBlockage(item) == null;
}
/**
* Checks whether the {@link Executor} represented by this object is capable of executing the given task.
* @return a reason why it cannot, or null if it could
* @since 2.37
*/
public @CheckForNull CauseOfBlockage getCauseOfBlockage(BuildableItem item) {
Node node = getNode();
if (node == null) {
return CauseOfBlockage.fromMessage(Messages._Queue_node_has_been_removed_from_configuration(executor.getOwner().getDisplayName()));
}
CauseOfBlockage reason = node.canTake(item);
if (reason != null) {
return reason;
}
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
reason = d.canTake(node, item);
if (reason != null) {
return reason;
}
}
// inlining isAvailable:
if (workUnit != null) { // unlikely in practice (should not have even found this executor if so)
return CauseOfBlockage.fromMessage(Messages._Queue_executor_slot_already_in_use());
}
if (executor.getOwner().isOffline()) {
return new CauseOfBlockage.BecauseNodeIsOffline(node);
}
if (!executor.getOwner().isAcceptingTasks()) { // Node.canTake (above) does not consider RetentionStrategy.isAcceptingTasks
return new CauseOfBlockage.BecauseNodeIsNotAcceptingTasks(node);
}
return null;
}
/**
* Is this executor ready to accept some tasks?
*/
public boolean isAvailable() {
return workUnit == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks();
}
@CheckForNull
public Node getNode() {
return executor.getOwner().getNode();
}
public boolean isNotExclusive() {
return getNode().getMode() == Mode.NORMAL;
}
@Override
public String toString() {
return String.format("JobOffer[%s #%d]",executor.getOwner().getName(), executor.getNumber());
}
}
private volatile transient LoadBalancer loadBalancer;
private volatile transient QueueSorter sorter;
private transient final AtmostOneTaskExecutor<Void> maintainerThread = new AtmostOneTaskExecutor<Void>(new Callable<Void>() {
@Override
public Void call() throws Exception {
maintain();
return null;
}
@Override
public String toString() {
return "Periodic Jenkins queue maintenance";
}
});
private transient final ReentrantLock lock = new ReentrantLock();
private transient final Condition condition = lock.newCondition();
public Queue(@Nonnull LoadBalancer loadBalancer) {
this.loadBalancer = loadBalancer.sanitize();
// if all the executors are busy doing something, then the queue won't be maintained in
// timely fashion, so use another thread to make sure it happens.
new MaintainTask(this).periodic();
}
public LoadBalancer getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(@Nonnull LoadBalancer loadBalancer) {
if(loadBalancer==null) throw new IllegalArgumentException();
this.loadBalancer = loadBalancer.sanitize();
}
public QueueSorter getSorter() {
return sorter;
}
public void setSorter(QueueSorter sorter) {
this.sorter = sorter;
}
/**
* Simple queue state persistence object.
*/
static class State {
public long counter;
public List<Item> items = new ArrayList<Item>();
}
/**
* Loads the queue contents that was {@link #save() saved}.
*/
public void load() {
lock.lock();
try { try {
// Clear items, for the benefit of reloading.
waitingList.clear();
blockedProjects.clear();
buildables.clear();
pendings.clear();
// first try the old format
File queueFile = getQueueFile();
if (queueFile.exists()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(Files.newInputStream(queueFile.toPath())))) {
String line;
while ((line = in.readLine()) != null) {
AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class);
if (j != null)
j.scheduleBuild();
}
} catch (InvalidPathException e) {
throw new IOException(e);
}
// discard the queue file now that we are done
queueFile.delete();
} else {
queueFile = getXMLQueueFile();
if (queueFile.exists()) {
Object unmarshaledObj = new XmlFile(XSTREAM, queueFile).read();
List items;
if (unmarshaledObj instanceof State) {
State state = (State) unmarshaledObj;
items = state.items;
WaitingItem.COUNTER.set(state.counter);
} else {
// backward compatibility - it's an old List queue.xml
items = (List) unmarshaledObj;
long maxId = 0;
for (Object o : items) {
if (o instanceof Item) {
maxId = Math.max(maxId, ((Item)o).id);
}
}
WaitingItem.COUNTER.set(maxId);
}
for (Object o : items) {
if (o instanceof Task) {
// backward compatibility
schedule((Task)o, 0);
} else if (o instanceof Item) {
Item item = (Item)o;
if (item.task == null) {
continue; // botched persistence. throw this one away
}
if (item instanceof WaitingItem) {
item.enter(this);
} else if (item instanceof BlockedItem) {
item.enter(this);
} else if (item instanceof BuildableItem) {
item.enter(this);
} else {
throw new IllegalStateException("Unknown item type! " + item);
}
}
}
// I just had an incident where all the executors are dead at AbstractProject._getRuns()
// because runs is null. Debugger revealed that this is caused by a MatrixConfiguration
// object that doesn't appear to be de-serialized properly.
// I don't know how this problem happened, but to diagnose this problem better
// when it happens again, save the old queue file for introspection.
File bk = new File(queueFile.getPath() + ".bak");
bk.delete();
queueFile.renameTo(bk);
queueFile.delete();
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load the queue file " + getXMLQueueFile(), e);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Persists the queue contents to the disk.
*/
public void save() {
if(BulkChange.contains(this)) return;
XmlFile queueFile = new XmlFile(XSTREAM, getXMLQueueFile());
lock.lock();
try {
// write out the queue state we want to save
State state = new State();
state.counter = WaitingItem.COUNTER.longValue();
// write out the tasks on the queue
for (Item item: getItems()) {
if(item.task instanceof TransientTask) continue;
state.items.add(item);
}
try {
queueFile.write(state);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to write out the queue file " + getXMLQueueFile(), e);
}
} finally {
lock.unlock();
}
SaveableListener.fireOnChange(this, queueFile);
}
/**
* Wipes out all the items currently in the queue, as if all of them are cancelled at once.
*/
public void clear() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
lock.lock();
try { try {
for (WaitingItem i : new ArrayList<WaitingItem>(
waitingList)) // copy the list as we'll modify it in the loop
i.cancel(this);
blockedProjects.cancelAll();
pendings.cancelAll();
buildables.cancelAll();
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
scheduleMaintenance();
}
private File getQueueFile() {
return new File(Jenkins.getInstance().getRootDir(), "queue.txt");
}
/*package*/ File getXMLQueueFile() {
return new File(Jenkins.getInstance().getRootDir(), "queue.xml");
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(AbstractProject)}
*/
@Deprecated
public boolean add(AbstractProject p) {
return schedule(p)!=null;
}
/**
* Schedule a new build for this project.
* @see #schedule(Task, int)
*/
public @CheckForNull WaitingItem schedule(AbstractProject p) {
return schedule(p, p.getQuietPeriod());
}
/**
* Schedules a new build with a custom quiet period.
*
* <p>
* Left for backward compatibility with <1.114.
*
* @since 1.105
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(AbstractProject p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
/**
* @deprecated as of 1.521
* Use {@link #schedule2(Task, int, List)}
*/
@Deprecated
public WaitingItem schedule(Task p, int quietPeriod, List<Action> actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Schedules an execution of a task.
*
* @param actions
* These actions can be used for associating information scoped to a particular build, to
* the task being queued. Upon the start of the build, these {@link Action}s will be automatically
* added to the {@link Run} object, and hence available to everyone.
* For the convenience of the caller, this list can contain null, and those will be silently ignored.
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Refused} if Jenkins refused to add this task into the queue (for example because the system
* is about to shutdown.) Otherwise the task is either merged into existing items in the queue
* (in which case you get {@link hudson.model.queue.ScheduleResult.Existing} instance back), or a new item
* gets created in the queue (in which case you get {@link Created}.
*
* Note the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link Queue.Item#future}, {@link Queue.Item#getId()}, etc.
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, List<Action> actions) {
// remove nulls
actions = new ArrayList<Action>(actions);
for (Iterator<Action> itr = actions.iterator(); itr.hasNext();) {
Action a = itr.next();
if (a==null) itr.remove();
}
lock.lock();
try { try {
for (QueueDecisionHandler h : QueueDecisionHandler.all())
if (!h.shouldSchedule(p, actions))
return ScheduleResult.refused(); // veto
return scheduleInternal(p, quietPeriod, actions);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Schedules an execution of a task.
*
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Existing} if this task is already in the queue and
* therefore the add operation was no-op. Otherwise {@link hudson.model.queue.ScheduleResult.Created}
* indicates the {@link WaitingItem} object added, although the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link WaitingItem#future}, {@link WaitingItem#getId()}, etc.
*/
private @Nonnull ScheduleResult scheduleInternal(Task p, int quietPeriod, List<Action> actions) {
lock.lock();
try { try {
Calendar due = new GregorianCalendar();
due.add(Calendar.SECOND, quietPeriod);
// Do we already have this task in the queue? Because if so, we won't schedule a new one.
List<Item> duplicatesInQueue = new ArrayList<Item>();
for (Item item : liveGetItems(p)) {
boolean shouldScheduleItem = false;
for (QueueAction action : item.getActions(QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule(actions);
}
for (QueueAction action : Util.filter(actions, QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule((new ArrayList<Action>(item.getAllActions())));
}
if (!shouldScheduleItem) {
duplicatesInQueue.add(item);
}
}
if (duplicatesInQueue.isEmpty()) {
LOGGER.log(Level.FINE, "{0} added to queue", p);
// put the item in the queue
WaitingItem added = new WaitingItem(due, p, actions);
added.enter(this);
scheduleMaintenance(); // let an executor know that a new item is in the queue.
return ScheduleResult.created(added);
}
LOGGER.log(Level.FINE, "{0} is already in the queue", p);
// but let the actions affect the existing stuff.
for (Item item : duplicatesInQueue) {
for (FoldableAction a : Util.filter(actions, FoldableAction.class)) {
a.foldIntoExisting(item, p, actions);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "after folding {0}, {1} includes {2}", new Object[] {a, item, item.getAllActions()});
}
}
}
boolean queueUpdated = false;
for (WaitingItem wi : Util.filter(duplicatesInQueue, WaitingItem.class)) {
// make sure to always use the shorter of the available due times
if (wi.timestamp.before(due))
continue;
// waitingList is sorted, so when we change a timestamp we need to maintain order
wi.leave(this);
wi.timestamp = due;
wi.enter(this);
queueUpdated = true;
}
if (queueUpdated) scheduleMaintenance();
// REVISIT: when there are multiple existing items in the queue that matches the incoming one,
// whether the new one should affect all existing ones or not is debatable. I for myself
// thought this would only affect one, so the code was bit of surprise, but I'm keeping the current
// behaviour.
return ScheduleResult.existing(duplicatesInQueue.get(0));
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod) {
return schedule(p, quietPeriod, new Action[0]);
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int, Action...)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod, Action... actions) {
return schedule(p, quietPeriod, actions)!=null;
}
/**
* Convenience wrapper method around {@link #schedule(Task, int, List)}
*/
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Convenience wrapper method around {@link #schedule2(Task, int, List)}
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, Arrays.asList(actions));
}
/**
* Cancels the item in the queue. If the item is scheduled more than once, cancels the first occurrence.
*
* @return true if the project was indeed in the queue and was removed.
* false if this was no-op.
*/
public boolean cancel(Task p) {
lock.lock();
try { try {
LOGGER.log(Level.FINE, "Cancelling {0}", p);
for (WaitingItem item : waitingList) {
if (item.task.equals(p)) {
return item.cancel(this);
}
}
// use bitwise-OR to make sure that both branches get evaluated all the time
return blockedProjects.cancel(p) != null | buildables.cancel(p) != null;
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
private void updateSnapshot() {
Snapshot revised = new Snapshot(waitingList, blockedProjects, buildables, pendings);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "{0} → {1}; leftItems={2}", new Object[] {snapshot, revised, leftItems.asMap()});
}
snapshot = revised;
}
public boolean cancel(Item item) {
LOGGER.log(Level.FINE, "Cancelling {0} item#{1}", new Object[] {item.task, item.id});
lock.lock();
try { try {
return item.cancel(this);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Called from {@code queue.jelly} and {@code entries.jelly}.
*/
@RequirePOST
public HttpResponse doCancelItem(@QueryParameter long id) throws IOException, ServletException {
Item item = getItem(id);
if (item != null) {
cancel(item);
} // else too late, ignore (JENKINS-14813)
return HttpResponses.forwardToPreviousPage();
}
public boolean isEmpty() {
Snapshot snapshot = this.snapshot;
return snapshot.waitingList.isEmpty() && snapshot.blockedProjects.isEmpty() && snapshot.buildables.isEmpty()
&& snapshot.pendings.isEmpty();
}
private WaitingItem peek() {
return waitingList.iterator().next();
}
/**
* Gets a snapshot of items in the queue.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Exported(inline=true)
public Item[] getItems() {
Snapshot s = this.snapshot;
List<Item> r = new ArrayList<Item>();
for(WaitingItem p : s.waitingList) {
r = checkPermissionsAndAddToList(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= checkPermissionsAndAddToList(r, p);
}
Item[] items = new Item[r.size()];
r.toArray(items);
return items;
}
private List<Item> checkPermissionsAndAddToList(List<Item> r, Item t) {
if (t.task instanceof hudson.security.AccessControlled) {
if (((hudson.security.AccessControlled)t.task).hasPermission(hudson.model.Item.READ)
|| ((hudson.security.AccessControlled) t.task).hasPermission(hudson.security.Permission.READ)) {
r.add(t);
}
}
return r;
}
/**
* Returns an array of Item for which it is only visible the name of the task.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Restricted(NoExternalUse.class)
@Exported(inline=true)
public StubItem[] getDiscoverableItems() {
Snapshot s = this.snapshot;
List<StubItem> r = new ArrayList<StubItem>();
for(WaitingItem p : s.waitingList) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= filterDiscoverableItemListBasedOnPermissions(r, p);
}
StubItem[] items = new StubItem[r.size()];
r.toArray(items);
return items;
}
private List<StubItem> filterDiscoverableItemListBasedOnPermissions(List<StubItem> r, Item t) {
if (t.task instanceof hudson.model.Item) {
if (!((hudson.model.Item)t.task).hasPermission(hudson.model.Item.READ) && ((hudson.model.Item)t.task).hasPermission(hudson.model.Item.DISCOVER)) {
r.add(new StubItem(new StubTask(t.task)));
}
}
return r;
}
/**
* Like {@link #getItems()}, but returns an approximation that might not be completely up-to-date.
*
* <p>
* At the expense of accuracy, this method does not usually lock {@link Queue} and therefore is faster
* in a highly concurrent situation.
*
* <p>
* The list obtained is an accurate snapshot of the queue at some point in the past. The snapshot
* is updated and normally no more than one second old, but this is a soft commitment that might
* get violated when the lock on {@link Queue} is highly contended.
*
* <p>
* This method is primarily added to make UI threads run faster.
*
* @since 1.483
* @deprecated Use {@link #getItems()} directly. As of 1.607 the approximation is no longer needed.
*/
@Deprecated
public List<Item> getApproximateItemsQuickly() {
return Arrays.asList(getItems());
}
public Item getItem(long id) {
Snapshot snapshot = this.snapshot;
for (Item item : snapshot.blockedProjects) {
if (item.id == id)
return item;
}
for (Item item : snapshot.buildables) {
if (item.id == id)
return item;
}
for (Item item : snapshot.pendings) {
if (item.id == id)
return item;
}
for (Item item : snapshot.waitingList) {
if (item.id == id) {
return item;
}
}
return leftItems.getIfPresent(id);
}
/**
* Gets all the {@link BuildableItem}s that are waiting for an executor in the given {@link Computer}.
*/
public List<BuildableItem> getBuildableItems(Computer c) {
Snapshot snapshot = this.snapshot;
List<BuildableItem> result = new ArrayList<BuildableItem>();
_getBuildableItems(c, snapshot.buildables, result);
_getBuildableItems(c, snapshot.pendings, result);
return result;
}
private void _getBuildableItems(Computer c, List<BuildableItem> col, List<BuildableItem> result) {
Node node = c.getNode();
if (node == null) // Deleted computers cannot take build items...
return;
for (BuildableItem p : col) {
if (node.canTake(p) == null)
result.add(p);
}
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getBuildableItems() {
Snapshot snapshot = this.snapshot;
ArrayList<BuildableItem> r = new ArrayList<BuildableItem>(snapshot.buildables);
r.addAll(snapshot.pendings);
return r;
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getPendingItems() {
return new ArrayList<BuildableItem>(snapshot.pendings);
}
/**
* Gets the snapshot of all {@link BlockedItem}s.
*/
protected List<BlockedItem> getBlockedItems() {
return new ArrayList<BlockedItem>(snapshot.blockedProjects);
}
/**
* Returns the snapshot of all {@link LeftItem}s.
*
* @since 1.519
*/
public Collection<LeftItem> getLeftItems() {
return Collections.unmodifiableCollection(leftItems.asMap().values());
}
/**
* Immediately clear the {@link #getLeftItems} cache.
* Useful for tests which need to verify that no links to a build remain.
* @since 1.519
*/
public void clearLeftItems() {
leftItems.invalidateAll();
}
/**
* Gets all items that are in the queue but not blocked
*
* @since 1.402
*/
public List<Item> getUnblockedItems() {
Snapshot snapshot = this.snapshot;
List<Item> queuedNotBlocked = new ArrayList<Item>();
queuedNotBlocked.addAll(snapshot.waitingList);
queuedNotBlocked.addAll(snapshot.buildables);
queuedNotBlocked.addAll(snapshot.pendings);
// but not 'blockedProjects'
return queuedNotBlocked;
}
/**
* Works just like {@link #getUnblockedItems()} but return tasks.
*
* @since 1.402
*/
public Set<Task> getUnblockedTasks() {
List<Item> items = getUnblockedItems();
Set<Task> unblockedTasks = new HashSet<Task>(items.size());
for (Queue.Item t : items)
unblockedTasks.add(t.task);
return unblockedTasks;
}
/**
* Is the given task currently pending execution?
*/
public boolean isPending(Task t) {
Snapshot snapshot = this.snapshot;
for (BuildableItem i : snapshot.pendings)
if (i.task.equals(t))
return true;
return false;
}
/**
* How many {@link BuildableItem}s are assigned for the given label?
* @param l Label to be checked. If null, any label will be accepted.
* If you want to count {@link BuildableItem}s without assigned labels,
* use {@link #strictCountBuildableItemsFor(hudson.model.Label)}.
* @return Number of {@link BuildableItem}s for the specified label.
*/
public @Nonnegative int countBuildableItemsFor(@CheckForNull Label l) {
Snapshot snapshot = this.snapshot;
int r = 0;
for (BuildableItem bi : snapshot.buildables)
for (SubTask st : bi.task.getSubTasks())
if (null == l || bi.getAssignedLabelFor(st) == l)
r++;
for (BuildableItem bi : snapshot.pendings)
for (SubTask st : bi.task.getSubTasks())
if (null == l || bi.getAssignedLabelFor(st) == l)
r++;
return r;
}
/**
* How many {@link BuildableItem}s are assigned for the given label?
* <p>
* The implementation is quite similar to {@link #countBuildableItemsFor(hudson.model.Label)},
* but it has another behavior for null parameters.
* @param l Label to be checked. If null, only jobs without assigned labels
* will be taken into the account.
* @return Number of {@link BuildableItem}s for the specified label.
* @since 1.615
*/
public @Nonnegative int strictCountBuildableItemsFor(@CheckForNull Label l) {
Snapshot _snapshot = this.snapshot;
int r = 0;
for (BuildableItem bi : _snapshot.buildables)
for (SubTask st : bi.task.getSubTasks())
if (bi.getAssignedLabelFor(st) == l)
r++;
for (BuildableItem bi : _snapshot.pendings)
for (SubTask st : bi.task.getSubTasks())
if (bi.getAssignedLabelFor(st) == l)
r++;
return r;
}
/**
* Counts all the {@link BuildableItem}s currently in the queue.
*/
public int countBuildableItems() {
return countBuildableItemsFor(null);
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
*/
public Item getItem(Task t) {
Snapshot snapshot = this.snapshot;
for (Item item : snapshot.blockedProjects) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.buildables) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.pendings) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.waitingList) {
if (item.task.equals(t)) {
return item;
}
}
return null;
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
* @since 1.607
*/
private List<Item> liveGetItems(Task t) {
lock.lock();
try {
List<Item> result = new ArrayList<Item>();
result.addAll(blockedProjects.getAll(t));
result.addAll(buildables.getAll(t));
// Do not include pendings—we have already finalized WorkUnitContext.actions.
if (LOGGER.isLoggable(Level.FINE)) {
List<BuildableItem> thePendings = pendings.getAll(t);
if (!thePendings.isEmpty()) {
LOGGER.log(Level.FINE, "ignoring {0} during scheduleInternal", thePendings);
}
}
for (Item item : waitingList) {
if (item.task.equals(t)) {
result.add(item);
}
}
return result;
} finally {
lock.unlock();
}
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
*/
public List<Item> getItems(Task t) {
Snapshot snapshot = this.snapshot;
List<Item> result = new ArrayList<Item>();
for (Item item : snapshot.blockedProjects) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.buildables) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.pendings) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.waitingList) {
if (item.task.equals(t)) {
result.add(item);
}
}
return result;
}
/**
* Returns true if this queue contains the said project.
*/
public boolean contains(Task t) {
return getItem(t)!=null;
}
/**
* Called when the executor actually starts executing the assigned work unit.
*
* This moves the task from the pending state to the "left the queue" state.
*/
/*package*/ void onStartExecuting(Executor exec) throws InterruptedException {
lock.lock();
try { try {
final WorkUnit wu = exec.getCurrentWorkUnit();
pendings.remove(wu.context.item);
LeftItem li = new LeftItem(wu.context);
li.enter(this);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Checks the queue and runs anything that can be run.
*
* <p>
* When conditions are changed, this method should be invoked.
* <p>
* This wakes up one {@link Executor} so that it will maintain a queue.
*/
@WithBridgeMethods(void.class)
public Future<?> scheduleMaintenance() {
// LOGGER.info("Scheduling maintenance");
return maintainerThread.submit();
}
/**
* Checks if the given item should be prevented from entering into the {@link #buildables} state
* and instead stay in the {@link #blockedProjects} state.
*/
private boolean isBuildBlocked(Item i) {
if (i.task.isBuildBlocked() || !canRun(i.task.getResourceList()))
return true;
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
if (d.canRun(i)!=null)
return true;
}
return false;
}
/**
* Make sure we don't queue two tasks of the same project to be built
* unless that project allows concurrent builds.
*/
private boolean allowNewBuildableTask(Task t) {
if (t.isConcurrentBuild()) {
return true;
}
return !buildables.containsKey(t) && !pendings.containsKey(t);
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
* @param runnable the operation to perform.
* @since 1.592
*/
public static void withLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
} else {
queue._withLock(runnable);
}
}
/**
* Some operations require the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @param <T> the type of exception.
* @return the result of the callable.
* @throws T the exception of the callable
* @since 1.592
*/
public static <V, T extends Throwable> V withLock(hudson.remoting.Callable<V, T> callable) throws T {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
} else {
return queue._withLock(callable);
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @return the result of the callable.
* @throws Exception if the callable throws an exception.
* @since 1.592
*/
public static <V> V withLock(java.util.concurrent.Callable<V> callable) throws Exception {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
} else {
return queue._withLock(callable);
}
}
/**
* Invokes the supplied {@link Runnable} if the {@link Queue} lock was obtained without blocking.
*
* @param runnable the operation to perform.
* @return {@code true} if the lock was available and the operation was performed.
* @since 1.618
*/
public static boolean tryWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
return true;
} else {
return queue._tryWithLock(runnable);
}
}
/**
* Wraps a {@link Runnable} with the {@link Queue} lock held.
*
* @param runnable the operation to wrap.
* @since 1.618
*/
public static Runnable wrapWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? runnable : new LockedRunnable(runnable);
}
/**
* Wraps a {@link hudson.remoting.Callable} with the {@link Queue} lock held.
*
* @param callable the operation to wrap.
* @since 1.618
*/
public static <V, T extends Throwable> hudson.remoting.Callable<V, T> wrapWithLock(hudson.remoting.Callable<V, T> callable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedHRCallable<>(callable);
}
/**
* Wraps a {@link java.util.concurrent.Callable} with the {@link Queue} lock held.
*
* @param callable the operation to wrap.
* @since 1.618
*/
public static <V> java.util.concurrent.Callable<V> wrapWithLock(java.util.concurrent.Callable<V> callable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedJUCCallable<V>(callable);
}
@Override
protected void _await() throws InterruptedException {
condition.await();
}
@Override
protected void _signalAll() {
condition.signalAll();
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
* @param runnable the operation to perform.
* @since 1.592
*/
protected void _withLock(Runnable runnable) {
lock.lock();
try {
runnable.run();
} finally {
lock.unlock();
}
}
/**
* Invokes the supplied {@link Runnable} if the {@link Queue} lock was obtained without blocking.
*
* @param runnable the operation to perform.
* @return {@code true} if the lock was available and the operation was performed.
* @since 1.618
*/
protected boolean _tryWithLock(Runnable runnable) {
if (lock.tryLock()) {
try {
runnable.run();
} finally {
lock.unlock();
}
return true;
} else {
return false;
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @param <T> the type of exception.
* @return the result of the callable.
* @throws T the exception of the callable
* @since 1.592
*/
protected <V, T extends Throwable> V _withLock(hudson.remoting.Callable<V, T> callable) throws T {
lock.lock();
try {
return callable.call();
} finally {
lock.unlock();
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @return the result of the callable.
* @throws Exception if the callable throws an exception.
* @since 1.592
*/
protected <V> V _withLock(java.util.concurrent.Callable<V> callable) throws Exception {
lock.lock();
try {
return callable.call();
} finally {
lock.unlock();
}
}
/**
* Queue maintenance.
*
* <p>
* Move projects between {@link #waitingList}, {@link #blockedProjects}, {@link #buildables}, and {@link #pendings}
* appropriately.
*
* <p>
* Jenkins internally invokes this method by itself whenever there's a change that can affect
* the scheduling (such as new node becoming online, # of executors change, a task completes execution, etc.),
* and it also gets invoked periodically (see {@link Queue.MaintainTask}.)
*/
public void maintain() {
lock.lock();
try { try {
LOGGER.log(Level.FINE, "Queue maintenance started on {0} with {1}", new Object[] {this, snapshot});
// The executors that are currently waiting for a job to run.
Map<Executor, JobOffer> parked = new HashMap<Executor, JobOffer>();
{// update parked (and identify any pending items whose executor has disappeared)
List<BuildableItem> lostPendings = new ArrayList<BuildableItem>(pendings);
for (Computer c : Jenkins.getInstance().getComputers()) {
for (Executor e : c.getExecutors()) {
if (e.isInterrupted()) {
// JENKINS-28840 we will deadlock if we try to touch this executor while interrupt flag set
// we need to clear lost pendings as we cannot know what work unit was on this executor
// while it is interrupted. (All this dancing is a result of Executor extending Thread)
lostPendings.clear(); // we'll get them next time around when the flag is cleared.
LOGGER.log(Level.FINEST,
"Interrupt thread for executor {0} is set and we do not know what work unit was on the executor.",
e.getDisplayName());
continue;
}
if (e.isParking()) {
LOGGER.log(Level.FINEST, "{0} is parking and is waiting for a job to execute.", e.getDisplayName());
parked.put(e, new JobOffer(e));
}
final WorkUnit workUnit = e.getCurrentWorkUnit();
if (workUnit != null) {
lostPendings.remove(workUnit.context.item);
}
}
}
// pending -> buildable
for (BuildableItem p: lostPendings) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"BuildableItem {0}: pending -> buildable as the assigned executor disappeared",
p.task.getFullDisplayName());
}
p.isPending = false;
pendings.remove(p);
makeBuildable(p); // TODO whatever this is for, the return value is being ignored, so this does nothing at all
}
}
final QueueSorter s = sorter;
{// blocked -> buildable
// copy as we'll mutate the list and we want to process in a potentially different order
List<BlockedItem> blockedItems = new ArrayList<>(blockedProjects.values());
// if facing a cycle of blocked tasks, ensure we process in the desired sort order
if (s != null) {
s.sortBlockedItems(blockedItems);
} else {
Collections.sort(blockedItems, QueueSorter.DEFAULT_BLOCKED_ITEM_COMPARATOR);
}
for (BlockedItem p : blockedItems) {
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
LOGGER.log(Level.FINEST, "Current blocked item: {0}", taskDisplayName);
if (!isBuildBlocked(p) && allowNewBuildableTask(p.task)) {
LOGGER.log(Level.FINEST,
"BlockedItem {0}: blocked -> buildable as the build is not blocked and new tasks are allowed",
taskDisplayName);
// ready to be executed
Runnable r = makeBuildable(new BuildableItem(p));
if (r != null) {
p.leave(this);
r.run();
// JENKINS-28926 we have removed a task from the blocked projects and added to building
// thus we should update the snapshot so that subsequent blocked projects can correctly
// determine if they are blocked by the lucky winner
updateSnapshot();
}
}
}
}
// waitingList -> buildable/blocked
while (!waitingList.isEmpty()) {
WaitingItem top = peek();
if (top.timestamp.compareTo(new GregorianCalendar()) > 0) {
LOGGER.log(Level.FINEST, "Finished moving all ready items from queue.");
break; // finished moving all ready items from queue
}
top.leave(this);
Task p = top.task;
if (!isBuildBlocked(top) && allowNewBuildableTask(p)) {
// ready to be executed immediately
Runnable r = makeBuildable(new BuildableItem(top));
String topTaskDisplayName = LOGGER.isLoggable(Level.FINEST) ? top.task.getFullDisplayName() : null;
if (r != null) {
LOGGER.log(Level.FINEST, "Executing runnable {0}", topTaskDisplayName);
r.run();
} else {
LOGGER.log(Level.FINEST, "Item {0} was unable to be made a buildable and is now a blocked item.", topTaskDisplayName);
new BlockedItem(top).enter(this);
}
} else {
// this can't be built now because another build is in progress
// set this project aside.
new BlockedItem(top).enter(this);
}
}
if (s != null)
s.sortBuildableItems(buildables);
// Ensure that identification of blocked tasks is using the live state: JENKINS-27708 & JENKINS-27871
updateSnapshot();
// allocate buildable jobs to executors
for (BuildableItem p : new ArrayList<BuildableItem>(
buildables)) {// copy as we'll mutate the list in the loop
// one last check to make sure this build is not blocked.
if (isBuildBlocked(p)) {
p.leave(this);
new BlockedItem(p).enter(this);
LOGGER.log(Level.FINE, "Catching that {0} is blocked in the last minute", p);
// JENKINS-28926 we have moved an unblocked task into the blocked state, update snapshot
// so that other buildables which might have been blocked by this can see the state change
updateSnapshot();
continue;
}
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
if (p.task instanceof FlyweightTask) {
Runnable r = makeFlyWeightTaskBuildable(new BuildableItem(p));
if (r != null) {
p.leave(this);
LOGGER.log(Level.FINEST, "Executing flyweight task {0}", taskDisplayName);
r.run();
updateSnapshot();
}
} else {
List<JobOffer> candidates = new ArrayList<>(parked.size());
List<CauseOfBlockage> reasons = new ArrayList<>(parked.size());
for (JobOffer j : parked.values()) {
CauseOfBlockage reason = j.getCauseOfBlockage(p);
if (reason == null) {
LOGGER.log(Level.FINEST,
"{0} is a potential candidate for task {1}",
new Object[]{j, taskDisplayName});
candidates.add(j);
} else {
LOGGER.log(Level.FINEST, "{0} rejected {1}: {2}", new Object[] {j, taskDisplayName, reason});
reasons.add(reason);
}
}
MappingWorksheet ws = new MappingWorksheet(p, candidates);
Mapping m = loadBalancer.map(p.task, ws);
if (m == null) {
// if we couldn't find the executor that fits,
// just leave it in the buildables list and
// check if we can execute other projects
LOGGER.log(Level.FINER, "Failed to map {0} to executors. candidates={1} parked={2}",
new Object[]{p, candidates, parked.values()});
p.transientCausesOfBlockage = reasons.isEmpty() ? null : reasons;
continue;
}
// found a matching executor. use it.
WorkUnitContext wuc = new WorkUnitContext(p);
LOGGER.log(Level.FINEST, "Found a matching executor for {0}. Using it.", taskDisplayName);
m.execute(wuc);
p.leave(this);
if (!wuc.getWorkUnits().isEmpty()) {
LOGGER.log(Level.FINEST, "BuildableItem {0} marked as pending.", taskDisplayName);
makePending(p);
}
else
LOGGER.log(Level.FINEST, "BuildableItem {0} with empty work units!?", p);
// Ensure that identification of blocked tasks is using the live state: JENKINS-27708 & JENKINS-27871
// The creation of a snapshot itself should be relatively cheap given the expected rate of
// job execution. You probably would need 100's of jobs starting execution every iteration
// of maintain() before this could even start to become an issue and likely the calculation
// of isBuildBlocked(p) will become a bottleneck before updateSnapshot() will. Additionally
// since the snapshot itself only ever has at most one reference originating outside of the stack
// it should remain in the eden space and thus be cheap to GC.
// See https://jenkins-ci.org/issue/27708?focusedCommentId=225819&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-225819
// or https://jenkins-ci.org/issue/27708?focusedCommentId=225906&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-225906
// for alternative fixes of this issue.
updateSnapshot();
}
}
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Tries to make an item ready to build.
* @param p a proposed buildable item
* @return a thunk to actually prepare it (after leaving an earlier list), or null if it cannot be run now
*/
private @CheckForNull Runnable makeBuildable(final BuildableItem p) {
if (p.task instanceof FlyweightTask) {
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
if (!isBlockedByShutdown(p.task)) {
Runnable runnable = makeFlyWeightTaskBuildable(p);
LOGGER.log(Level.FINEST, "Converting flyweight task: {0} into a BuildableRunnable", taskDisplayName);
if(runnable != null){
return runnable;
}
//this is to solve JENKINS-30084: the task has to be buildable to force the provisioning of nodes.
//if the execution gets here, it means the task could not be scheduled since the node
//the task is supposed to run on is offline or not available.
//Thus, the flyweighttask enters the buildables queue and will ask Jenkins to provision a node
LOGGER.log(Level.FINEST, "Flyweight task {0} is entering as buildable to provision a node.", taskDisplayName);
return new BuildableRunnable(p);
}
// if the execution gets here, it means the task is blocked by shutdown and null is returned.
LOGGER.log(Level.FINEST, "Task {0} is blocked by shutdown.", taskDisplayName);
return null;
} else {
// regular heavyweight task
return new BuildableRunnable(p);
}
}
/**
* This method checks if the flyweight task can be run on any of the available executors
* @param p - the flyweight task to be scheduled
* @return a Runnable if there is an executor that can take the task, null otherwise
*/
@CheckForNull
private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){
//we double check if this is a flyweight task
if (p.task instanceof FlyweightTask) {
Jenkins h = Jenkins.getInstance();
Map<Node, Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size());
// Even if master is configured with zero executors, we may need to run a flyweight task like MatrixProject on it.
hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1));
for (Node n : h.getNodes()) {
hashSource.put(n, n.getNumExecutors() * 100);
}
ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH);
hash.addAll(hashSource);
Label lbl = p.getAssignedLabel();
String fullDisplayName = p.task.getFullDisplayName();
for (Node n : hash.list(fullDisplayName)) {
final Computer c = n.toComputer();
if (c == null || c.isOffline()) {
continue;
}
if (lbl!=null && !lbl.contains(n)) {
continue;
}
if (n.canTake(p) != null) {
continue;
}
LOGGER.log(Level.FINEST, "Creating flyweight task {0} for computer {1}", new Object[]{fullDisplayName, c.getName()});
return new Runnable() {
@Override public void run() {
c.startFlyWeightTask(new WorkUnitContext(p).createWorkUnit(p.task));
makePending(p);
}
};
}
}
return null;
}
private static Hash<Node> NODE_HASH = new Hash<Node>() {
public String hash(Node node) {
return node.getNodeName();
}
};
private boolean makePending(BuildableItem p) {
// LOGGER.info("Making "+p.task+" pending"); // REMOVE
p.isPending = true;
return pendings.add(p);
}
/** @deprecated Use {@link #isBlockedByShutdown} instead. */
@Deprecated
public static boolean ifBlockedByHudsonShutdown(Task task) {
return isBlockedByShutdown(task);
}
/**
* Checks whether a task should not be scheduled because {@link Jenkins#isQuietingDown()}.
* @param task some queue task
* @return true if {@link Jenkins#isQuietingDown()} unless this is a {@link NonBlockingTask}
* @since 1.598
*/
public static boolean isBlockedByShutdown(Task task) {
return Jenkins.getInstance().isQuietingDown() && !(task instanceof NonBlockingTask);
}
public Api getApi() {
return new Api(this);
}
/**
* Marks {@link Task}s that are not persisted.
* @since 1.311
*/
public interface TransientTask extends Task {}
/**
* Marks {@link Task}s that do not consume {@link Executor}.
* @see OneOffExecutor
* @since 1.318
*/
public interface FlyweightTask extends Task {}
/**
* Marks {@link Task}s that are not affected by the {@linkplain Jenkins#isQuietingDown()} quieting down},
* because these tasks keep other tasks executing.
* @see #isBlockedByShutdown
* @since 1.336
*/
public interface NonBlockingTask extends Task {}
/**
* Task whose execution is controlled by the queue.
*
* <p>
* {@link #equals(Object) Value equality} of {@link Task}s is used
* to collapse two tasks into one. This is used to avoid infinite
* queue backlog.
*
* <p>
* Pending {@link Task}s are persisted when Hudson shuts down, so
* it needs to be persistable via XStream. To create a non-persisted
* transient Task, extend {@link TransientTask} marker interface.
*
* <p>
* Plugins are encouraged to extend from {@link AbstractQueueTask}
* instead of implementing this interface directly, to maintain
* compatibility with future changes to this interface.
*
* <p>
* Plugins are encouraged to implement {@link AccessControlled} otherwise
* the tasks will be hidden from display in the queue.
*
* <p>
* For historical reasons, {@link Task} object by itself
* also represents the "primary" sub-task (and as implied by this
* design, a {@link Task} must have at least one sub-task.)
* Most of the time, the primary subtask is the only sub task.
*/
public interface Task extends ModelObject, SubTask {
/**
* Returns true if the execution should be blocked
* for temporary reasons.
*
* <p>
* Short-hand for {@code getCauseOfBlockage()!=null}.
*/
boolean isBuildBlocked();
/**
* @deprecated as of 1.330
* Use {@link CauseOfBlockage#getShortDescription()} instead.
*/
@Deprecated
String getWhyBlocked();
/**
* If the execution of this task should be blocked for temporary reasons,
* this method returns a non-null object explaining why.
*
* <p>
* Otherwise this method returns null, indicating that the build can proceed right away.
*
* <p>
* This can be used to define mutual exclusion that goes beyond
* {@link #getResourceList()}.
* @return by default, null
*/
@CheckForNull
default CauseOfBlockage getCauseOfBlockage() {
return null;
}
/**
* Unique name of this task.
*
* <p>
* This method is no longer used, left here for compatibility. Just return {@link #getDisplayName()}.
*/
String getName();
/**
* @see hudson.model.Item#getFullDisplayName()
*/
String getFullDisplayName();
/**
* Checks the permission to see if the current user can abort this executable.
* Returns normally from this method if it's OK.
* <p>
* NOTE: If you have implemented {@link AccessControlled} this should just be
* {@code checkPermission(hudson.model.Item.CANCEL);}
*
* @throws AccessDeniedException if the permission is not granted.
*/
void checkAbortPermission();
/**
* Works just like {@link #checkAbortPermission()} except it indicates the status by a return value,
* instead of exception.
* Also used by default for {@link hudson.model.Queue.Item#hasCancelPermission}.
* <p>
* NOTE: If you have implemented {@link AccessControlled} this should just be
* {@code return hasPermission(hudson.model.Item.CANCEL);}
*
* @return false
* if the user doesn't have the permission.
*/
boolean hasAbortPermission();
/**
* Returns the URL of this task relative to the context root of the application.
*
* <p>
* When the user clicks an item in the queue, this is the page where the user is taken to.
* Hudson expects the current instance to be bound to the URL returned by this method.
*
* @return
* URL that ends with '/'.
*/
String getUrl();
/**
* True if the task allows concurrent builds, where the same {@link Task} is executed
* by multiple executors concurrently on the same or different nodes.
* @return by default, false
* @since 1.338
*/
default boolean isConcurrentBuild() {
return false;
}
/**
* Obtains the {@link SubTask}s that constitute this task.
*
* <p>
* The collection returned by this method must also contain the primary {@link SubTask}
* represented by this {@link Task} object itself as the first element.
* The returned value is read-only.
*
* <p>
* At least size 1.
*
* @return by default, {@code this}
* @since 1.377
*/
default Collection<? extends SubTask> getSubTasks() {
return Collections.singleton(this);
}
/**
* This method allows the task to provide the default fallback authentication object to be used
* when {@link QueueItemAuthenticator} fails to authenticate the build.
*
* <p>
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them.
*
* @return by default, {@link ACL#SYSTEM}
* @since 1.520
* @see QueueItemAuthenticator
* @see Tasks#getDefaultAuthenticationOf(Queue.Task)
*/
default @Nonnull Authentication getDefaultAuthentication() {
return ACL.SYSTEM;
}
/**
* This method allows the task to provide the default fallback authentication object to be used
* when {@link QueueItemAuthenticator} fails to authenticate the build.
*
* <p>
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them.
*
* <p>
* This method was added to an interface after it was created, so plugins built against
* older versions of Jenkins may not have this method implemented. Called private method _getDefaultAuthenticationOf(Task) on {@link Tasks}
* to avoid {@link AbstractMethodError}.
*
* @since 1.592
* @see QueueItemAuthenticator
* @see Tasks#getDefaultAuthenticationOf(Queue.Task, Queue.Item)
*/
default @Nonnull Authentication getDefaultAuthentication(Queue.Item item) {
return getDefaultAuthentication();
}
}
/**
* Represents the real meat of the computation run by {@link Executor}.
*
* <h2>Views</h2>
* <p>
* Implementation must have <tt>executorCell.jelly</tt>, which is
* used to render the HTML that indicates this executable is executing.
*/
public interface Executable extends Runnable {
/**
* Task from which this executable was created.
*
* <p>
* Since this method went through a signature change in 1.377, the invocation may results in
* {@link AbstractMethodError}.
* Use {@link Executables#getParentOf(Queue.Executable)} that avoids this.
*/
@Nonnull SubTask getParent();
/**
* Called by {@link Executor} to perform the task.
* @throws AsynchronousExecution if you would like to continue without consuming a thread
*/
@Override void run() throws AsynchronousExecution;
/**
* Estimate of how long will it take to execute this executable.
* Measured in milliseconds.
*
* @return -1 if it's impossible to estimate; default, {@link SubTask#getEstimatedDuration}
* @since 1.383
*/
default long getEstimatedDuration() {
return Executables.getParentOf(this).getEstimatedDuration();
}
/**
* Used to render the HTML. Should be a human readable text of what this executable is.
*/
@Override String toString();
}
/**
* Item in a queue.
*/
@ExportedBean(defaultVisibility = 999)
public static abstract class Item extends Actionable {
private final long id;
/**
* Unique ID (per master) that tracks the {@link Task} as it moves through different stages
* in the queue (each represented by different subtypes of {@link Item} and into any subsequent
* {@link Run} instance (see {@link Run#getQueueId()}).
* @return
* @since 1.601
*/
@Exported
public long getId() {
return id;
}
@AdaptField(was=int.class, name="id")
@Deprecated
public int getIdLegacy() {
if (id > Integer.MAX_VALUE) {
throw new IllegalStateException("Sorry, you need to update any Plugins attempting to " +
"assign 'Queue.Item.id' to an int value. 'Queue.Item.id' is now a long value and " +
"has incremented to a value greater than Integer.MAX_VALUE (2^31 - 1).");
}
return (int) id;
}
/**
* Project to be built.
*/
@Exported
public final Task task;
private /*almost final*/ transient FutureImpl future;
private final long inQueueSince;
/**
* Build is blocked because another build is in progress,
* required {@link Resource}s are not available, or otherwise blocked
* by {@link Task#isBuildBlocked()}.
*/
@Exported
public boolean isBlocked() { return this instanceof BlockedItem; }
/**
* Build is waiting the executor to become available.
* This flag is only used in {@link Queue#getItems()} for
* 'pseudo' items that are actually not really in the queue.
*/
@Exported
public boolean isBuildable() { return this instanceof BuildableItem; }
/**
* True if the item is starving for an executor for too long.
*/
@Exported
public boolean isStuck() { return false; }
/**
* Since when is this item in the queue.
* @return Unix timestamp
*/
@Exported
public long getInQueueSince() {
return this.inQueueSince;
}
/**
* Returns a human readable presentation of how long this item is already in the queue.
* E.g. something like '3 minutes 40 seconds'
*/
public String getInQueueForString() {
long duration = System.currentTimeMillis() - this.inQueueSince;
return Util.getTimeSpanString(duration);
}
/**
* Can be used to wait for the completion (either normal, abnormal, or cancellation) of the {@link Task}.
* <p>
* Just like {@link #getId()}, the same object tracks various stages of the queue.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<Executable> getFuture() { return future; }
/**
* If this task needs to be run on a node with a particular label,
* return that {@link Label}. Otherwise null, indicating
* it can run on anywhere.
*
* <p>
* This code takes {@link LabelAssignmentAction} into account, then fall back to {@link SubTask#getAssignedLabel()}
*/
public Label getAssignedLabel() {
for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) {
Label l = laa.getAssignedLabel(task);
if (l!=null) return l;
}
return task.getAssignedLabel();
}
/**
* Test if the specified {@link SubTask} needs to be run on a node with a particular label.
* <p>
* This method takes {@link LabelAssignmentAction} into account, the first
* non-null assignment will be returned.
* Otherwise falls back to {@link SubTask#getAssignedLabel()}
* @param st {@link SubTask} to be checked.
* @return Required {@link Label}. Otherwise null, indicating it can run on anywhere.
*/
public @CheckForNull Label getAssignedLabelFor(@Nonnull SubTask st) {
for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) {
Label l = laa.getAssignedLabel(st);
if (l!=null) return l;
}
return st.getAssignedLabel();
}
/**
* Convenience method that returns a read only view of the {@link Cause}s associated with this item in the queue.
*
* @return can be empty but never null
* @since 1.343
*/
public final List<Cause> getCauses() {
CauseAction ca = getAction(CauseAction.class);
if (ca!=null)
return Collections.unmodifiableList(ca.getCauses());
return Collections.emptyList();
}
@Restricted(DoNotUse.class) // used from Jelly
public String getCausesDescription() {
List<Cause> causes = getCauses();
StringBuilder s = new StringBuilder();
for (Cause c : causes) {
s.append(c.getShortDescription()).append('\n');
}
return s.toString();
}
protected Item(Task task, List<Action> actions, long id, FutureImpl future) {
this.task = task;
this.id = id;
this.future = future;
this.inQueueSince = System.currentTimeMillis();
for (Action action: actions) addAction(action);
}
protected Item(Task task, List<Action> actions, long id, FutureImpl future, long inQueueSince) {
this.task = task;
this.id = id;
this.future = future;
this.inQueueSince = inQueueSince;
for (Action action: actions) addAction(action);
}
protected Item(Item item) {
this(item.task, new ArrayList<Action>(item.getAllActions()), item.id, item.future, item.inQueueSince);
}
/**
* Returns the URL of this {@link Item} relative to the context path of Jenkins
*
* @return
* URL that ends with '/'.
* @since 1.519
*/
@Exported
public String getUrl() {
return "queue/item/"+id+'/';
}
/**
* Gets a human-readable status message describing why it's in the queue.
*/
@Exported
public final String getWhy() {
CauseOfBlockage cob = getCauseOfBlockage();
return cob!=null ? cob.getShortDescription() : null;
}
/**
* Gets an object that describes why this item is in the queue.
*/
public abstract CauseOfBlockage getCauseOfBlockage();
/**
* Gets a human-readable message about the parameters of this item
* @return String
*/
@Exported
public String getParams() {
StringBuilder s = new StringBuilder();
for (ParametersAction pa : getActions(ParametersAction.class)) {
for (ParameterValue p : pa.getParameters()) {
s.append('\n').append(p.getShortDescription());
}
}
return s.toString();
}
/**
* Checks whether a scheduled item may be canceled.
* @return by default, the same as {@link hudson.model.Queue.Task#hasAbortPermission}
*/
public boolean hasCancelPermission() {
return task.hasAbortPermission();
}
public String getDisplayName() {
// TODO Auto-generated method stub
return null;
}
public String getSearchUrl() {
// TODO Auto-generated method stub
return null;
}
/** @deprecated Use {@link #doCancelItem} instead. */
@Deprecated
@RequirePOST
public HttpResponse doCancelQueue() throws IOException, ServletException {
Jenkins.getInstance().getQueue().cancel(this);
return HttpResponses.forwardToPreviousPage();
}
/**
* Returns the identity that this task carries when it runs, for the purpose of access control.
*
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them. Implementers, if you are unsure,
* return the identity of the user who queued the task, or {@link ACL#SYSTEM} to bypass the access control
* and run as the super user.
*
* @since 1.520
*/
@Nonnull
public Authentication authenticate() {
for (QueueItemAuthenticator auth : QueueItemAuthenticatorProvider.authenticators()) {
Authentication a = auth.authenticate(this);
if (a!=null)
return a;
}
return task.getDefaultAuthentication(this);
}
public Api getApi() {
return new Api(this);
}
private Object readResolve() {
this.future = new FutureImpl(task);
return this;
}
@Override
public String toString() {
return getClass().getName() + ':' + task + ':' + id;
}
/**
* Enters the appropriate queue for this type of item.
*/
/*package*/ abstract void enter(Queue q);
/**
* Leaves the appropriate queue for this type of item.
*/
/*package*/ abstract boolean leave(Queue q);
/**
* Cancels this item, which updates {@link #future} to notify the listener, and
* also leaves the queue.
*
* @return true
* if the item was successfully cancelled.
*/
/*package*/ boolean cancel(Queue q) {
boolean r = leave(q);
if (r) {
future.setAsCancelled();
LeftItem li = new LeftItem(this);
li.enter(q);
}
return r;
}
}
/**
* A Stub class for {@link Task} which exposes only the name of the Task to be displayed when the user
* has DISCOVERY permissions only.
*/
@Restricted(NoExternalUse.class)
@ExportedBean(defaultVisibility = 999)
public static class StubTask {
private String name;
public StubTask(@Nonnull Queue.Task base) {
this.name = base.getName();
}
@Exported
public String getName() {
return name;
}
}
/**
* A Stub class for {@link Item} which exposes only the name of the Task to be displayed when the user
* has DISCOVERY permissions only.
*/
@Restricted(NoExternalUse.class)
@ExportedBean(defaultVisibility = 999)
public class StubItem {
@Exported public StubTask task;
public StubItem(StubTask task) {
this.task = task;
}
}
/**
* An optional interface for actions on Queue.Item.
* Lets the action cooperate in queue management.
*
* @since 1.300-ish.
*/
public interface QueueAction extends Action {
/**
* Returns whether the new item should be scheduled.
* An action should return true if the associated task is 'different enough' to warrant a separate execution.
*/
boolean shouldSchedule(List<Action> actions);
}
/**
* Extension point for deciding if particular job should be scheduled or not.
*
* <p>
* This handler is consulted every time someone tries to submit a task to the queue.
* If any of the registered handlers returns false, the task will not be added
* to the queue, and the task will never get executed.
*
* <p>
* The other use case is to add additional {@link Action}s to the task
* (for example {@link LabelAssignmentAction}) to tasks that are submitted to the queue.
*
* @since 1.316
*/
public static abstract class QueueDecisionHandler implements ExtensionPoint {
/**
* Returns whether the new item should be scheduled.
*
* @param actions
* List of actions that are to be made available as {@link AbstractBuild#getActions()}
* upon the start of the build. This list is live, and can be mutated.
*/
public abstract boolean shouldSchedule(Task p, List<Action> actions);
/**
* All registered {@link QueueDecisionHandler}s
*/
public static ExtensionList<QueueDecisionHandler> all() {
return ExtensionList.lookup(QueueDecisionHandler.class);
}
}
/**
* {@link Item} in the {@link Queue#waitingList} stage.
*/
public static final class WaitingItem extends Item implements Comparable<WaitingItem> {
private static final AtomicLong COUNTER = new AtomicLong(0);
/**
* This item can be run after this time.
*/
@Exported
public Calendar timestamp;
public WaitingItem(Calendar timestamp, Task project, List<Action> actions) {
super(project, actions, COUNTER.incrementAndGet(), new FutureImpl(project));
this.timestamp = timestamp;
}
static int getCurrentCounterValue() {
return COUNTER.intValue();
}
public int compareTo(WaitingItem that) {
int r = this.timestamp.getTime().compareTo(that.timestamp.getTime());
if (r != 0) return r;
if (this.getId() < that.getId()) {
return -1;
} else if (this.getId() == that.getId()) {
return 0;
} else {
return 1;
}
}
public CauseOfBlockage getCauseOfBlockage() {
long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
if (diff > 0)
return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff)));
else
return CauseOfBlockage.fromMessage(Messages._Queue_Unknown());
}
@Override
/*package*/ void enter(Queue q) {
if (q.waitingList.add(this)) {
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterWaiting(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
}
@Override
/*package*/ boolean leave(Queue q) {
boolean r = q.waitingList.remove(this);
if (r) {
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveWaiting(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* Common part between {@link BlockedItem} and {@link BuildableItem}.
*/
public static abstract class NotWaitingItem extends Item {
/**
* When did this job exit the {@link Queue#waitingList} phase?
*/
@Exported
public final long buildableStartMilliseconds;
protected NotWaitingItem(WaitingItem wi) {
super(wi);
buildableStartMilliseconds = System.currentTimeMillis();
}
protected NotWaitingItem(NotWaitingItem ni) {
super(ni);
buildableStartMilliseconds = ni.buildableStartMilliseconds;
}
}
/**
* {@link Item} in the {@link Queue#blockedProjects} stage.
*/
public final class BlockedItem extends NotWaitingItem {
public BlockedItem(WaitingItem wi) {
super(wi);
}
public BlockedItem(NotWaitingItem ni) {
super(ni);
}
public CauseOfBlockage getCauseOfBlockage() {
ResourceActivity r = getBlockingActivity(task);
if (r != null) {
if (r == task) // blocked by itself, meaning another build is in progress
return CauseOfBlockage.fromMessage(Messages._Queue_InProgress());
return CauseOfBlockage.fromMessage(Messages._Queue_BlockedBy(r.getDisplayName()));
}
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
CauseOfBlockage cause = d.canRun(this);
if (cause != null)
return cause;
}
return task.getCauseOfBlockage();
}
/*package*/ void enter(Queue q) {
LOGGER.log(Level.FINE, "{0} is blocked", this);
blockedProjects.add(this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterBlocked(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
/*package*/ boolean leave(Queue q) {
boolean r = blockedProjects.remove(this);
if (r) {
LOGGER.log(Level.FINE, "{0} no longer blocked", this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveBlocked(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* {@link Item} in the {@link Queue#buildables} stage.
*/
public final static class BuildableItem extends NotWaitingItem {
/**
* Set to true when this is added to the {@link Queue#pendings} list.
*/
private boolean isPending;
/**
* Reasons why the last call to {@link #maintain} left this buildable (but not blocked or executing).
* May be null but not empty.
*/
private transient volatile @CheckForNull List<CauseOfBlockage> transientCausesOfBlockage;
public BuildableItem(WaitingItem wi) {
super(wi);
}
public BuildableItem(NotWaitingItem ni) {
super(ni);
}
public CauseOfBlockage getCauseOfBlockage() {
Jenkins jenkins = Jenkins.getInstance();
if(isBlockedByShutdown(task))
return CauseOfBlockage.fromMessage(Messages._Queue_HudsonIsAboutToShutDown());
List<CauseOfBlockage> causesOfBlockage = transientCausesOfBlockage;
Label label = getAssignedLabel();
List<Node> allNodes = jenkins.getNodes();
if (allNodes.isEmpty())
label = null; // no master/agent. pointless to talk about nodes
if (label != null) {
Set<Node> nodes = label.getNodes();
if (label.isOffline()) {
if (nodes.size() != 1) return new BecauseLabelIsOffline(label);
else return new BecauseNodeIsOffline(nodes.iterator().next());
} else {
if (causesOfBlockage != null && label.getIdleExecutors() > 0) {
return new CompositeCauseOfBlockage(causesOfBlockage);
}
if (nodes.size() != 1) return new BecauseLabelIsBusy(label);
else return new BecauseNodeIsBusy(nodes.iterator().next());
}
} else if (causesOfBlockage != null && new ComputerSet().getIdleExecutors() > 0) {
return new CompositeCauseOfBlockage(causesOfBlockage);
} else {
return CauseOfBlockage.createNeedsMoreExecutor(Messages._Queue_WaitingForNextAvailableExecutor());
}
}
@Override
public boolean isStuck() {
Label label = getAssignedLabel();
if(label!=null && label.isOffline())
// no executor online to process this job. definitely stuck.
return true;
long d = task.getEstimatedDuration();
long elapsed = System.currentTimeMillis()-buildableStartMilliseconds;
if(d>=0) {
// if we were running elsewhere, we would have done this build ten times.
return elapsed > Math.max(d,60000L)*10;
} else {
// more than a day in the queue
return TimeUnit.MILLISECONDS.toHours(elapsed)>24;
}
}
@Exported
public boolean isPending() {
return isPending;
}
@Override
/*package*/ void enter(Queue q) {
q.buildables.add(this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterBuildable(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
@Override
/*package*/ boolean leave(Queue q) {
boolean r = q.buildables.remove(this);
if (r) {
LOGGER.log(Level.FINE, "{0} no longer blocked", this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveBuildable(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* {@link Item} in the {@link Queue#leftItems} stage. These are items that had left the queue
* by either began executing or by getting cancelled.
*
* @since 1.519
*/
public final static class LeftItem extends Item {
public final WorkUnitContext outcome;
/**
* When item has left the queue and begin executing.
*/
public LeftItem(WorkUnitContext wuc) {
super(wuc.item);
this.outcome = wuc;
}
/**
* When item is cancelled.
*/
public LeftItem(Item cancelled) {
super(cancelled);
this.outcome = null;
}
@Override
public CauseOfBlockage getCauseOfBlockage() {
return null;
}
/**
* If this is representing an item that started executing, this property returns
* the primary executable (such as {@link AbstractBuild}) that created out of it.
*/
@Exported
public @CheckForNull Executable getExecutable() {
return outcome!=null ? outcome.getPrimaryWorkUnit().getExecutable() : null;
}
/**
* Is this representing a cancelled item?
*/
@Exported
public boolean isCancelled() {
return outcome==null;
}
@Override
void enter(Queue q) {
q.leftItems.put(getId(),this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeft(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
@Override
boolean leave(Queue q) {
// there's no leave operation
return false;
}
}
private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
/**
* This {@link XStream} instance is used to persist {@link Task}s.
*/
public static final XStream XSTREAM = new XStream2();
static {
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@Override
@SuppressWarnings("unchecked")
public boolean canConvert(Class klazz) {
return hudson.model.Item.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
Object item = Jenkins.getInstance().getItemByFullName(string);
if(item==null) throw new NoSuchElementException("No such job exists: "+string);
return item;
}
@Override
public String toString(Object item) {
return ((hudson.model.Item) item).getFullName();
}
});
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class klazz) {
return Run.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
String[] split = string.split("#");
String projectName = split[0];
int buildNumber = Integer.parseInt(split[1]);
Job<?,?> job = (Job<?,?>) Jenkins.getInstance().getItemByFullName(projectName);
if(job==null) throw new NoSuchElementException("No such job exists: "+projectName);
Run<?,?> run = job.getBuildByNumber(buildNumber);
if(run==null) throw new NoSuchElementException("No such build: "+string);
return run;
}
@Override
public String toString(Object object) {
Run<?,?> run = (Run<?,?>) object;
return run.getParent().getFullName() + "#" + run.getNumber();
}
});
/**
* Reconnect every reference to {@link Queue} by the singleton.
*/
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@Override
public boolean canConvert(Class klazz) {
return Queue.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
return Jenkins.getInstance().getQueue();
}
@Override
public String toString(Object item) {
return "queue";
}
});
}
/**
* Regularly invokes {@link Queue#maintain()} and clean itself up when
* {@link Queue} gets GC-ed.
*/
private static class MaintainTask extends SafeTimerTask {
private final WeakReference<Queue> queue;
MaintainTask(Queue queue) {
this.queue = new WeakReference<Queue>(queue);
}
private void periodic() {
long interval = 5000;
Timer.get().scheduleWithFixedDelay(this, interval, interval, TimeUnit.MILLISECONDS);
}
protected void doRun() {
Queue q = queue.get();
if (q != null)
q.maintain();
else
cancel();
}
}
/**
* {@link ArrayList} of {@link Item} with more convenience methods.
*/
private class ItemList<T extends Item> extends ArrayList<T> {
public T get(Task task) {
for (T item: this) {
if (item.task.equals(task)) {
return item;
}
}
return null;
}
public List<T> getAll(Task task) {
List<T> result = new ArrayList<T>();
for (T item: this) {
if (item.task.equals(task)) {
result.add(item);
}
}
return result;
}
public boolean containsKey(Task task) {
return get(task) != null;
}
public T remove(Task task) {
Iterator<T> it = iterator();
while (it.hasNext()) {
T t = it.next();
if (t.task.equals(task)) {
it.remove();
return t;
}
}
return null;
}
public void put(Task task, T item) {
assert item.task.equals(task);
add(item);
}
public ItemList<T> values() {
return this;
}
/**
* Works like {@link #remove(Task)} but also marks the {@link Item} as cancelled.
*/
public T cancel(Task p) {
T x = get(p);
if(x!=null) x.cancel(Queue.this);
return x;
}
@SuppressFBWarnings(value = "IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD",
justification = "It will invoke the inherited clear() method according to Java semantics. "
+ "FindBugs recommends suppressing warnings in such case")
public void cancelAll() {
for (T t : new ArrayList<T>(this))
t.cancel(Queue.this);
clear();
}
}
private static class Snapshot {
private final Set<WaitingItem> waitingList;
private final List<BlockedItem> blockedProjects;
private final List<BuildableItem> buildables;
private final List<BuildableItem> pendings;
public Snapshot(Set<WaitingItem> waitingList, List<BlockedItem> blockedProjects, List<BuildableItem> buildables,
List<BuildableItem> pendings) {
this.waitingList = new LinkedHashSet<WaitingItem>(waitingList);
this.blockedProjects = new ArrayList<BlockedItem>(blockedProjects);
this.buildables = new ArrayList<BuildableItem>(buildables);
this.pendings = new ArrayList<BuildableItem>(pendings);
}
@Override
public String toString() {
return "Queue.Snapshot{waitingList=" + waitingList + ";blockedProjects=" + blockedProjects + ";buildables=" + buildables + ";pendings=" + pendings + "}";
}
}
private static class LockedRunnable implements Runnable {
private final Runnable delegate;
private LockedRunnable(Runnable delegate) {
this.delegate = delegate;
}
@Override
public void run() {
withLock(delegate);
}
}
private class BuildableRunnable implements Runnable {
private final BuildableItem buildableItem;
private BuildableRunnable(BuildableItem p) {
this.buildableItem = p;
}
@Override
public void run() {
//the flyweighttask enters the buildables queue and will ask Jenkins to provision a node
buildableItem.enter(Queue.this);
}
}
private static class LockedJUCCallable<V> implements java.util.concurrent.Callable<V> {
private final java.util.concurrent.Callable<V> delegate;
private LockedJUCCallable(java.util.concurrent.Callable<V> delegate) {
this.delegate = delegate;
}
@Override
public V call() throws Exception {
return withLock(delegate);
}
}
private static class LockedHRCallable<V,T extends Throwable> implements hudson.remoting.Callable<V,T> {
private static final long serialVersionUID = 1L;
private final hudson.remoting.Callable<V,T> delegate;
private LockedHRCallable(hudson.remoting.Callable<V,T> delegate) {
this.delegate = delegate;
}
@Override
public V call() throws T {
return withLock(delegate);
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
delegate.checkRoles(checker);
}
}
@CLIResolver
public static Queue getInstance() {
return Jenkins.getInstance().getQueue();
}
/**
* Restores the queue content during the start up.
*/
@Initializer(after=JOB_LOADED)
public static void init(Jenkins h) {
h.getQueue().load();
}
}
| tfennelly/jenkins | core/src/main/java/hudson/model/Queue.java | Java | mit | 108,599 |
require "action_controller"
Mime::Type.register "application/pdf", :pdf
require "prawn"
ActionController::Renderers.add :pdf do |filename, options|
pdf = Prawn::Document.new
pdf.text render_to_string options
send_data pdf.render, :filename => "#{filename}.pdf",
:type => "application/pdf", :disposition => "attachment"
end
module PdfRenderer
end
| travisjeffery/pdf_renderer | lib/pdf_renderer.rb | Ruby | mit | 361 |
describe('modelAndOptionMapping', function() {
var utHelper = window.utHelper;
var testCase = utHelper.prepare([
'echarts/src/component/grid',
'echarts/src/chart/line',
'echarts/src/chart/pie',
'echarts/src/chart/bar',
'echarts/src/component/toolbox',
'echarts/src/component/dataZoom'
]);
function getData0(chart, seriesIndex) {
return getSeries(chart, seriesIndex).getData().get('y', 0);
}
function getSeries(chart, seriesIndex) {
return chart.getModel().getComponent('series', seriesIndex);
}
function getModel(chart, type, index) {
return chart.getModel().getComponent(type, index);
}
function countSeries(chart) {
return countModel(chart, 'series');
}
function countModel(chart, type) {
// FIXME
// access private
return chart.getModel()._componentsMap.get(type).length;
}
function getChartView(chart, series) {
return chart._chartsMap[series.__viewId];
}
function countChartViews(chart) {
return chart._chartsViews.length;
}
function saveOrigins(chart) {
var count = countSeries(chart);
var origins = [];
for (var i = 0; i < count; i++) {
var series = getSeries(chart, i);
origins.push({
model: series,
view: getChartView(chart, series)
});
}
return origins;
}
function modelEqualsToOrigin(chart, idxList, origins, boolResult) {
for (var i = 0; i < idxList.length; i++) {
var idx = idxList[i];
expect(origins[idx].model === getSeries(chart, idx)).toEqual(boolResult);
}
}
function viewEqualsToOrigin(chart, idxList, origins, boolResult) {
for (var i = 0; i < idxList.length; i++) {
var idx = idxList[i];
expect(
origins[idx].view === getChartView(chart, getSeries(chart, idx))
).toEqual(boolResult);
}
}
describe('idNoNameNo', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Not merge
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
modelEqualsToOrigin(chart, [0, 1, 2], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('sameTypeMergeFull', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{type: 'line', data: [111]},
{type: 'line', data: [222]},
{type: 'line', data: [333]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(111);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(333);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
modelEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('sameTypeMergePartial', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{data: [22222]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(22222);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
modelEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('differentTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{type: 'line', data: [111]},
{type: 'bar', data: [222]},
{type: 'line', data: [333]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(111);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(333);
expect(getSeries(chart, 1).type === 'series.bar').toEqual(true);
modelEqualsToOrigin(chart, [0, 2], origins, true);
modelEqualsToOrigin(chart, [1], origins, false);
viewEqualsToOrigin(chart, [0, 2], origins, true);
viewEqualsToOrigin(chart, [1], origins, false);
});
});
describe('idSpecified', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(countSeries(chart)).toEqual(5);
expect(countChartViews(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('sameTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
chart.setOption(option);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('differentTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'bar', data: [44]},
{type: 'line', data: [55]}
]
};
chart.setOption(option2, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergeFull', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30, name: 'a'},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], id: 20, name: 'a'},
{type: 'line', data: [33], id: 30},
{type: 'bar', data: [44]},
{type: 'line', data: [55]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 2, 4], origins, true);
modelEqualsToOrigin(chart, [1, 3], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergePartial1', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33]},
{type: 'line', data: [44], id: 40},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'line', data: [222], id: 20}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(444);
expect(getData0(chart, 4)).toEqual(55);
modelEqualsToOrigin(chart, [0, 1, 2, 4], origins, true);
modelEqualsToOrigin(chart, [3], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 4], origins, true);
viewEqualsToOrigin(chart, [3], origins, false);
});
testCase.createChart()('differentTypeMergePartial2', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'line', data: [222], id: 20},
{type: 'line', data: [111]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(4);
expect(countSeries(chart)).toEqual(4);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(444);
expect(getData0(chart, 3)).toEqual(111);
});
testCase.createChart()('mergePartialDoNotMapToOtherId', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], id: 10},
{type: 'line', data: [22], id: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(444);
});
testCase.createChart()('idDuplicate', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], id: 10},
{type: 'line', data: [22], id: 10}
]
};
var chart = this.chart;
expect(function () {
chart.setOption(option);
}).toThrowError(/duplicate/);
});
testCase.createChart()('nameTheSameButIdNotTheSame', function () {
var chart = this.chart;
var option = {
grid: {},
xAxis: [
{id: 'x1', name: 'a', xxxx: 'x1_a'},
{id: 'x2', name: 'b', xxxx: 'x2_b'}
],
yAxis: {}
};
chart.setOption(option);
var xAxisModel0 = getModel(chart, 'xAxis', 0);
var xAxisModel1 = getModel(chart, 'xAxis', 1);
expect(xAxisModel0.option.xxxx).toEqual('x1_a');
expect(xAxisModel1.option.xxxx).toEqual('x2_b');
expect(xAxisModel1.option.name).toEqual('b');
var option2 = {
xAxis: [
{id: 'k1', name: 'a', xxxx: 'k1_a'},
{id: 'x2', name: 'a', xxxx: 'x2_a'}
]
};
chart.setOption(option2);
var xAxisModel0 = getModel(chart, 'xAxis', 0);
var xAxisModel1 = getModel(chart, 'xAxis', 1);
var xAxisModel2 = getModel(chart, 'xAxis', 2);
expect(xAxisModel0.option.xxxx).toEqual('x1_a');
expect(xAxisModel1.option.xxxx).toEqual('x2_a');
expect(xAxisModel1.option.name).toEqual('a');
expect(xAxisModel2.option.xxxx).toEqual('k1_a');
});
});
describe('noIdButNameExists', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
expect(getSeries(chart, 1)).not.toEqual(getSeries(chart, 4));
expect(countSeries(chart)).toEqual(5);
expect(countChartViews(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('sameTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
chart.setOption(option);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('differentTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'bar', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
chart.setOption(option2, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergePartialOneMapTwo', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33]},
{type: 'line', data: [44], name: 'b'},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'bar', data: [222], name: 'a'}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(6);
expect(countSeries(chart)).toEqual(6);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
expect(getData0(chart, 5)).toEqual(444);
modelEqualsToOrigin(chart, [0, 2, 3, 4], origins, true);
modelEqualsToOrigin(chart, [1], origins, false);
viewEqualsToOrigin(chart, [0, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [1], origins, false);
});
testCase.createChart()('differentTypeMergePartialTwoMapOne', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], name: 'a'},
{type: 'line', data: [333]},
{type: 'line', data: [222], name: 'a'},
{type: 'line', data: [111]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(4);
expect(countSeries(chart)).toEqual(4);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(444);
expect(getData0(chart, 2)).toEqual(222);
expect(getData0(chart, 3)).toEqual(111);
});
testCase.createChart()('mergePartialCanMapToOtherName', function () {
// Consider case: axis.name = 'some label', which can be overwritten.
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], name: 10},
{type: 'line', data: [22], name: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], name: 40},
{type: 'bar', data: [999], name: 40},
{type: 'bar', data: [777], id: 70}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(444);
expect(getData0(chart, 1)).toEqual(999);
expect(getData0(chart, 2)).toEqual(777);
});
});
describe('ohters', function () {
testCase.createChart()('aBugCase', function () {
var option = {
series: [
{
type:'pie',
radius: ['20%', '25%'],
center:['20%', '20%'],
avoidLabelOverlap: true,
hoverAnimation :false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
},
emphasis: {
show: true
}
},
data:[
{value:135, name:'视频广告'},
{value:1548}
]
}
]
};
var chart = this.chart;
chart.setOption(option);
chart.setOption({
series: [
{
type:'pie',
radius: ['20%', '25%'],
center: ['20%', '20%'],
avoidLabelOverlap: true,
hoverAnimation: false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
data: [
{value:135, name:'视频广告'},
{value:1548}
]
},
{
type:'pie',
radius: ['20%', '25%'],
center: ['60%', '20%'],
avoidLabelOverlap: true,
hoverAnimation: false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
data: [
{value:135, name:'视频广告'},
{value:1548}
]
}
]
}, true);
expect(countChartViews(chart)).toEqual(2);
expect(countSeries(chart)).toEqual(2);
});
testCase.createChart()('color', function () {
var option = {
backgroundColor: 'rgba(1,1,1,1)',
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(chart._model.option.backgroundColor).toEqual('rgba(1,1,1,1)');
// Not merge
chart.setOption({
backgroundColor: '#fff'
}, true);
expect(chart._model.option.backgroundColor).toEqual('#fff');
});
testCase.createChart()('innerId', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
toolbox: {
feature: {
dataZoom: {}
}
},
dataZoom: [
{type: 'inside', id: 'a'},
{type: 'slider', id: 'b'}
],
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(countModel(chart, 'dataZoom')).toEqual(4);
expect(getModel(chart, 'dataZoom', 0).id).toEqual('a');
expect(getModel(chart, 'dataZoom', 1).id).toEqual('b');
// Merge
chart.setOption({
dataZoom: [
{type: 'slider', id: 'c'},
{type: 'slider', name: 'x'}
]
});
expect(countModel(chart, 'dataZoom')).toEqual(5);
expect(getModel(chart, 'dataZoom', 0).id).toEqual('a');
expect(getModel(chart, 'dataZoom', 1).id).toEqual('b');
expect(getModel(chart, 'dataZoom', 4).id).toEqual('c');
});
});
});
| ka215/WP-Gentelella | vendors/echarts/test/ut/spec/model/Global.js | JavaScript | mit | 29,436 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M5 20v2h5v2l3-3-3-3v2zm9 0h5v2h-5zm3-20H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm0 16H7V2h10v14zm-5-9c1.1 0 2-.9 1.99-2 0-1.1-.9-2-2-2S10 3.9 10 5s.89 2 2 2z"
}), 'CameraRearOutlined'); | AlloyTeam/Nuclear | components/icon/esm/camera-rear-outlined.js | JavaScript | mit | 337 |
package gpg
import "context"
type contextKey int
const (
ctxKeyAlwaysTrust contextKey = iota
ctxKeyUseCache
)
// WithAlwaysTrust will return a context with the flag for always trust set.
func WithAlwaysTrust(ctx context.Context, at bool) context.Context {
return context.WithValue(ctx, ctxKeyAlwaysTrust, at)
}
// IsAlwaysTrust will return the value of the always trust flag or the default
// (false).
func IsAlwaysTrust(ctx context.Context) bool {
bv, ok := ctx.Value(ctxKeyAlwaysTrust).(bool)
if !ok {
return false
}
return bv
}
// WithUseCache returns a context with the value of NoCache set.
func WithUseCache(ctx context.Context, nc bool) context.Context {
return context.WithValue(ctx, ctxKeyUseCache, nc)
}
// UseCache returns true if this request should ignore the cache.
func UseCache(ctx context.Context) bool {
nc, ok := ctx.Value(ctxKeyUseCache).(bool)
if !ok {
return false
}
return nc
}
| gopasspw/gopass | internal/backend/crypto/gpg/context.go | GO | mit | 924 |
using System;
using System.Runtime.InteropServices;
using EnvDTE;
namespace ManuelNaujoks.VSChat
{
[Guid("173cbcde-e728-442c-82ee-1c29ae3e00af")]
public class MyToolWindow : SolutionAwareToolWindowPane
{
public MyToolWindow()
{
Caption = Resources.ToolWindowTitle;
BitmapResourceID = 301;
BitmapIndex = 1;
base.Content = new MyControl
{
GetRelativeCodePosition = MakeRelativeCodePosition,
GoToFileAndLine = GoToFileAndLine
};
}
protected override void OnClose()
{
var chat = (MyControl)base.Content;
chat.Closing();
base.OnClose();
}
private void MakeRelativeCodePosition(Action<RelativeCodePosition> callback)
{
try
{
var activeDocument = MasterObjekt.ActiveDocument;
if (activeDocument != null)
{
var selection = (TextSelection)activeDocument.Selection;
if (selection != null)
{
if (RawSolution != null)
{
callback(new RelativeCodePosition(solutionFile: RawSolution.FileName, file: activeDocument.FullName, line: selection.AnchorPoint.Line));
}
}
}
}
catch (Exception)
{
}
}
private void GoToFileAndLine(string shortcut)
{
if (RawSolution != null)
{
var relativeCodePosition = new RelativeCodePosition(solutionFile: RawSolution.FileName, shortcut: shortcut);
MasterObjekt.ItemOperations.OpenFile(relativeCodePosition.File, Constants.vsViewKindTextView);
var activeDocument = MasterObjekt.ActiveDocument;
if (activeDocument != null)
{
var selection = (TextSelection)activeDocument.Selection;
if (selection != null)
{
selection.GotoLine(relativeCodePosition.Line);
}
}
}
}
}
}
| halllo/ManuelsChat | VSChat/MyToolWindow.cs | C# | mit | 1,689 |
'use strict';
/**
* controller for angular-ladda
* An angular directive wrapper for Ladda buttons.
*/
angular.module('core').controller('LaddaCtrl', ["$scope", "$timeout", function ($scope, $timeout) {
$scope.ldloading = {};
$scope.clickBtn = function (style) {
$scope.ldloading[style.replace('-', '_')] = true;
$timeout(function () {
$scope.ldloading[style.replace('-', '_')] = false;
}, 2000);
};
$scope.clickProgressBtn = function (style) {
$scope.ldloading[style.replace('-', '_') + "_progress"] = true;
$timeout(function () {
$scope.ldloading[style.replace('-', '_') + "_progress"] = 0.1;
}, 500);
$timeout(function () {
$scope.ldloading[style.replace('-', '_') + "_progress"] += 0.1;
}, 1000);
$timeout(function () {
$scope.ldloading[style.replace('-', '_') + "_progress"] += 0.1;
}, 1500);
$timeout(function () {
$scope.ldloading[style.replace('-', '_') + "_progress"] = false;
}, 2000);
};
}]); | mchammabc/sites | public/modules/core/controllers/laddaCtrl.js | JavaScript | mit | 1,099 |
from distutils.core import setup, Extension
setup(
name="tentacle_pi.TSL2561",
version="1.0",
packages = ["tentacle_pi"],
ext_modules = [
Extension("tentacle_pi.TSL2561",
sources = ["src/tsl2561.c", "src/tsl2561_ext.c"])
]
)
| lexruee/tsl2561 | setup.py | Python | mit | 237 |
import React, {PureComponent} from "react";
import "./fill-view.css";
export class FillView extends PureComponent {
divRef = null;
state = {
scale: 1.0
};
setDivRef = (ref) => {
this.divRef = ref;
};
componentDidMount() {
const {percentMargin = 6} = this.props;
const adjust = (100 - percentMargin) * 0.01;
const {width: contentWidth, height: contentHeight} = this.divRef.getBoundingClientRect();
const {width: parentWidth, height: parentHeight} = this.divRef.parentNode.parentNode.getBoundingClientRect();
const availableWidth = parentWidth * adjust;
const availableHeight = parentHeight * adjust;
const scale = Math.min(availableWidth / contentWidth, availableHeight / contentHeight);
this.setState(() => ({ scale }));
}
render() {
const {children} = this.props;
const {scale} = this.state;
const contentProps = {
ref: this.setDivRef,
style: {
transform: `scale(${scale})`,
}
};
return (
<div className="fill-view">
<div {...contentProps}>
{children}
</div>
</div>
)
}
}
| dfbaskin/react-higher-order-components | packages/presentation/src/shared/fill-view.js | JavaScript | mit | 1,272 |
<?php header("Content-type: text/html; charset=utf-8");
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Matricula extends CI_Controller {
public function __construct(){
parent::__construct();
if(!isset($_SESSION['login'])) die("Sesion terminada. <a href='". base_url()."'>Registrarse e ingresar.</a> ");
$this->load->model(ventas.'matricula_model');
$this->load->model(ventas.'alumno_model');
$this->load->model(ventas.'actividad_model');
$this->load->model(maestros.'persona_model');
$this->load->model(seguridad.'permiso_model');
$this->load->model(almacen.'curso_model');
$this->load->model(maestros.'ciclo_model');
$this->load->model(maestros.'aula_model');
$this->load->model(maestros.'tipoestudiociclo_model');
$this->load->model(maestros.'local_model');
$this->load->model(ventas.'apertura_model');
$this->load->helper('menu');
$this->configuracion = $this->config->item('conf_pagina');
$this->login = $this->session->userdata('login');
}
public function index()
{
$this->load->view('seguridad/inicio');
}
public function listar($j=0){
$filter = new stdClass();
$filter->rol = $this->session->userdata('rolusu');
$filter->order_by = array("m.MENU_Orden"=>"asc");
$menu = get_menu($filter);
$filter = new stdClass();
//$filter->order_by = array("c.CICLOP_Codigo"=>"desc","e.PERSC_ApellidoPaterno"=>"asc","e.PERSC_ApellidoMaterno"=>"asc");
$filter_not = new stdClass();
$registros = count($this->matricula_model->listar($filter,$filter_not));
$matricula = $this->matricula_model->listar($filter,$filter_not,$this->configuracion['per_page'],$j);
$item = 1;
$lista = array();
if(count($matricula)>0){
foreach($matricula as $indice => $value){
$lista[$indice] = new stdClass();
$lista[$indice]->codigo = $value->ORDENP_Codigo;
$lista[$indice]->nombres = $value->PERSC_Nombre;
$lista[$indice]->paterno = $value->PERSC_ApellidoPaterno;
$lista[$indice]->materno = $value->PERSC_ApellidoMaterno;
$lista[$indice]->tipoestudio = $value->TIPC_Nombre;
$lista[$indice]->ciclo = $value->COMPC_Nombre;
$lista[$indice]->aula = $value->AULAC_Nombre;
$lista[$indice]->estado = $value->ORDENC_FlagEstado;
$lista[$indice]->fechareg = ($value->fechareg);
$lista[$indice]->fecha = date_sql($value->ORDENC_Fecot);
}
}
$configuracion = $this->configuracion;
$configuracion['base_url'] = base_url()."index.php/ventas/orden/listar";
$configuracion['total_rows'] = $registros;
$this->pagination->initialize($configuracion);
/*Enviamos los datos a la vista*/
$data['lista'] = $lista;
$data['menu'] = $menu;
$data['header'] = get_header();
$data['form_open'] = form_open('',array("name"=>"frmPersona","id"=>"frmPersona","onsubmit"=>"return valida_guiain();"));
$data['form_close'] = form_close();
$data['j'] = $j;
$data['registros'] = $registros;
$data['paginacion'] = $this->pagination->create_links();
$this->load->view("ventas/matricula_index",$data);
}
public function editar($accion,$codigo=""){
$ciclo = $this->input->get_post('ciclo');
$local = $this->input->get_post('local');
$aula = $this->input->get_post('aula');
$user_id = $this->input->get_post('user_id');
$nombres = $this->input->get_post('nombres');
$tipoestudiociclo = $this->input->get_post('tipoestudiociclo');
$lista = new stdClass();
if($accion == "e"){
$filter = new stdClass();
$filter->matricula = $codigo;
$orden = $this->matricula_model->obtener($filter);
$lista->nombres = $nombres!=""?$nombres:$orden->firstname." ".$orden->lastname;
$lista->tipoestudiociclo = $tipoestudio!=""?$tipoestudio:$orden->TIPP_Codigo;
$lista->fecha = date_sql($orden->ORDENC_Fecot);
$lista->user_id = $user_id!==""?$user_id:$orden->user_id;
$lista->matricula = $orden->ORDENP_Codigo;
$lista->estado = $orden->ORDENC_FlagEstado;
$lista->ciclo = $ciclo!=""?$ciclo:$orden->CICLOP_Codigo;
$lista->local = $local!=""?$local:$orden->LOCP_Codigo;
$lista->aula = $aula!=""?$aula:$orden->AULAP_Codigo;
$filter = new stdClass();
$filter->ciclo = $ciclo;
$filter->order_by = array("d.PERSC_ApellidoPaterno"=>"asc","d.PERSC_ApellidoMaterno"=>"asc","d.PERSC_Nombre"=>"asc");
$lista->alumnos = $this->alumno_model->listar($filter);
}
elseif($accion == "n"){
$lista->apellidos = "";
$lista->nombres = "";
$lista->tipoestudiociclo = $tipoestudiociclo;
$lista->fecha = date("d/m/Y",time());
$lista->user_id = $user_id;
$lista->matricula = "";
$lista->estado = 1;
$lista->ciclo = $ciclo;
$lista->local = $local;
$lista->aula = $aula;
$filter = new stdClass();
$filter->ciclo = $ciclo;
$filter->order_by = array("d.PERSC_ApellidoPaterno"=>"asc","d.PERSC_ApellidoMaterno"=>"asc","d.PERSC_Nombre"=>"asc");
$lista->alumnos = $this->alumno_model->seleccionar("0",$filter);
}
$arrEstado = array("0"=>"::Seleccione::","1"=>"ACTIVO","2"=>"INACTIVO");
$data['titulo'] = $accion=="e"?"Editar Matricula":"Nueva Matricula";
$data['form_open'] = form_open('',array("name"=>"frmPersona","id"=>"frmPersona"));
$data['form_close'] = form_close();
$data['lista'] = $lista;
$data['accion'] = $accion;
$filter = new stdClass();
$filter->ciclo = $lista->ciclo;
$data['seltipoestudiociclo'] = form_dropdown('tipoestudiociclo',$this->tipoestudiociclo_model->seleccionar('0',$filter),$lista->tipoestudiociclo,"id='tipoestudiociclo' class='comboMedio'");
$filter2 = new stdClass();
$filter2->local = $lista->local;
$filter2->ciclo = $lista->local;
$filter2->tipoestudiociclo = $lista->tipoestudiociclo;
$data['selaula'] = form_dropdown('apertura',$this->apertura_model->seleccionar('0',$filter2),$lista->aula,"id='apertura' class='comboMedio'");
$data['selciclo'] = form_dropdown('ciclo',$this->ciclo_model->seleccionar('0'),$lista->ciclo,"id='ciclo' class='comboMedio'");
$data['sellocal'] = form_dropdown('local',$this->local_model->seleccionar('0'),$lista->local,"id='local' class='comboMedio'");
$data['selestado'] = form_dropdown('estado',$arrEstado,$lista->estado,"id='estado' class='comboMedio'");
$data['selalum_total'] = form_multiselect('alum_total[]',$lista->alumnos,$lista->estado,"id='alum_total' class='comboMultipleGrande'");
$data['selalum_matri'] = form_multiselect('alum_matriculados[]',array(),$lista->estado,"id='alum_matriculados' class='comboMultipleGrande'");
$data['oculto'] = form_hidden(array("accion"=>$accion,"codigo"=>$codigo));
$this->load->view("ventas/matricula_nuevo",$data);
}
public function grabar(){
$accion = $this->input->get_post('accion');
$codigo = $this->input->get_post('codigo');
$data = array(
"CICLOP_Codigo" => $this->input->post('ciclo'),
"CLIP_Codigo" => $this->input->post('alumno'),
"AULAP_Codigo" => $this->input->post('aula'),
"TIPP_Codigo" => $this->input->post('tipoestudio'),
"ORDENC_Fecot" => date_sql_ret($this->input->post('fecha')),
"ORDENC_FlagEstado" => $this->input->post('estado'),
"ORDENC_FechaModificacion" => date("Y-m-d",time())
);
$resultado = false;
$filter = new stdClass();
$filter->cliente = $this->input->post('alumno');
$filter->curso = $this->input->post('curso');
$ordenes = $this->matricula_model->listar($filter);
if($accion == "n"){
if(count($ordenes)==0){
$resultado = true;
$this->matricula_model->insertar($data);
}
}
elseif($accion == "e"){
if(count($ordenes)==0){
$resultado = true;
$this->matricula_model->modificar($codigo,$data);
}
else{
$numero = $ordenes[0]->ORDENP_Codigo;
if($numero==$this->input->post('matricula')){
$resultado = true;
$this->matricula_model->modificar($codigo,$data);
}
}
}
echo json_encode($resultado);
}
public function eliminar(){
$codigo = $this->input->post('codigo');
$filter = new stdClass();
$filter->orden = $codigo;
$actividades = $this->actividad_model->listar($filter);
$resultado = false;
if(count($actividades)==0){
$this->matricula_model->eliminar($codigo);
$resultado = true;
}
echo json_encode($resultado);
}
public function ver($codigo){
$filter = new stdClass();
$filter->orden = $codigo;
$ordenes = $this->matricula_model->obtener($filter);
$codproducto = $ordenes->PROD_Codigo;
$codcliente = $ordenes->CLIP_Codigo;
$filter = new stdClass();
$filter->cliente = $codcliente;
$clientes = $this->alumno_model->obtener($filter);
$filter = new stdClass();
$filter->curso = $codproducto;
$productos = $this->curso_model->obtener($filter);
$this->load->library("fpdf/pdf");
$CI = & get_instance();
$CI->pdf->FPDF('P');
$CI->pdf->AliasNbPages();
$CI->pdf->AddPage();
$CI->pdf->SetTextColor(0,0,0);
$CI->pdf->SetFillColor(216,216,216);
$CI->pdf->SetFont('Arial','B',11);
$CI->pdf->Image('img/puertosaber.jpg',10,8,10);
$CI->pdf->Cell(0,13,"MATRICULA Nro ".$ordenes->ORDENC_Numero,0,1,"C",0);
$CI->pdf->SetFont('Arial','B',7);
$CI->pdf->Cell(120,10, "" ,0,1,"L",0);
$CI->pdf->Cell(90,5, "CURSO : " ,1,0,"L",0);
$CI->pdf->Cell(1,1, "" ,0,0,"L",0);
$CI->pdf->Cell(90,5,$productos->PROD_Nombre,1,1,"L",0);
$CI->pdf->Cell(90,1, "" ,0,1,"L",0);
$CI->pdf->Cell(90,5, "APELLIDOS Y NOMBRES: " ,1,0,"L",0);
$CI->pdf->Cell(1,1, "" ,0,0,"L",0);
$CI->pdf->Cell(90,5,$clientes->PERSC_ApellidoPaterno." ".$clientes->PERSC_ApellidoMaterno.", ".$clientes->PERSC_Nombre,1,1,"L",0);
$CI->pdf->Cell(90,1, "" ,0,1,"L",0);
$CI->pdf->Cell(90,5, "USUARIO: " ,1,0,"L",0);
$CI->pdf->Cell(1,1, "" ,0,0,"L",0);
$CI->pdf->Cell(90,5,$ordenes->ORDENC_Usuario ,1,1,"L",0);
$CI->pdf->Cell(90,1, "" ,0,1,"L",0);
$CI->pdf->Cell(90,5, "CLAVE: " ,1,0,"L",0);
$CI->pdf->Cell(1,1,$ordenes->ORDENC_Password,0,0,"L",0);
$CI->pdf->Cell(90,5, "" ,1,1,"L",0);
$CI->pdf->Cell(90,1, "" ,0,1,"L",0);
$CI->pdf->Cell(90,5, "RESPONSABLE: " ,1,0,"L",0);
$CI->pdf->Cell(1,1, "" ,0,0,"L",0);
$CI->pdf->Cell(90,5, "" ,1,1,"L",0);
$CI->pdf->Cell(90,1, "" ,0,1,"L",0);
$CI->pdf->SetTextColor(0,0,0);
$CI->pdf->SetFillColor(255,255,255);
$CI->pdf->Cell(181,5, "OBSERVACION : " ,0,1,"L",1);
$CI->pdf->Cell(181,5,$ordenes->ORDENC_Observacion,1,1,"L",1);
$CI->pdf->Output();
}
public function buscar($n=""){
$tipo = $this->input->get_post('tipo');
$ot = $this->input->get_post('ot');
$rsocial = $this->input->get_post('rsocial');
$filter = new stdClass();
$filter->anio = date('Y',time());
$filter->tipo = "OT";
$tipoots = $this->tipoot_model->listar($filter);
if($tipo=='') $tipo = isset($tipoots->cod_argumento)?$tipoots->cod_argumento:"";
$fila = "";
$filter = new stdClass();
$filter->tipoot = $tipo;
if($ot!='') $filter->nroot = $ot;
if($rsocial!='') $filter->codcliente = $rsocial;
if($tipo=="04") $filter->estado = "P";
$ots = $this->ot_model->listarg($filter,array('ot.nroOt'=>'asc'));
$tipoOt = form_dropdown('tipo',$this->tipoot_model->seleccionar('',''),$tipo,"id='tipo' class='comboMedio' onchange='busca_tipoOt();'");
if(count($ots)>0){
foreach($ots as $indice=>$value){
$nroot = $value->NroOt;
$site = $value->DirOt;
$codcli = $value->CodCli;
$codot = $value->CodOt;
$finot = $value->FinOt;
$ftermino = $value->FteOt;
$razon_social = $tipo=='04'?$site:$value->razcli;
// quitar esto {
$finot_envia = $tipo=='04'?date("d/m/Y",time()):$value->FinOt;
// }
$fila .= "<tr title='Fecha Termino: ".$ftermino."' id='".$codot."' id2='".$tipo."' id3='".$finot."' onclick='listadoot(this);'>";
$fila .= "<td style='width:10%;' align='center'><p class='listadoot'>".$nroot."</p></td>";
$fila .= "<td style='width:35%;' align='left'><p class='listadoot'>".$site."</p></td>";
$fila .= "<td style='width:12%;' align='left'><p class='listadoot'>".$finot."</p></td>";
$fila .= "<td style='width:12%;' align='left'><p class='listadoot'>".$ftermino."</p></td>";
$fila .= "<td style='width:31%;' align='left'><p class='listadoot'>".$razon_social."</p></td>";
$fila .= "</tr>";
}
}
else{
$fila.="<tr>";
$fila.="<td colspan='3'>NO EXISTEN RESULTADOS</td>";
$fila.="</tr>";
}
$data['ot'] = $ot;
$data['n'] = $n;
$data['fila'] = $fila;
$data['tipoot'] = $tipoOt;
$data['rsocial'] = $rsocial;
$this->load->view(ventas."ot_buscar",$data);
}
// public function obtener_tipOt($tipoOt){
// $this->load->model(maestros.'tipoot_model');
// $tipoOt = $this->tipoot_model->obtener($tipoOt);
// echo json_encode($tipoOt);
// }
public function export_excel($type) {
if($this->session->userdata('data_'.$type)){
$result = $this->session->userdata('data_'.$type);
$arr_columns = array();
switch ($type) {
case 'listar_requisiciones_ot':
$this->reports_model->rpt_general('rpt_'.$type, 'REQUISICIONES POR OT', $result["columns"], $result["rows"],$result["group"]);
break;
case 'listar_control_pesos1':
case 'listar_control_pesos2':
case 'listar_control_pesos3':
case 'listar_control_pesos4':
case 'listar_control_pesos5':
case 'listar_control_pesos':
$arr_export_detalle = array();
$arr_columns[]['STRING'] = 'NRO.OT';
$arr_columns[]['STRING'] = 'NOMBRE';
$arr_columns[]['STRING'] = 'PROYECTO';
$arr_columns[]['STRING'] = 'TIPO PRODUCTO';
$arr_columns[]['DATE'] = 'F.INICIO';
$arr_columns[]['DATE'] = 'F.TERMINO';
$arr_columns[]['NUMERIC'] = 'W.REQUISICION';
$arr_columns[]['NUMERIC'] = 'W.PPTO.';
//$arr_columns[]['NUMERIC'] = 'W.METRADO';
$arr_columns[]['NUMERIC'] = 'W.O.TECNICA';
$arr_columns[]['NUMERIC'] = 'W.GALVANIZADO';
$arr_columns[]['NUMERIC'] = 'W.PRODUCCION';
$arr_columns[]['NUMERIC'] = 'W.ALMACEN';
$arr_group = array();
$this->reports_model->rpt_general('rpt_'.$type,'Control de pesos',$arr_columns,$result["rows"],$arr_group);
break;
case'productos_x_ot':
$arr_export_detalle = array();
$arr_columns[]['STRING'] = 'NRO.OT';
$arr_columns[]['STRING'] = 'T.TORRE';
$arr_columns[]['STRING'] = 'CODIGO';
$arr_columns[]['STRING'] = 'FAMILIA';
$arr_columns[]['STRING'] = 'DESCRIPCION';
$arr_columns[]['NUMERIC'] = 'INGRESO';
$arr_columns[]['NUMERIC'] = 'SALIDA';
$arr_columns[]['NUMERIC'] = 'SALDO';
$arr_columns[]['NUMERIC'] = 'INGRESO';
$arr_columns[]['NUMERIC'] = 'SALIDA';
$arr_columns[]['NUMERIC'] = 'SALDO';
$arr_group = array('E5:G5'=>'CANTIDAD','H5:K5'=>'MONTO');
$arr_group = array();
$this->reports_model->rpt_general('rpt_'.$type,'pRODUCTOS POR OT',$arr_columns,$result["rows"],$arr_group);
break;
}
}else{
echo "<div style='color:rgb(150,150,150);padding:10px;width:560px;height:160px;border:1px solid rgb(210,210,210);'>
No hay datos para exportar
</div>";
}
}
} | ccjuantrujillo/cepreadm | application/controllers/ventas/matricula.php | PHP | mit | 18,373 |
#include "Pch.h"
#include "EngineCore.h"
#include "GetTextDialog.h"
#include "KeyStates.h"
//-----------------------------------------------------------------------------
GetTextDialog* GetTextDialog::self;
//=================================================================================================
GetTextDialog::GetTextDialog(const DialogInfo& info) : DialogBox(info), singleline(true)
{
}
//=================================================================================================
void GetTextDialog::Draw(ControlDrawData* cdd/* =nullptr */)
{
GUI.DrawSpriteFull(tBackground, Color::Alpha(128));
GUI.DrawItem(tDialog, global_pos, size, Color::Alpha(222), 16);
for(int i = 0; i < 2; ++i)
bts[i].Draw();
Rect r = { global_pos.x + 16,global_pos.y + 16,global_pos.x + size.x,global_pos.y + size.y };
GUI.DrawText(GUI.default_font, text, DTF_CENTER, Color::Black, r);
textBox.Draw();
}
//=================================================================================================
void GetTextDialog::Update(float dt)
{
textBox.mouse_focus = focus;
if(Key.Focus() && focus)
{
for(int i = 0; i < 2; ++i)
{
bts[i].mouse_focus = focus;
bts[i].Update(dt);
if(result != -1)
goto got_result;
}
textBox.focus = true;
textBox.Update(dt);
if(textBox.GetText().empty())
bts[1].state = Button::DISABLED;
else if(bts[1].state == Button::DISABLED)
bts[1].state = Button::NONE;
if(result == -1)
{
if(Key.PressedRelease(VK_ESCAPE))
result = BUTTON_CANCEL;
else if(Key.PressedRelease(VK_RETURN))
{
if(!textBox.IsMultiline() || Key.Down(VK_SHIFT))
{
Key.SetState(VK_RETURN, IS_UP);
result = BUTTON_OK;
}
}
}
if(result != -1)
{
got_result:
if(result == BUTTON_OK)
*input = textBox.GetText();
GUI.CloseDialog(this);
if(event)
event(result);
}
}
}
//=================================================================================================
void GetTextDialog::Event(GuiEvent e)
{
if(e == GuiEvent_GainFocus)
{
textBox.focus = true;
textBox.Event(GuiEvent_GainFocus);
}
else if(e == GuiEvent_LostFocus || e == GuiEvent_Close)
{
textBox.focus = false;
textBox.Event(GuiEvent_LostFocus);
}
else if(e == GuiEvent_WindowResize)
{
self->pos = self->global_pos = (GUI.wnd_size - self->size) / 2;
self->bts[0].global_pos = self->bts[0].pos + self->global_pos;
self->bts[1].global_pos = self->bts[1].pos + self->global_pos;
self->textBox.global_pos = self->textBox.pos + self->global_pos;
}
else if(e >= GuiEvent_Custom)
{
if(e == Result_Ok)
result = BUTTON_OK;
else if(e == Result_Cancel)
result = BUTTON_CANCEL;
}
}
//=================================================================================================
GetTextDialog* GetTextDialog::Show(const GetTextDialogParams& params)
{
if(!self)
{
DialogInfo info;
info.event = nullptr;
info.name = "GetTextDialog";
info.parent = nullptr;
info.pause = false;
info.order = ORDER_NORMAL;
info.type = DIALOG_CUSTOM;
self = new GetTextDialog(info);
self->bts.resize(2);
Button& bt1 = self->bts[0],
&bt2 = self->bts[1];
bt1.id = Result_Cancel;
bt1.size = Int2(100, 40);
bt1.parent = self;
bt2.id = Result_Ok;
bt2.size = Int2(100, 40);
bt2.parent = self;
self->textBox.pos = Int2(25, 60);
}
self->Create(params);
GUI.ShowDialog(self);
return self;
}
//=================================================================================================
void GetTextDialog::Create(const GetTextDialogParams& params)
{
Button& bt1 = bts[0],
&bt2 = bts[1];
int lines = params.lines;
if(!params.multiline || params.lines < 1)
lines = 1;
size = Int2(params.width, 180 + lines * 20);
textBox.size = Int2(params.width - 50, 15 + lines * 20);
textBox.SetMultiline(params.multiline);
textBox.limit = params.limit;
textBox.SetText(params.input->c_str());
// ustaw przyciski
bt1.pos = Int2(size.x - 100 - 16, size.y - 40 - 16);
bt2.pos = Int2(16, size.y - 40 - 16);
if(params.custom_names)
{
bt1.text = (params.custom_names[0] ? params.custom_names[0] : GUI.txCancel);
bt2.text = (params.custom_names[1] ? params.custom_names[1] : GUI.txOk);
}
else
{
bt1.text = GUI.txCancel;
bt2.text = GUI.txOk;
}
// ustaw parametry
result = -1;
parent = params.parent;
order = parent ? static_cast<DialogBox*>(parent)->order : ORDER_NORMAL;
event = params.event;
text = params.text;
input = params.input;
// ustaw pozycjê
pos = global_pos = (GUI.wnd_size - size) / 2;
bt1.global_pos = bt1.pos + global_pos;
bt2.global_pos = bt2.pos + global_pos;
textBox.global_pos = textBox.pos + global_pos;
}
| lcs2/carpg | project/source/engine/gui/GetTextDialog.cpp | C++ | mit | 4,677 |
import * as React from 'react';
import {SvgIconProps} from '../../SvgIcon';
export default function SpeakerNotes(props: SvgIconProps): React.ReactElement<SvgIconProps>;
| mattiamanzati/typings-material-ui | svg-icons/action/speaker-notes.d.ts | TypeScript | mit | 170 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::RecoveryServicesBackup::Mgmt::V2019_05_13
module Models
#
# Yearly retention schedule.
#
class YearlyRetentionSchedule
include MsRestAzure
# @return [RetentionScheduleFormat] Retention schedule format for yearly
# retention policy. Possible values include: 'Invalid', 'Daily', 'Weekly'
attr_accessor :retention_schedule_format_type
# @return [Array<MonthOfYear>] List of months of year of yearly retention
# policy.
attr_accessor :months_of_year
# @return [DailyRetentionFormat] Daily retention format for yearly
# retention policy.
attr_accessor :retention_schedule_daily
# @return [WeeklyRetentionFormat] Weekly retention format for yearly
# retention policy.
attr_accessor :retention_schedule_weekly
# @return [Array<DateTime>] Retention times of retention policy.
attr_accessor :retention_times
# @return [RetentionDuration] Retention duration of retention Policy.
attr_accessor :retention_duration
#
# Mapper for YearlyRetentionSchedule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'YearlyRetentionSchedule',
type: {
name: 'Composite',
class_name: 'YearlyRetentionSchedule',
model_properties: {
retention_schedule_format_type: {
client_side_validation: true,
required: false,
serialized_name: 'retentionScheduleFormatType',
type: {
name: 'String'
}
},
months_of_year: {
client_side_validation: true,
required: false,
serialized_name: 'monthsOfYear',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'MonthOfYearElementType',
type: {
name: 'Enum',
module: 'MonthOfYear'
}
}
}
},
retention_schedule_daily: {
client_side_validation: true,
required: false,
serialized_name: 'retentionScheduleDaily',
type: {
name: 'Composite',
class_name: 'DailyRetentionFormat'
}
},
retention_schedule_weekly: {
client_side_validation: true,
required: false,
serialized_name: 'retentionScheduleWeekly',
type: {
name: 'Composite',
class_name: 'WeeklyRetentionFormat'
}
},
retention_times: {
client_side_validation: true,
required: false,
serialized_name: 'retentionTimes',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'DateTimeElementType',
type: {
name: 'DateTime'
}
}
}
},
retention_duration: {
client_side_validation: true,
required: false,
serialized_name: 'retentionDuration',
type: {
name: 'Composite',
class_name: 'RetentionDuration'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_recovery_services_backup/lib/2019-05-13/generated/azure_mgmt_recovery_services_backup/models/yearly_retention_schedule.rb | Ruby | mit | 4,112 |
<?php
/**
* Created by PhpStorm.
* User: lenovo
* Date: 02/08/2016
* Time: 16.37
*/
class News_m extends CI_Model{
function m_get_news($limit=null,$offset=null){
if($limit!==null && $offset !== null){
$this->db->limit($limit,$offset);
}
if(isset($_GET["id"]))
{
return $this->db->order_by("date_created","desc")
->where("news_category_id", $_GET["id"])
->get("sc_news")
->result_array();
}
return $this->db->order_by("date_created","desc")
->get("sc_news")
->result_array();
}
function m_get_news_by_id($news_id){
return $this->db->where("news_id",$news_id)
->get("sc_news")->row_array();
}
function m_get_detail($id)
{
return $this->db->where("news_id", $id)
->from("sc_news")
->join("sc_news_category", "sc_news.news_category_id = sc_news_category.news_category_id")
->get()->row_array();
}
function m_get_category()
{
return $this->db->get("sc_news_category")->result_array();
}
}
//asdn | Calvinn097/servermedan | application/models/MAIN/News_m.php | PHP | mit | 1,108 |
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("ExtractEmails")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExtractEmails")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("06f60f4e-3cf1-432e-b0e8-edf4c7631b37")]
// 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")]
| zdzdz/CSharp-Part-2-Homeworks | 06. Strings-And-Text-Processing-HW/ExtractEmails/Properties/AssemblyInfo.cs | C# | mit | 1,402 |
from flask import Flask, jsonify, request, redirect, url_for
import subprocess
import os
import json
from cross_domain import *
app = Flask(__name__)
ALLOWED_EXTENSIONS = set(['mol', 'smi'])
try:
TARGET = os.environ['TARGET']
except Exception:
print 'export TARGET=<path to data>'
exit(1)
try:
AlGDock = os.environ['AlGDock_Pref']
except Exception:
print 'export AlGDock_Pref=<path to BindingPMF_arguments.py>'
exit(1)
import sys
sys.path.insert(0, AlGDock)
from BindingPMF_arguments import *
#File system functions
@app.route('/api/v1.0/proteins', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_protein_names():
proteins = os.walk(TARGET).next()[1]
protein_lst = [{"filename": protein} for protein in sorted(proteins) if protein != "scripts"]
return jsonify({"files": protein_lst})
@app.route('/api/v1.0/ligands/<protein>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_ligand_names(protein):
ligands = os.walk(os.path.join(TARGET, protein, "ligand")).next()[2]
ligand_lst = [{"filename": ligand} for ligand in sorted(ligands) if ".ism" in ligand]
return jsonify({"files": ligand_lst})
@app.route('/api/v1.0/ligandSelection/<protein>/<library>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_ligand_selections(protein, library):
trimmed_library = library.split(".ism")[0] + ".A__"
try:
ligand_selections = sorted(os.walk(os.path.join(TARGET, protein, "AlGDock/cool", trimmed_library)).next()[1])
except Exception:
ligand_selections = None
return jsonify({"ligandSelections": ligand_selections})
@app.route('/api/v1.0/ligandLine/<protein>/<library>/<lineNumber>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_ligand_line(protein, library, lineNumber):
try:
path = os.path.join(TARGET, protein, "ligand", library)
library_f = open(path, 'r')
for i, line in enumerate(library_f):
if i == int(lineNumber) - 1:
return line.split()[0]
library_f.close()
except Exception:
return None
@app.route('/api/v1.0/addToLibrary/<protein>/', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def add_to_library(protein):
fileJson = request.get_json()
libraryName = fileJson["libraryName"]
smiles = fileJson["smiles"]
path = os.path.join(TARGET, protein, "ligand", libraryName)
library_f = open(path, 'a')
library_f.write(smiles)
library_f.write("\n")
library_f.close()
return "Added ligand to library."
#Gets for preference dropdowns
@app.route('/api/v1.0/protocols', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_protocols():
choices = arguments['protocol']['choices']
choice_lst = [{"choice": choice} for choice in choices]
return jsonify({"protocol": choice_lst})
@app.route('/api/v1.0/samplers', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_samplers():
choices = arguments['sampler']['choices']
choice_lst = [{"choice": choice} for choice in choices]
return jsonify({"sampler": choice_lst})
@app.route('/api/v1.0/sites', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_sites():
choices = arguments['site']['choices']
choice_lst = [{"choice": choice} for choice in choices]
return jsonify({"site": choice_lst})
@app.route('/api/v1.0/phases', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_phases():
choices = allowed_phases
choice_lst = [{"choice": choice} for choice in choices]
return jsonify({"phase": choice_lst})
@app.route('/api/v1.0/runtypes', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_runtype():
choices = arguments['run_type']['choices']
choice_lst = [{"choice": choice} for choice in choices]
return jsonify({"runtype": choice_lst})
#Saving preferences file
@app.route('/api/v1.0/run/<protein>/<protocol>/<runtype>/<cthermspeed>/<dthermspeed>/<sampler>/<mcmc>/<seedsperstate>/<stepsperseed>/<sweepspercycle>/<attemptspersweep>/<stepspersweep>/<crepxcycles>/<drepxcycles>/<site>/<sxcenter>/<sycenter>/<szcenter>/<sradius>/<sdensity>/<phase>/<cores>/<score>/<from_reps>/<to_reps>/<rmsd>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def save_preferences(protein, protocol, runtype, cthermspeed, dthermspeed, sampler, mcmc, seedsperstate, stepsperseed, sweepspercycle, attemptspersweep, stepspersweep, crepxcycles, drepxcycles, site, sxcenter, sycenter, szcenter, sradius, sdensity, phase, cores, score, from_reps, to_reps, rmsd):
rmsd_n = " "
score_n = " "
if rmsd == "false":
rmsd_n = "#"
if score == "Score" or score == "None":
score_n = "#"
args = ["./create_saved_args.sh", runtype, protocol, cthermspeed, dthermspeed, sampler, mcmc, seedsperstate, stepsperseed, sweepspercycle, attemptspersweep, stepspersweep, crepxcycles, drepxcycles, site, sxcenter, sycenter, szcenter, sradius, sdensity, phase, cores, score, from_reps, to_reps, rmsd, score_n, rmsd_n]
p = subprocess.Popen(args, stdout=subprocess.PIPE)
f = open(os.path.join(TARGET, protein, "AlGDock/saved_arguments.py"), 'w')
f.write(p.stdout.read())
f.close()
return "Preferences File Saved"
#Run button
@app.route('/api/v1.0/run/<protein>/<ligand>/<email>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def run(protein, ligand, email):
run_string = "python " + os.path.join(AlGDock, "../Pipeline/run_anchor_and_grow.py") + " --max_jobs 20 --email " + email + " --ligand " + os.path.join(TARGET, protein, "ligand/dock_in", ligand.split(".ism")[0] + ".A__")
os.chdir(os.path.join(TARGET, protein, "dock6"))
print run_string
os.system(run_string)
return "Job Sent to Cluster"
#Prepare ligands button
@app.route('/api/v1.0/prepLigandLibrary/<protein>/<ligand>/<email>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def prepareLigandLibrary(protein, ligand, email):
run_string = "python " + os.path.join(AlGDock, "../Pipeline/run_prep_ligand_for_dock.py") + " " + ligand + " --email " + email
os.chdir(os.path.join(TARGET, protein, "ligand"))
print run_string
os.system(run_string)
return "Ligand is being prepared."
if __name__ == '__main__':
app.run(debug=True)
| gkumar7/AlGDock | gui/api/REST.py | Python | mit | 6,256 |
const crypto = require('crypto');
const passwordHashAlgorithm = 'sha1';
module.exports = function(client) {
var computeSHA1 = function(str) { return crypto.createHash(passwordHashAlgorithm).update(str).digest('hex'); };
var user = {
addUser: function(email, password, callback) {
client.incr('global:userId', function(error, id) {
if(error) {
callback(false);
return;
};
id --;
console.log('Dodaje user z id ' + id);
client.setnx('user:' + email + ':id', id, function(error, set) {
if (error) {
console.log('Error ' + error);
callback(false);
return;
};
console.log('Set ' + set);
if (set == 0) {
callback(false, 'User ' + email + ' is registred');
return;
};
client
.multi()
.set('user:'+id+':email', email)
.set('user:' + id + ':password', computeSHA1(password))
.exec(function(error, results) {
if (error) {
callback(false);
return;
};
callback(true);
return;
});
});
});
},
getUserWithEmail: function(email, callback) {
client.get('user:' + email.toLowerCase() + ':id', function(error,id) {
if(error) {
callback(null);
return;
}
if (id == null) {
callback(null);
return;
}
user.getUserWithId(id, callback);
});
},
getUserWithId: function(id, callback) {
client
.multi()
.get('user:' + id + ':email')
.exec(function(error, results) {
if (error) {
callback(null);
return;
}
callback({
id: id,
email: results[0]
});
});
},
validateUser: function(email, password, callback) {
user.getUserWithEmail(email, function(user) {
if(user == null) {
callback(false);
return;
}
client.get('user:' + user.id + ':password', function(error, passwordF) {
if(error) {
callback(false);
return;
}
callback(computeSHA1(password) == passwordF);
});
});
},
};
return user;
};
//
//user.addUser('test2@o2.pl', 'test', function(result, msg) {
// if(result) {
// console.log('jest ok');
// } else {
// console.log('Error: ' + msg);
// }
//});
//
//user.validateUser('test3@o2.pl', 'test', function(result) {
// console.log('Validate: ' + result);
//});
// client.set("string key", "string val", redis.print);
// client.hset("hash key", "hashtest 1", "some value", redis.print);
// client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
// client.hkeys("hash key", function (err, replies) {
// console.log(replies.length + " replies:");
// replies.forEach(function (reply, i) {
// console.log(" " + i + ": " + reply);
// });
// client.quit();
// }); | yoman07/GeoChatServer | db.js | JavaScript | mit | 3,170 |
const { validateLocaleId } = require("..");
describe("validateLocaleId", () => {
it("validateLocaleId", () => {
validateLocaleId("en").should.eql(true);
validateLocaleId(null).should.eql(true);
});
}); | node-opcua/node-opcua | packages/node-opcua-basic-types/test/test_locale_id.js | JavaScript | mit | 227 |
var Q = require('q');
/*
**
@param [object | array] object: is the object that needs to be iterated, can be an Object or an array
@param [integer] index: is the index of argument obtained from the object element and to be added to asyncFunc arguments, starting from 1
@param [function] asyncFunc: is the asynchronous function that needs to be called at every iteration.
**
*/
var iterate = function(object, index, asyncFunc /* 1...n args */){
var item = null;
var args = Array.prototype.slice.call(arguments, 3);
if(Object.prototype.toString.call(object) === "[object Array]"){
asyncIterateArray(object, 0, asyncFunc, args, index);
}else if(Object.prototype.toString.call(object) === "[object Object]"){
asyncIterateObjectKeys(object, 0, asyncFunc, args, index);
}
}
function asyncIterateObjectKeys(object, i, func, args, index){
var keys = Object.keys(object);
if( i < keys.length){
var tmpargs = args.slice();
tmpargs.splice(index - 1, 0, object[keys[i]]);
Q.fcall(asyncRun, func, tmpargs)
.then(function() {
asyncIterateObjectKeys(object, i = i+ 1, func, args, index);
})
.catch(function(err){
console.log(err);
});
}
}
function asyncIterateArray(object, i, func, args, index){
if(i < object.length){
var tmpargs = args.slice();
tmpargs.splice(index - 1, 0, object[i]);
Q.fcall(asyncRun, func, tmpargs)
.then(function() {
asyncIterateArray(object, i = i+ 1, func, args, index);
})
.catch(function(err){
console.log(err);
});
}
}
function asyncRun(asyncFunc, args){
var def = Q.defer();
Q.fcall(function(){
return asyncFunc.apply(this, args)
})
.then(function(ret){
def.resolve(ret);
})
.catch(function(err){
def.reject(err);
});
return def.promise;
}
module.exports = iterate;
| m-arch/for-async | index.js | JavaScript | mit | 1,825 |
package name.reidmiller.iesoreports.client;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ca.ieso.reports.schema.nislshadowprices.DocBody;
import ca.ieso.reports.schema.nislshadowprices.DocHeader;
import ca.ieso.reports.schema.nislshadowprices.Document;
public class NetInterchangeSchedulingLimitClient extends DailyReportClient {
private Logger logger = LogManager.getLogger(this.getClass());
public NetInterchangeSchedulingLimitClient(String defaultUrlString, String jaxb2ContextPath) {
super.setDefaultUrlString(defaultUrlString);
super.setJaxb2ContextPath(jaxb2ContextPath);
}
/**
* Unmarshals XML text from {@link #getDefaultUrlString()} into a
* {@link Document} using JAXB2. This method is a wrapper around
* {@link #getDocument(String)}.
*
* @return {@link Document}
* @throws MalformedURLException
* @throws IOException
*
*/
public Document getDefaultDocument() throws MalformedURLException,
IOException, ClassCastException {
return this.getDocument(super.getDefaultUrlString());
}
/**
* This method uses {@link #getDefaultUrlString()} to request the current
* (default) {@link DocBody}.
*
* @return {@link DocBody} for the current (default) report.
* @throws MalformedURLException
*
* @throws IOException
*/
public DocBody getDefaultDocBody() throws MalformedURLException,
IOException {
Document document = this.getDefaultDocument();
return this.getDocBody(document);
}
/**
* This method uses {@link #getDefaultUrlString()} to request the current
* (default) {@link DocHeader}.
*
* @return {@link DocHeader} for the current (default) report.
* @throws MalformedURLException
* @throws IOException
*/
public DocHeader getDefaultDocHeader() throws MalformedURLException,
IOException {
Document document = this.getDefaultDocument();
return this.getDocHeader(document);
}
/**
* Returns only the {@link DocBody} portion of the {@link Document}.
*
* @param document
* {@link Document} comprised of two parts: {@link DocHeader} and
* {@link DocBody}.
* @return {@link DocBody}
*/
public DocBody getDocBody(Document document) {
List<Object> docHeaderAndDocBody = document.getDocHeaderAndDocBody();
return super.getDocPart(docHeaderAndDocBody, DocBody.class);
}
/**
* Get a {@link DocBody} for a date in past.
*
* @param historyDate
* Date in the past that a report is being requested for.
* @return Returns the {@link DocBody} of a past report.
* @throws MalformedURLException
* @throws IOException
*/
public DocBody getDocBodyForDate(Date historyDate)
throws MalformedURLException, IOException {
Document document = super.getDocumentForDate(historyDate,
Document.class);
return this.getDocBody(document);
}
/**
* Makes a request for each Date in the provided range (inclusive) building
* out a {@link List} of {@link DocBody} objects.
*
* @param startDate
* Start point (inclusive) of the date range (ie. date furthest
* in the past).
* @param endDate
* End point (inclusive) of the date range (ie. date closest to
* present).
* @return If the startDate is in the future, a one-item {@link List} of
* {@link DocBody} Objects will be returned. If endDate is in the
* future the {@link List} will stop at the current (default)
* report.
* @throws MalformedURLException
* @throws IOException
*/
public List<DocBody> getDocBodiesInDateRange(Date startDate, Date endDate)
throws MalformedURLException, IOException {
List<DocBody> docBodies = new ArrayList<DocBody>();
List<Document> documents = super.getDocumentsInDateRange(startDate,
endDate, Document.class);
for (Document document : documents) {
docBodies.add(this.getDocBody(document));
}
return docBodies;
}
/**
* Returns only the {@link DocHeader} portion of the {@link Document}.
*
* @param document
* {@link Document} comprised of two parts: {@link DocHeader} and
* {@link DocBody}.
*
* @return {@link DocHeader}
*/
public DocHeader getDocHeader(Document document) {
List<Object> docHeaderAndDocBody = document.getDocHeaderAndDocBody();
return super.getDocPart(docHeaderAndDocBody, DocHeader.class);
}
/**
* Get a {@link DocHeader} for a date in past.
*
* @param historyDate
* Date in the past that a report header is being requested for.
* @return Returns the {@link DocHeader} of a past report.
* @throws MalformedURLException
*
* @throws IOException
*/
public DocHeader getDocHeaderForDate(Date historyDate)
throws MalformedURLException, IOException {
Document document = super.getDocumentForDate(historyDate,
Document.class);
return this.getDocHeader(document);
}
/**
* Makes a request for each Date in the provided range (inclusive) building
* out a {@link List} of {@link DocHeader} Objects.
*
* @param startDate
* Start point (inclusive) of the date range (ie. date furthest
* in the past).
* @param endDate
* End point (inclusive) of the date range (ie. date closest to
* present).
* @return If the startDate is in the future, a one-item {@link List} of
* {@link DocHeader} Objects will be returned. If endDate is in the
* future the {@link List} will stop at the current (default)
* report.
* @throws MalformedURLException
* @throws IOException
*/
public List<DocHeader> getDocHeadersInDateRange(Date startDate, Date endDate)
throws MalformedURLException, IOException {
List<DocHeader> docHeaders = new ArrayList<DocHeader>();
List<Document> documents = super.getDocumentsInDateRange(startDate,
endDate, Document.class);
for (Document document : documents) {
docHeaders.add(this.getDocHeader(document));
}
return docHeaders;
}
/**
* Unmarshals XML text into a {@link Document} using JAXB2, into the package
* name specified by {@link #getJaxb2ContextPath()}.
*
* @param urlString
* The URL that will be unmarshalled into a {@link Document}.
* @return {@link Document}
* @throws MalformedURLException
* @throws IOException
*
*/
private Document getDocument(String urlString)
throws MalformedURLException, IOException {
return super.getDocument(urlString, Document.class);
}
}
| r24mille/IesoPublicReportBindings | src/main/java/name/reidmiller/iesoreports/client/NetInterchangeSchedulingLimitClient.java | Java | mit | 6,803 |
# -*- encoding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014-2015 Haltu Oy, http://haltu.fi
#
# 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
# AUTHORS OR COPYRIGHT HOLDERS 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.
import csv
import codecs
from optparse import make_option
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from authdata.models import User, Role, Attribute, UserAttribute, Municipality, School, Attendance, Source
class Command(BaseCommand):
help = """Imports data from CSV file to the database.
Do not put any header to the CSV file. Only provide data separated by commas and quoted with \".
You need to provide at least two arguments: the name of the input file and list of attributes for the User.
For example: manage.py csv_import file.csv dreamschool,facebook,twitter,linkedin,mepin
"""
args = '<csvfile> <attr1,attr2...>'
option_list = BaseCommand.option_list + (
make_option('--source',
action='store',
dest='source',
default='manual',
help='Source value for this run'),
make_option('--municipality',
action='store',
dest='municipality',
default='-',
help='Source value for this run'),
make_option('--run',
action='store_true',
dest='really_do_this',
default=False,
help='Really run the command'),
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='Verbose'),
)
def handle(self, *args, **options):
if len(args) != 2:
raise CommandError('Wrong parameters, try reading --help')
self.verbose = options['verbose']
self.municipality = options['municipality']
# Create needed Attribute objects to the database
# These are the attributes which can be used to query for User objects in the API
# attribute names are defined in the commandline as the second parameter
# for example: manage.py csv_import file.csv dreamschool,facebook,twitter,linkedin,mepin
self.attribute_names = OrderedDict()
for key in args[1].split(','):
self.attribute_names[key], _ = Attribute.objects.get_or_create(name=key)
self.source, _ = Source.objects.get_or_create(name=options['source'])
# If you need more roles, add them here
self.role_names = OrderedDict()
for r in ['teacher', 'student']:
self.role_names[r], _ = Role.objects.get_or_create(name=r)
csv_data = csv.reader(codecs.open(args[0], 'rb'), delimiter=',', quotechar='"')
for r in csv_data:
# These are the fixed fields for the User. These are returned from the API.
data = {
'username': r[0], # OID
'school': r[1], # School
'group': r[2], # Class
'role': r[3], # Role
'first_name': r[4], # First name
'last_name': r[5], # Last name
}
# This is not mandatory, but it would be nice. Can be changed to error by terminating the script here.
if data['role'] not in self.role_names.keys():
print 'WARNING, role not in:', repr(self.role_names.keys())
attributes = {}
i = 6 # Next csv_data row index is 6 :)
for a in self.attribute_names:
attributes[a] = r[i]
i = i + 1
try:
if self.verbose:
print repr(data)
print repr(attributes)
if options['really_do_this']:
self.really_do_this(data.copy(), attributes.copy())
except IntegrityError, e:
print "ERR IE", e
print repr(data)
print repr(attributes)
except ObjectDoesNotExist, e:
print "ERR ODN", e
print repr(data)
print repr(attributes)
def really_do_this(self, d, a):
# Create User
# User is identified from username and other fields are updated
user, _ = User.objects.get_or_create(username=d['username'])
user.first_name = d['first_name']
user.last_name = d['last_name']
user.save()
# Assign attributes for User
# There can be multiple attributes with the same name and different value.
# This is one of the reasons we have the source parameter to tell where the data came from.
for k, v in a.iteritems():
UserAttribute.objects.get_or_create(user=user, attribute=self.attribute_names[k], value=v, source=self.source)
# Create Municipality
# If you leave this empty on the CLI it will default to '-'
municipality, _ = Municipality.objects.get_or_create(name=self.municipality)
# Create School
# School data is not updated after it is created. Data can be then changed in the admin.
school, _ = School.objects.get_or_create(school_id=d['school'], defaults={'municipality': municipality, 'name': d['school']})
# Create Attendance object for User. There can be more than one Attendance per User.
Attendance.objects.get_or_create(user=user, school=school, role=self.role_names[d['role']], group=d['group'], source=self.source)
# vim: tabstop=2 expandtab shiftwidth=2 softtabstop=2
| educloudalliance/eca-auth-data | authdata/management/commands/csv_import.py | Python | mit | 6,066 |
package br.ifcibirama.dell_pc.javaisfun;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Objetos2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_objetos2);
setTitle("Orientação à Objetos");
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition( R.anim.rigth_in, R.anim.rigth_out);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_go_back_red, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_go:
Intent intent = new Intent(this, Objetos3.class);
startActivity(intent);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finishAffinity();
return true;
case R.id.menu_home:
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setTitle("Home")
.setMessage("Você tem certeza que quer voltar ao menu principal?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Objetos2.this, MainActivity.class);
startActivity(intent);
finishAffinity();
overridePendingTransition( R.anim.rigth_in, R.anim.rigth_out);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(R.drawable.warning)
.show();
return true;
case R.id.menu_back:
Intent intent2 = new Intent(this, Objetos.class);
startActivity(intent2);
overridePendingTransition(R.anim.rigth_in, R.anim.rigth_out);
finishAffinity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| jvbeltra/JavaIsFun | app/src/main/java/br/ifcibirama/dell_pc/javaisfun/Objetos2.java | Java | mit | 2,904 |
package ru.otus.java_2017_04.golovnin.hw11.Cache;
public interface CacheEngine<K, V> {
void put(K key, V element);
V get(K key);
int getHitCount();
int getMissCount();
void dispose();
}
| vladimir-golovnin/otus-java-2017-04-golovnin | hw11/src/main/java/ru/otus/java_2017_04/golovnin/hw11/Cache/CacheEngine.java | Java | mit | 207 |
# こっちのURLで放送予定の番組情報取得できるけど視聴者数ないので使わない
# http://live.nicovideo.jp/rss
require File.expand_path('./lib/readers/channel_list_reader')
class NicoOfficialReader < ChannelListReader
def read_rows
@doc.css('#rank .active .detail')
end
def read_channel_name(row)
row.css('p a').text.slice(0, 10)
end
def read_contact_url(row)
'http://live.nicovideo.jp/' << row.css('p a')[0][:href]
end
def read_genre(row)
'【ニコ生公式】'
end
def read_detail(row)
row.css('p a').text
end
# 10分あたりの平均コメ数を返す
def read_listener_count(row)
hour, min = read_elapsed_hour_and_min(row)
elapsed_minutes = (hour.to_i * 60) + min.to_i
comment_count = row.css('.count .coment').text.gsub!(/\s|,/, '').to_i
(comment_count / (elapsed_minutes / 10)).to_i
rescue ZeroDivisionError
0
end
def read_relay_count(row)
row.css('.count .audience').text.gsub!(/\s|,/, '').to_i
end
def read_time(row)
hour, min = read_elapsed_hour_and_min(row)
sprintf('%02d', hour) + ':' + sprintf('%02d', min)
end
def read_elapsed_hour_and_min(row)
unless @hour && @min
time = row.css('.time').text
if time.include?('時間')
time = time.split('時間')
@hour = time[0]
@min = time[1].sub('分', '')
else
@hour = '00'
@min = time.sub('分', '')
end
end
return @hour, @min
end
end
| masu-kawa/nyp | lib/readers/nico_official_reader.rb | Ruby | mit | 1,554 |
'use strict';
var kraken = require('kraken-js'),
app = require('express')(),
options = require('./lib/spec')(app),
port = process.env.PORT || 8000;
app.use(kraken(options));
app.listen(port, function(err) {
console.log('[%s] Listening on http://localhost:%d', app.settings.env, port);
});
| NaveenAttri/TestProject | index.js | JavaScript | mit | 310 |
<?php
return array (
'id' => 'kddi_sn3q_ver1',
'fallback' => 'kddi_sn3p_ver1',
'capabilities' =>
array (
'model_name' => 'S005',
'release_date' => '2010_november',
'max_image_width' => '234',
'resolution_height' => '854',
'resolution_width' => '480',
'max_image_height' => '375',
'flash_lite_version' => '3_0',
),
);
| cuckata23/wurfl-data | data/kddi_sn3q_ver1.php | PHP | mit | 356 |
<?php
namespace daVerona\Texting\Contracts;
interface TextingRequest
{
public function getSender();
public function getReceiver();
}
| daverona/texting | src/Contracts/TextingRequest.php | PHP | mit | 148 |
/* global __phantom_writeFile */
(function(global) {
var UNDEFINED,
exportObject;
if (typeof module !== "undefined" && module.exports) {
exportObject = exports;
} else {
exportObject = global.jasmineReporters = global.jasmineReporters || {};
}
function trim(str) { return str.replace(/^\s+/, "" ).replace(/\s+$/, "" ); }
function elapsed(start, end) { return (end - start)/1000; }
function isFailed(obj) { return obj.status === "failed"; }
function isSkipped(obj) { return obj.status === "pending"; }
function isDisabled(obj) { return obj.status === "disabled"; }
function pad(n) { return n < 10 ? '0'+n : n; }
function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe`
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
dupe[prop] = obj[prop];
}
}
return dupe;
}
function ISODateString(d) {
return d.getFullYear() + '-' +
pad(d.getMonth()+1) + '-' +
pad(d.getDate()) + 'T' +
pad(d.getHours()) + ':' +
pad(d.getMinutes()) + ':' +
pad(d.getSeconds());
}
function escapeInvalidXmlChars(str) {
return str.replace(/</g, "<")
.replace(/\>/g, ">")
.replace(/\"/g, """)
.replace(/\'/g, "'")
.replace(/\&/g, "&");
}
function getQualifiedFilename(path, filename, separator) {
if (path && path.substr(-1) !== separator && filename.substr(0) !== separator) {
path += separator;
}
return path + filename;
}
function log(str) {
var con = global.console || console;
if (con && con.log) {
con.log(str);
}
}
/**
* Generates JUnit XML for the given spec run. There are various options
* to control where the results are written, and the default values are
* set to create as few .xml files as possible. It is possible to save a
* single XML file, or an XML file for each top-level `describe`, or an
* XML file for each `describe` regardless of nesting.
*
* Usage:
*
* jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter(options);
*
* @param {object} [options]
* @param {string} [savePath] directory to save the files (default: '')
* @param {boolean} [consolidateAll] whether to save all test results in a
* single file (default: true)
* NOTE: if true, {filePrefix} is treated as the full filename (excluding
* extension)
* @param {boolean} [consolidate] whether to save nested describes within the
* same file as their parent (default: true)
* NOTE: true does nothing if consolidateAll is also true.
* NOTE: false also sets consolidateAll to false.
* @param {boolean} [useDotNotation] whether to separate suite names with
* dots instead of spaces, ie "Class.init" not "Class init" (default: true)
* @param {string} [filePrefix] is the string value that is prepended to the
* xml output file (default: junitresults-)
* NOTE: if consolidateAll is true, the default is simply "junitresults" and
* this becomes the actual filename, ie "junitresults.xml"
*/
exportObject.JUnitXmlReporter = function(options) {
var self = this;
self.started = false;
self.finished = false;
// sanitize arguments
options = options || {};
self.savePath = options.savePath || '';
self.consolidate = options.consolidate === UNDEFINED ? true : options.consolidate;
self.consolidateAll = self.consolidate !== false && (options.consolidateAll === UNDEFINED ? true : options.consolidateAll);
self.useDotNotation = options.useDotNotation === UNDEFINED ? true : options.useDotNotation;
self.filePrefix = options.filePrefix || (self.consolidateAll ? 'junitresults' : 'junitresults-');
var suites = [],
currentSuite = null,
totalSpecsExecuted = 0,
totalSpecsDefined,
// when use use fit, jasmine never calls suiteStarted / suiteDone, so make a fake one to use
fakeFocusedSuite = {
id: 'focused',
description: 'focused specs',
fullName: 'focused specs'
};
var __suites = {}, __specs = {};
function getSuite(suite) {
__suites[suite.id] = extend(__suites[suite.id] || {}, suite);
return __suites[suite.id];
}
function getSpec(spec) {
__specs[spec.id] = extend(__specs[spec.id] || {}, spec);
return __specs[spec.id];
}
self.jasmineStarted = function(summary) {
totalSpecsDefined = summary && summary.totalSpecsDefined || NaN;
exportObject.startTime = new Date();
self.started = true;
};
self.suiteStarted = function(suite) {
suite = getSuite(suite);
suite._startTime = new Date();
suite._specs = [];
suite._suites = [];
suite._failures = 0;
suite._skipped = 0;
suite._disabled = 0;
suite._parent = currentSuite;
if (!currentSuite) {
suites.push(suite);
} else {
currentSuite._suites.push(suite);
}
currentSuite = suite;
};
self.specStarted = function(spec) {
if (!currentSuite) {
// focused spec (fit) -- suiteStarted was never called
self.suiteStarted(fakeFocusedSuite);
}
spec = getSpec(spec);
spec._startTime = new Date();
spec._suite = currentSuite;
currentSuite._specs.push(spec);
};
self.specDone = function(spec) {
spec = getSpec(spec);
spec._endTime = new Date();
if (isSkipped(spec)) { spec._suite._skipped++; }
if (isDisabled(spec)) { spec._suite._disabled++; }
if (isFailed(spec)) { spec._suite._failures++; }
totalSpecsExecuted++;
};
self.suiteDone = function(suite) {
suite = getSuite(suite);
if (suite._parent === UNDEFINED) {
// disabled suite (xdescribe) -- suiteStarted was never called
self.suiteStarted(suite);
}
suite._endTime = new Date();
currentSuite = suite._parent;
};
self.jasmineDone = function() {
if (currentSuite) {
// focused spec (fit) -- suiteDone was never called
self.suiteDone(fakeFocusedSuite);
}
var output = '';
for (var i = 0; i < suites.length; i++) {
output += self.getOrWriteNestedOutput(suites[i]);
}
// if we have anything to write here, write out the consolidated file
if (output) {
wrapOutputAndWriteFile(self.filePrefix, output);
}
//log("Specs skipped but not reported (entire suite skipped or targeted to specific specs)", totalSpecsDefined - totalSpecsExecuted + totalSpecsDisabled);
self.finished = true;
// this is so phantomjs-testrunner.js can tell if we're done executing
exportObject.endTime = new Date();
};
self.getOrWriteNestedOutput = function(suite) {
var output = suiteAsXml(suite);
for (var i = 0; i < suite._suites.length; i++) {
output += self.getOrWriteNestedOutput(suite._suites[i]);
}
if (self.consolidateAll || self.consolidate && suite._parent) {
return output;
} else {
// if we aren't supposed to consolidate output, just write it now
wrapOutputAndWriteFile(generateFilename(suite), output);
return '';
}
};
self.writeFile = function(filename, text) {
var errors = [];
var path = self.savePath;
function phantomWrite(path, filename, text) {
// turn filename into a qualified path
filename = getQualifiedFilename(path, filename, window.fs_path_separator);
// write via a method injected by phantomjs-testrunner.js
__phantom_writeFile(filename, text);
}
function nodeWrite(path, filename, text) {
var fs = require("fs");
var nodejs_path = require("path");
require("mkdirp").sync(path); // make sure the path exists
var filepath = nodejs_path.join(path, filename);
var xmlfile = fs.openSync(filepath, "w");
fs.writeSync(xmlfile, text, 0);
fs.closeSync(xmlfile);
return;
}
// Attempt writing with each possible environment.
// Track errors in case no write succeeds
try {
phantomWrite(path, filename, text);
return;
} catch (e) { errors.push(' PhantomJs attempt: ' + e.message); }
try {
nodeWrite(path, filename, text);
return;
} catch (f) { errors.push(' NodeJS attempt: ' + f.message); }
// If made it here, no write succeeded. Let user know.
log("Warning: writing junit report failed for '" + path + "', '" +
filename + "'. Reasons:\n" +
errors.join("\n")
);
};
/******** Helper functions with closure access for simplicity ********/
function generateFilename(suite) {
return self.filePrefix + getFullyQualifiedSuiteName(suite, true) + '.xml';
}
function getFullyQualifiedSuiteName(suite, isFilename) {
var fullName;
if (self.useDotNotation || isFilename) {
fullName = suite.description;
for (var parent = suite._parent; parent; parent = parent._parent) {
fullName = parent.description + '.' + fullName;
}
} else {
fullName = suite.fullName;
}
// Either remove or escape invalid XML characters
if (isFilename) {
var fileName = "",
rFileChars = /[\w\.]/,
chr;
while (fullName.length) {
chr = fullName[0];
fullName = fullName.substr(1);
if (rFileChars.test(chr)) {
fileName += chr;
}
}
return fileName;
} else {
return escapeInvalidXmlChars(fullName);
}
}
function suiteAsXml(suite) {
var xml = '\n <testsuite name="' + getFullyQualifiedSuiteName(suite) + '"';
xml += ' timestamp="' + ISODateString(suite._startTime) + '"';
xml += ' hostname="localhost"'; // many CI systems like Jenkins don't care about this, but junit spec says it is required
xml += ' time="' + elapsed(suite._startTime, suite._endTime) + '"';
xml += ' errors="0"';
xml += ' tests="' + suite._specs.length + '"';
xml += ' skipped="' + suite._skipped + '"';
xml += ' disabled="' + suite._disabled + '"';
// Because of JUnit's flat structure, only include directly failed tests (not failures for nested suites)
xml += ' failures="' + suite._failures + '"';
xml += '>';
for (var i = 0; i < suite._specs.length; i++) {
xml += specAsXml(suite._specs[i]);
}
xml += '\n </testsuite>';
return xml;
}
function specAsXml(spec) {
var xml = '\n <testcase classname="' + getFullyQualifiedSuiteName(spec._suite) + '"';
xml += ' name="' + escapeInvalidXmlChars(spec.description) + '"';
xml += ' time="' + elapsed(spec._startTime, spec._endTime) + '"';
xml += '>';
if (isSkipped(spec) || isDisabled(spec)) {
xml += '<skipped />';
} else if (isFailed(spec)) {
for (var i = 0, failure; i < spec.failedExpectations.length; i++) {
failure = spec.failedExpectations[i];
xml += '\n <failure type="' + (failure.matcherName || "exception") + '"';
xml += ' message="' + trim(escapeInvalidXmlChars(failure.message))+ '"';
xml += '>';
xml += '<![CDATA[' + trim(failure.stack || failure.message) + ']]>';
xml += '\n </failure>';
}
}
xml += '\n </testcase>';
return xml;
}
// To remove complexity and be more DRY about the silly preamble and <testsuites> element
var prefix = '<?xml version="1.0" encoding="UTF-8" ?>';
prefix += '\n<testsuites>';
var suffix = '\n</testsuites>';
function wrapOutputAndWriteFile(filename, text) {
if (filename.substr(-4) !== '.xml') { filename += '.xml'; }
self.writeFile(filename, (prefix + text + suffix));
}
};
})(this);
| Zack-Tillotson/open-door-the-game | node_modules/jasmine-reporters/src/junit_reporter.js | JavaScript | mit | 13,510 |
<?php
$textImage = imagecreate(200,100);
$white = imagecolorallocate($textImage, 255, 255, 255);
$black = imagecolorallocate($textImage, 0, 0, 0);
$yOffset = 0;
for ($i = 1; $i <=5; $i++) {
imagestring($textImage, $i, 5, $yOffset, "This is system font $i", $black);
$yOffset += imagefontheight($i);
}
header("Content-type: image/png");
imagepng($textImage);
imagedestroy($textImage);
?>
| inest-us/php | PHP5/Ch16/drawstring.php | PHP | mit | 389 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injectable } from '@angular/core';
@Injectable()
export class Service386Service {
constructor() { }
}
| angular/angular-cli-stress-test | src/app/services/service-386.service.ts | TypeScript | mit | 320 |
/**
* Copyright (c) 2015-2018, CJ Hare All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* * Neither the name of [project] nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.systematic.trading.backtest.output.elastic.dao;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import com.systematic.trading.backtest.BacktestBatchId;
import com.systematic.trading.backtest.output.elastic.model.ElasticIndexName;
/**
* Connectivity to Elastic search.
*
* @author CJ Hare
*/
public interface ElasticDao {
Response index( ElasticIndexName indexName );
Response mapping( ElasticIndexName indexName, BacktestBatchId id );
void postTypes( ElasticIndexName indexName, Entity<?> requestBody );
void putMapping( ElasticIndexName indexName, BacktestBatchId id, Entity<?> requestBody );
void put( ElasticIndexName indexName, Entity<?> requestBody );
void putSetting( ElasticIndexName indexName, Entity<?> requestBody );
}
| CjHare/systematic-trading | systematic-trading-backtest-output-elastic/src/main/java/com/systematic/trading/backtest/output/elastic/dao/ElasticDao.java | Java | mit | 2,322 |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
namespace FluentAssertions.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class StringShouldNotBeNullOrWhiteSpaceAnalyzer : StringAnalyzer
{
public const string DiagnosticId = Constants.Tips.Strings.StringShouldNotBeNullOrWhiteSpace;
public const string Category = Constants.Tips.Category;
public const string Message = "Use .Should() followed by .NotBeNullOrWhiteSpace() instead.";
protected override DiagnosticDescriptor Rule => new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, DiagnosticSeverity.Info, true);
protected override IEnumerable<FluentAssertionsCSharpSyntaxVisitor> Visitors
{
get
{
yield return new StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor();
}
}
public class StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor : FluentAssertionsCSharpSyntaxVisitor
{
public StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor() : base(new MemberValidator("IsNullOrWhiteSpace"), MemberValidator.Should, new MemberValidator("BeFalse"))
{
}
}
}
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(StringShouldNotBeNullOrWhiteSpaceCodeFix)), Shared]
public class StringShouldNotBeNullOrWhiteSpaceCodeFix : FluentAssertionsCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(StringShouldNotBeNullOrWhiteSpaceAnalyzer.DiagnosticId);
protected override ExpressionSyntax GetNewExpression(ExpressionSyntax expression, FluentAssertionsDiagnosticProperties properties)
{
var remove = NodeReplacement.RemoveAndExtractArguments("IsNullOrWhiteSpace");
var newExpression = GetNewExpression(expression, remove);
var rename = NodeReplacement.Rename("BeFalse", "NotBeNullOrWhiteSpace");
newExpression = GetNewExpression(newExpression, rename);
var stringKeyword = newExpression.DescendantNodes().OfType<PredefinedTypeSyntax>().Single();
var subject = remove.Arguments.First().Expression;
return newExpression.ReplaceNode(stringKeyword, subject.WithTriviaFrom(stringKeyword));
}
}
} | fluentassertions/fluentassertions.analyzers | src/FluentAssertions.Analyzers/Tips/Strings/StringShouldNotBeNullOrWhiteSpace.cs | C# | mit | 2,544 |
package com.pedanov.departments.dao;
/**
* Created by Anfel on 16.02.2017.
*/
public class DepartmentDao {
}
| anfel4life/departments | src/main/java/com/pedanov/departments/dao/DepartmentDao.java | Java | mit | 112 |
package intersectables;
import base.HitRecord;
import base.Intersectable;
import base.Material;
import base.Ray;
/**
* Any Primitive Geometry is an intersectable and has a certain material assigned to.
* Created by simplaY on 06.01.2015.
*/
public abstract class PrimitiveGeometry implements Intersectable {
// material assigned to any PrimitiveGeometry.
// NB: Cannot be set after initialization.
protected final Material material;
/**
* Material that should be set to Geometry.
*
* @param material
*/
public PrimitiveGeometry(Material material) {
this.material = material;
}
public Material getMaterial() {
return material;
}
@Override
public abstract HitRecord intersect(Ray ray);
}
| simplay/aptRenderer | src/main/java/intersectables/PrimitiveGeometry.java | Java | mit | 771 |
var Handlebars = require("handlebars");
export default class Lean {
constructor() {
this.name = this.constructor.name;
this.id = `${this.name}-${Lean.INCREMENTAL_ID++}`;
this.children = {};
this.props = {};
this.element = null;
this.view = this.name;
Lean.registerInstance(this);
}
render() {
return Lean.Templates[this.view](this);
}
postrender() {
this.element = document.getElementById(this.id);
this.element.self = this;
this.postrenderRecursive(this.children);
}
postrenderRecursive(component) {
if(!component) {
return;
}
else if(typeof component.postrender === "function") {
component.postrender();
}
else if(Array.isArray(component)) {
component.forEach(this.postrenderRecursive.bind(this));
}
else if(typeof component === "object" && component !== null) {
for(let childName in component) {
this.postrenderRecursive(component[childName]);
}
}
}
rerender(selector) {
if(selector) {
var wrapperElement = document.createElement("div");
wrapperElement.innerHTML = this.render();
this.element.querySelector(selector).outerHTML = wrapperElement.querySelector(selector).outerHTML;
}
else {
this.element.outerHTML = this.render();
this.postrender();
}
}
static precompileAllInPage() {
var allTemplates = document.querySelectorAll('script[type="text/x-handlebars-template"]');
for (let i = 0; i < allTemplates.length; i++) {
let template = allTemplates[i], isPartial = false;
if(template.classList.contains("partial")) {
isPartial = true;
}
Lean.precompile(template.id, template.innerHTML, isPartial);
}
}
static precompileAllFiles(baseDir, extension, templates, partials, done) {
var promises = [];
for (let i = 0; i < templates.length; i++) {
let
template = templates[i],
templateName = Lean.getBaseName(template),
isPartial = partials.indexOf(templateName) > -1 ? true : false;
promises.push(Lean.precompileFile(baseDir + template + extension, templateName, isPartial));
}
$.when.apply($, promises).done(done);
}
static precompileFile(templatePath, templateName, isPartial) {
return $.get(templatePath).done((data) => {
Lean.precompile(templateName, data, isPartial);
});
}
static precompile(id, innerHTML, isPartial) {
Lean.Templates[id] = Handlebars.compile(innerHTML);
if(isPartial) {
Handlebars.registerPartial(id, Lean.Templates[id]);
}
}
static registerInstance(instance) {
Lean.AllInstances[instance.id] = instance;
}
static findInstance(id) {
return document.getElementById(id).self;
}
static getBaseName(str) {
var base = new String(str).substring(str.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1) {
base = base.substring(0, base.lastIndexOf("."));
}
return base;
}
}
Lean.INCREMENTAL_ID = 0;
Lean.Templates = {};
Handlebars.registerHelper("render", (template) => {
if(template && typeof template.render === "function") {
return template.render();
}
else {
return ""
}
});
Handlebars.registerHelper("call", (context, func, ...params) => {
return func.apply(context, params);
}); | amirmohsen/lean | lib/Lean.js | JavaScript | mit | 3,109 |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketLibrary
{
/// <summary>
/// SocketµÄ¿Í»§¶Ë
/// </summary>
public class Client : SocketBase
{
//ÊÇ·ñÐÄÌø¼ì²â
private const bool _isSendHeartbeat = true;
/// <summary>
/// ³¬Ê±Ê±¼ä
/// </summary>
///
public const int CONNECTTIMEOUT = 10;
private TcpClient client;
private IPAddress ipAddress;
private int port;
private Thread _listenningClientThread;
private string _clientName;
/// <summary>
/// Á¬½ÓµÄKey
/// </summary>
public string ClientName
{
get { return _clientName; }
}
/// <summary>
/// ³õʼ»¯
/// </summary>
/// <param name="ipaddress">µØÖ·</param>
/// <param name="port">¶Ë¿Ú</param>
public Client(string ipaddress, int port)
: this(IPAddress.Parse(ipaddress), port)
{
}
/// <summary>
///³õʼ»¯
/// </summary>
/// <param name="ipaddress">µØÖ·</param>
/// <param name="port">¶Ë¿Ú</param>
public Client(IPAddress ipaddress, int port) : base(_isSendHeartbeat)
{
this.ipAddress = ipaddress;
this.port = port;
this._clientName = ipAddress + ":" + port;
}
/// <summary>
/// ´ò¿ªÁ´½Ó
/// </summary>
public void StartClient()
{
_listenningClientThread = new Thread(new ThreadStart(Start));
_listenningClientThread.Start();
}
/// <summary>
/// ¹Ø±ÕÁ¬½Ó²¢ÊÍ·Å×ÊÔ´
/// </summary>
public void StopClient()
{
this.EndListenAndSend();
//ȱÉÙ֪ͨ¸ø·þÎñ¶Ë ×Ô¼ºÖ÷¶¯¹Ø±ÕÁË
_listenningClientThread.Abort();
}
/// <summary>
/// »ñȡָ¶¨Á¬½ÓÃûµÄÁ¬½Ó,²éѯ²»µ½·µ»Ønull
/// </summary>
/// <returns></returns>
public Connection GetConnection()
{
Connection connection = null;
this.Connections.TryGetValue(this.ClientName, out connection);
return connection;
}
private void Start()
{
while (true)
{
if (!this.Connections.ContainsKey(this._clientName))
{
try
{
client = new TcpClient();
client.SendTimeout = CONNECTTIMEOUT;
client.ReceiveTimeout = CONNECTTIMEOUT;
client.Connect(ipAddress, port);
Connection conn = new Connection(client, this._clientName);
this.Connections.TryAdd(this._clientName, conn);
this.OnConnected(this, conn);
}
catch (Exception ex)
{
this.connClose(this._clientName, new List<Message>() { }, ex);
}
}
//½ÓÊÕÊý¾Ý¡¢·¢ËÍÊý¾Ý ÐÄÌø¼ì²â
this.SenRecMsg();
Thread.Sleep(1000);
}
}
}
}
| Harbour9354/Socket.Harbour | SocketLibrary/Client.cs | C# | mit | 3,300 |
<?php
/**
* This file is part of ClassMocker.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package JSiefer\ClassMocker
*/
namespace JSiefer\ClassMocker\Footprint;
/**
* Class ClassFootprintTest
*
* @covers \JSiefer\ClassMocker\Footprint\ClassFootprint
*/
class ClassFootprintTest extends \PHPUnit_Framework_TestCase
{
/**
* Test type methods
*
* @return void
* @test
*/
public function testType()
{
$footprint = new ClassFootprint();
$this->assertEquals(
ClassFootprint::TYPE_CLASS,
$footprint->getType(),
'Class should be the default type'
);
$this->assertFalse(
$footprint->isInterface(),
'Should not be an interface by default'
);
$footprint->setType(ClassFootprint::TYPE_INTERFACE);
$this->assertTrue(
$footprint->isInterface(),
'Should be an interface'
);
}
/**
* Test Parent Setter and Getter
*
* @return void
* @test
*/
public function testParentSetter()
{
$footprint = new ClassFootprint();
$footprint->setParent('');
$this->assertNull(
$footprint->getParent(),
'Empty parent class must result in NULL'
);
$footprint->setParent('Test');
$this->assertEquals(
'\Test',
$footprint->getParent(),
'Add root back-slash if missing'
);
$footprint->setParent('\Test');
$this->assertEquals(
'\Test',
$footprint->getParent(),
'Only add root back-slash if missing'
);
}
/**
* Test interface setter methods
*
* @return void
* @test
*/
public function testInterfaceSetter()
{
$footprint = new ClassFootprint();
$footprint->setInterfaces(['InterfaceA', '\InterfaceB']);
$this->assertEquals(
['\InterfaceA', '\InterfaceB'],
$footprint->getInterfaces(),
'Add root back-slash if missing'
);
$footprint->setInterfaces(['Foobar']);
$this->assertEquals(
['\Foobar'],
$footprint->getInterfaces(),
'Set must overwrite existing interfaces'
);
$footprint->addInterface('Barfoo');
$this->assertEquals(
['\Foobar', '\Barfoo'],
$footprint->getInterfaces(),
'Add must NOT overwrite existing interfaces'
);
$footprint->addInterface('');
$this->assertEquals(
['\Foobar', '\Barfoo'],
$footprint->getInterfaces(),
'Add must ignore empty interfaces'
);
}
/**
* Test constant setter methods
*
* @return void
* @test
*/
public function testConstantSetter()
{
$footprint = new ClassFootprint();
$footprint->setConstants(['FOO' => 'foo', 'TWO' => '2']);
$this->assertSame(
['FOO' => 'foo', 'TWO' => 2.0],
$footprint->getConstants(),
'Strings must be checked vor number values'
);
$footprint->setConstants(['FOO' => 'foo']);
$this->assertEquals(
['FOO' => 'foo'],
$footprint->getConstants(),
'Set must replace existing constants'
);
$footprint->addConstant('BAR', 'bar');
$this->assertEquals(
['FOO' => 'foo', 'BAR' => 'bar'],
$footprint->getConstants(),
'Add must NOT replace existing constants'
);
}
/**
* Simple export and import test
*
* Footprint can be exported to simple arrays and then
* re-imported
*
* The exported footprint data should be as small as possible
* to later easily create small json reference files
*
* @return void
* @test
*/
public function testExportAndImport()
{
$source = new ClassFootprint();
$source->setType(ClassFootprint::TYPE_INTERFACE);
$source->setParent('Test');
$source->addConstant('A', '1');
$source->addConstant('B', '1.5');
$source->addConstant('C', 'test');
$source->setInterfaces(['InterfaceA', 'InterfaceB']);
$data = $source->export();
$this->assertInternalType(
'array',
$data,
'Exported data should be an array'
);
$target = new ClassFootprint($data);
$this->assertSame(
$target->getType(),
$source->getType(),
'Should have copied type'
);
$this->assertSame(
$target->getParent(),
$source->getParent(),
'Should have copied parent class'
);
$this->assertSame(
$target->getConstants(),
$source->getConstants(),
'Should have copied constants'
);
$this->assertSame(
$target->getInterfaces(),
$source->getInterfaces(),
'Should have copied interface'
);
}
/**
* Should fail on invalid data
*
* The footprint data must be an array of size 4
*
* @test
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid footprint array
*/
public function shouldFailOnInvalidData()
{
new ClassFootprint([0,0]);
}
}
| jsiefer/class-mocker | tests/Footprint/ClassFootprintTest.php | PHP | mit | 5,555 |
/**
* File: Command.java<br/>
* Author: Peter M. Corcoran, pmcorcor@uab.edu<br/>
* Assignment: EE433 Research Project<br/>
* Version: 1.0.0 11/27/2015 pmc - initial coding<br/>
* Structure Component: Abstract Command Object
*/
package ee433.behavior.command;
public abstract class Command {
public abstract void execute();
}
| corcoranp/ee433 | src/ee433/behavior/command/Command.java | Java | mit | 337 |
class BitsInterpreter < ActiveRecord::Base
validates_presence_of :name, :length
validates_numericality_of :length, :only_integer => true
validates_inclusion_of :length, :in => [16, 32, 48, 64, 1024], :message => "valid value [16, 32, 48, 64, 1024]"
validates_length_of :name, :maximum => 255
validates_uniqueness_of :name
validates_length_of :description, :maximum => 255, :allow_nil => true
has_many :bits_segments, -> {order :start_bit}
def validate
name.strip!
end
end
| rli9/vims | app/models/bits_interpreter.rb | Ruby | mit | 498 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require 'icheck'
//= require highcharts
//= require highcharts/highcharts-more
//= require_tree .
function icheck(){
if($(".icheck-me").length > 0){
$(".icheck-me").each(function(){
var $el = $(this);
var skin = ($el.attr('data-skin') !== undefined) ? "_" + $el.attr('data-skin') : "",
color = ($el.attr('data-color') !== undefined) ? "-" + $el.attr('data-color') : "";
var opt = {
checkboxClass: 'icheckbox' + skin + color,
radioClass: 'iradio' + skin + color,
}
$el.iCheck(opt);
});
}
}
$(function(){
icheck();
})
| MaSys/natumex | app/assets/javascripts/application.js | JavaScript | mit | 1,227 |
<?php
namespace Tests\DependencyInjectorTests;
return [
ServiceWithDependency::class,
TestService::class,
BaseService::class,
ExtendedService::class
];
| martinbrom/trip-hatch | tests/DependencyInjectorTests/service_list.php | PHP | mit | 170 |
using System.Xml.Serialization;
namespace WebApiDavExtension.CalDav
{
[XmlRoot("href", Namespace = "DAV:")]
public class HRef
{
public HRef()
{
}
public HRef(string reference)
{
Reference = reference;
}
[XmlText]
public string Reference { get; set; }
}
}
| medocheck/WebApiDavExtension | WebApiDavExtension/CalDav/HRef.cs | C# | mit | 353 |
import asyncio
import rocat.message
import rocat.actor
import rocat.globals
class BaseActorRef(object):
def tell(self, m, *, sender=None):
raise NotImplementedError
def ask(self, m, *, timeout=None):
raise NotImplementedError
def error(self, e):
raise NotImplementedError
class LocalActorRef(BaseActorRef):
def __init__(self, q, loop):
self._q = q
self._loop = loop
def _send(self, envel):
self._loop.call_soon_threadsafe(self._q.put_nowait, envel)
def tell(self, m, *, sender=None):
if sender is None:
sender = _guess_current_sender()
self._send(rocat.message.Envelope.for_tell(m, sender=sender))
async def ask(self, m, *, timeout=None):
fut = asyncio.get_event_loop().create_future()
sender = FunctionRef(fut, asyncio.get_event_loop())
self._send(rocat.message.Envelope.for_ask(m, sender=sender))
if timeout is None:
timeout = _guess_default_timeout()
if timeout > 0:
reply = await asyncio.wait_for(fut, timeout)
else:
reply = await fut
if reply.is_error:
raise reply.msg
return reply.msg
def error(self, e):
raise NotImplementedError('You can tell error only when you reply')
class FunctionRef(BaseActorRef):
def __init__(self, fut, loop):
self._fut = fut
self._loop = loop
def _send(self, envel):
self._loop.call_soon_threadsafe(self._try_set_future, envel)
def _try_set_future(self, result):
if not self._fut.done():
self._fut.set_result(result)
def tell(self, m, *, sender=None):
if sender is None:
sender = _guess_current_sender()
self._send(rocat.message.Envelope.for_ask(m, sender=sender))
def ask(self, m, *, sender=None, timeout=None):
raise NotImplementedError('You cannot ask back to ask request')
def error(self, e):
self._send(rocat.message.Envelope.for_error(e))
def _guess_current_sender():
current_ctx = rocat.actor.ActorContext.current()
if current_ctx is not None:
return current_ctx.sender
def _guess_default_timeout():
current_ctx = rocat.actor.ActorContext.current()
if current_ctx is not None:
return current_ctx.default_timeout or -1
return -1
| chongkong/rocat | rocat/ref.py | Python | mit | 2,370 |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017-2018 Esteban Tovagliari, The appleseedhq Organization
//
// 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
// AUTHORS OR COPYRIGHT HOLDERS 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.
//
// Interface header.
#include "plasticbrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/scatteringmode.h"
#include "renderer/kernel/shading/directshadingcomponents.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/bsdfsample.h"
#include "renderer/modeling/bsdf/bsdfwrapper.h"
#include "renderer/modeling/bsdf/fresnel.h"
#include "renderer/modeling/bsdf/microfacethelper.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/containers/dictionary.h"
#include "foundation/math/basis.h"
#include "foundation/math/dual.h"
#include "foundation/math/fresnel.h"
#include "foundation/math/microfacet.h"
#include "foundation/math/sampling/mappings.h"
#include "foundation/math/vector.h"
#include "foundation/utility/api/specializedapiarrays.h"
#include "foundation/utility/makevector.h"
// Standard headers.
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <string>
// Forward declarations.
namespace foundation { class IAbortSwitch; }
namespace renderer { class Assembly; }
namespace renderer { class Project; }
using namespace foundation;
namespace renderer
{
namespace
{
//
// Plastic BRDF.
//
// References:
//
// [1] A Physically-Based Reflectance Model Combining Reflection and Diffraction
// https://hal.inria.fr/hal-01386157
//
// [2] Mitsuba renderer
// https://github.com/mitsuba-renderer/mitsuba
//
const char* Model = "plastic_brdf";
class PlasticBRDFImpl
: public BSDF
{
public:
PlasticBRDFImpl(
const char* name,
const ParamArray& params)
: BSDF(name, Reflective, ScatteringMode::Diffuse | ScatteringMode::Glossy | ScatteringMode::Specular, params)
{
m_inputs.declare("diffuse_reflectance", InputFormatSpectralReflectance);
m_inputs.declare("diffuse_reflectance_multiplier", InputFormatFloat, "1.0");
m_inputs.declare("specular_reflectance", InputFormatSpectralReflectance);
m_inputs.declare("specular_reflectance_multiplier", InputFormatFloat, "1.0");
m_inputs.declare("roughness", InputFormatFloat, "0.15");
m_inputs.declare("ior", InputFormatFloat, "1.5");
m_inputs.declare("internal_scattering", InputFormatFloat, "1.0");
}
void release() override
{
delete this;
}
const char* get_model() const override
{
return Model;
}
size_t compute_input_data_size() const override
{
return sizeof(InputValues);
}
void prepare_inputs(
Arena& arena,
const ShadingPoint& shading_point,
void* data) const override
{
InputValues* values = static_cast<InputValues*>(data);
// Apply multipliers to input values.
values->m_specular_reflectance *= values->m_specular_reflectance_multiplier;
values->m_diffuse_reflectance *= values->m_diffuse_reflectance_multiplier;
values->m_roughness = std::max(values->m_roughness, shading_point.get_ray().m_min_roughness);
new (&values->m_precomputed) InputValues::Precomputed();
const float outside_ior = shading_point.get_ray().get_current_ior();
values->m_precomputed.m_eta = outside_ior / values->m_ior;
values->m_precomputed.m_specular_weight = std::max(max_value(values->m_specular_reflectance), 0.0f);
values->m_precomputed.m_diffuse_weight = std::max(max_value(values->m_diffuse_reflectance), 0.0f);
}
void sample(
SamplingContext& sampling_context,
const void* data,
const bool adjoint,
const bool cosine_mult,
const LocalGeometry& local_geometry,
const Dual3f& outgoing,
const int modes,
BSDFSample& sample) const override
{
const InputValues* values = static_cast<const InputValues*>(data);
const float alpha = microfacet_alpha_from_roughness(values->m_roughness);
// Compute the microfacet normal by sampling the MDF.
const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing.get_value());
sampling_context.split_in_place(3, 1);
const Vector3f s = sampling_context.next2<Vector3f>();
const Vector3f m =
alpha == 0.0f
? Vector3f(0.0f, 1.0f, 0.0f)
: GGXMDF::sample(wo, Vector2f(s[0], s[1]), alpha);
const float F = fresnel_reflectance(wo, m, values->m_precomputed.m_eta);
const float specular_probability = choose_specular_probability(*values, F);
Vector3f wi;
// Choose between specular/glossy and diffuse.
if (ScatteringMode::has_glossy(modes) &&
(!ScatteringMode::has_diffuse(modes) || s[2] < specular_probability))
{
wi = improve_normalization(reflect(wo, m));
if (wi.y <= 0.0f)
return;
if (alpha == 0.0f)
{
if (!ScatteringMode::has_specular(modes))
return;
sample.set_to_scattering(ScatteringMode::Specular, DiracDelta);
sample.m_value.m_glossy = values->m_specular_reflectance;
sample.m_value.m_glossy *= F;
sample.m_value.m_beauty = sample.m_value.m_glossy;
sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi));
sample.m_min_roughness = values->m_roughness;
sample.compute_glossy_reflected_differentials(local_geometry, values->m_roughness, outgoing);
}
else
{
const float probability = specular_pdf(alpha, wo, m) * specular_probability;
assert(probability >= 0.0f);
if (probability > 1.0e-6f)
{
sample.set_to_scattering(ScatteringMode::Glossy, probability);
sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi));
sample.m_min_roughness = values->m_roughness;
evaluate_specular(
values->m_specular_reflectance,
alpha,
wi,
wo,
m,
F,
sample.m_value.m_glossy);
sample.m_value.m_beauty = sample.m_value.m_glossy;
sample.compute_glossy_reflected_differentials(local_geometry, values->m_roughness, outgoing);
}
}
}
else
{
wi = sample_hemisphere_cosine(Vector2f(s[0], s[1]));
const float probability = wi.y * RcpPi<float>() * (1.0f - specular_probability);
assert(probability > 0.0f);
if (probability > 1.0e-6f)
{
sample.set_to_scattering(ScatteringMode::Diffuse, probability);
sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi));
sample.m_min_roughness = values->m_roughness;
const float Fi = fresnel_reflectance(wi, m, values->m_precomputed.m_eta);
evaluate_diffuse(
values->m_diffuse_reflectance,
values->m_precomputed.m_eta,
values->m_internal_scattering,
F,
Fi,
sample.m_value.m_diffuse);
sample.m_value.m_beauty = sample.m_value.m_diffuse;
sample.m_aov_components.m_albedo = values->m_diffuse_reflectance;
sample.compute_diffuse_differentials(outgoing);
}
}
}
float evaluate(
const void* data,
const bool adjoint,
const bool cosine_mult,
const LocalGeometry& local_geometry,
const Vector3f& outgoing,
const Vector3f& incoming,
const int modes,
DirectShadingComponents& value) const override
{
const InputValues* values = static_cast<const InputValues*>(data);
const float alpha = microfacet_alpha_from_roughness(values->m_roughness);
const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing);
const Vector3f wi = local_geometry.m_shading_basis.transform_to_local(incoming);
const Vector3f m =
alpha == 0.0f
? Vector3f(0.0f, 1.0f, 0.0f)
: normalize(wi + wo);
const float Fo = fresnel_reflectance(wo, m, values->m_precomputed.m_eta);
const float Fi = fresnel_reflectance(wi, m, values->m_precomputed.m_eta);
const float specular_probability = choose_specular_probability(*values, Fo);
float pdf_glossy = 0.0f, pdf_diffuse = 0.0f;
if (ScatteringMode::has_glossy(modes))
{
evaluate_specular(
values->m_specular_reflectance,
alpha,
wi,
wo,
m,
Fo,
value.m_glossy);
pdf_glossy = specular_pdf(alpha, wo, m);
}
if (ScatteringMode::has_diffuse(modes))
{
evaluate_diffuse(
values->m_diffuse_reflectance,
values->m_precomputed.m_eta,
values->m_internal_scattering,
Fo,
Fi,
value.m_diffuse);
pdf_diffuse = std::abs(wi.y) * RcpPi<float>();
}
value.m_beauty = value.m_diffuse;
value.m_beauty += value.m_glossy;
const float pdf =
ScatteringMode::has_diffuse_and_glossy(modes) ? lerp(pdf_diffuse, pdf_glossy, specular_probability) :
ScatteringMode::has_diffuse(modes) ? pdf_diffuse :
ScatteringMode::has_glossy(modes) ? pdf_glossy : 0.0f;
assert(pdf >= 0.0f);
return pdf;
}
float evaluate_pdf(
const void* data,
const bool adjoint,
const LocalGeometry& local_geometry,
const Vector3f& outgoing,
const Vector3f& incoming,
const int modes) const override
{
const InputValues* values = static_cast<const InputValues*>(data);
const float alpha = microfacet_alpha_from_roughness(values->m_roughness);
const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing);
const Vector3f wi = local_geometry.m_shading_basis.transform_to_local(incoming);
const Vector3f m =
alpha == 0.0f
? Vector3f(0.0f, 1.0f, 0.0f)
: normalize(wi + wo);
const float F = fresnel_reflectance(wo, m, values->m_precomputed.m_eta);
const float specular_probability = choose_specular_probability(*values, F);
const float pdf_glossy =
ScatteringMode::has_glossy(modes)
? specular_pdf(alpha, wo, m)
: 0.0f;
const float pdf_diffuse =
ScatteringMode::has_diffuse(modes)
? std::abs(wi.y) * RcpPi<float>()
: 0.0f;
const float pdf =
ScatteringMode::has_diffuse_and_glossy(modes) ? lerp(pdf_diffuse, pdf_glossy, specular_probability) :
ScatteringMode::has_diffuse(modes) ? pdf_diffuse :
ScatteringMode::has_glossy(modes) ? pdf_glossy : 0.0f;
assert(pdf >= 0.0f);
return pdf;
}
private:
typedef PlasticBRDFInputValues InputValues;
static float choose_specular_probability(
const InputValues& values,
const float F)
{
const float specular_weight = F * values.m_precomputed.m_specular_weight;
const float diffuse_weight = (1.0f - F) * values.m_precomputed.m_diffuse_weight;
const float total_weight = specular_weight + diffuse_weight;
return total_weight == 0.0f ? 1.0f : specular_weight / total_weight;
}
static float fresnel_reflectance(
const Vector3f& w,
const Vector3f& m,
const float eta)
{
const float cos_wm(dot(w, m));
if (cos_wm < 0.0f)
return 0.0f;
float F;
fresnel_reflectance_dielectric(
F,
eta,
std::min(cos_wm, 1.0f));
return F;
}
static void evaluate_specular(
const Spectrum& specular_reflectance,
const float alpha,
const Vector3f& wi,
const Vector3f& wo,
const Vector3f& m,
const float F,
Spectrum& value)
{
if (alpha == 0.0f)
return;
const float denom = std::abs(4.0f * wo.y * wi.y);
if (denom == 0.0f)
{
value.set(0.0f);
return;
}
value = specular_reflectance;
const float D = GGXMDF::D(m, alpha);
const float G = GGXMDF::G(wi, wo, m, alpha);
value *= F * D * G / denom;
}
static float specular_pdf(
const float alpha,
const Vector3f& wo,
const Vector3f& m)
{
if (alpha == 0.0f)
return 0.0f;
const float cos_wom = dot(wo, m);
if (cos_wom == 0.0f)
return 0.0f;
const float jacobian = 1.0f / (4.0f * std::abs(cos_wom));
return jacobian * GGXMDF::pdf(wo, m, alpha, alpha);
}
static void evaluate_diffuse(
const Spectrum& diffuse_reflectance,
const float eta,
const float internal_scattering,
const float Fo,
const float Fi,
Spectrum& value)
{
const float eta2 = square(eta);
const float fdr = fresnel_internal_diffuse_reflectance(1.0f / eta);
const float T = (1.0f - Fo) * (1.0f - Fi);
for (size_t i = 0, e = Spectrum::size(); i < e; ++i)
{
const float pd = diffuse_reflectance[i];
const float non_linear_term = 1.0f - lerp(1.0f, pd, internal_scattering) * fdr;
value[i] = (T * pd * eta2 * RcpPi<float>()) / non_linear_term;
}
}
};
typedef BSDFWrapper<PlasticBRDFImpl> PlasticBRDF;
}
//
// PlasticBRDFFactory class implementation.
//
void PlasticBRDFFactory::release()
{
delete this;
}
const char* PlasticBRDFFactory::get_model() const
{
return Model;
}
Dictionary PlasticBRDFFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Plastic BRDF");
}
DictionaryArray PlasticBRDFFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "diffuse_reflectance")
.insert("label", "Diffuse Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Texture Instances"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "diffuse_reflectance_multiplier")
.insert("label", "Diffuse Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Texture Instances"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "specular_reflectance")
.insert("label", "Specular Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Texture Instances"))
.insert("use", "required")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "specular_reflectance_multiplier")
.insert("label", "Specular Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Texture Instances"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "roughness")
.insert("label", "Roughness")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Texture Instances"))
.insert("use", "optional")
.insert("min",
Dictionary()
.insert("value", "0.0")
.insert("type", "hard"))
.insert("max",
Dictionary()
.insert("value", "1.0")
.insert("type", "hard"))
.insert("default", "0.15"));
metadata.push_back(
Dictionary()
.insert("name", "ior")
.insert("label", "Index of Refraction")
.insert("type", "numeric")
.insert("min",
Dictionary()
.insert("value", "1.0")
.insert("type", "hard"))
.insert("max",
Dictionary()
.insert("value", "2.5")
.insert("type", "hard"))
.insert("use", "required")
.insert("default", "1.5"));
metadata.push_back(
Dictionary()
.insert("name", "internal_scattering")
.insert("label", "Internal Scattering")
.insert("type", "numeric")
.insert("min",
Dictionary()
.insert("value", "0.0")
.insert("type", "hard"))
.insert("max",
Dictionary()
.insert("value", "1.0")
.insert("type", "hard"))
.insert("use", "optional")
.insert("default", "1.0"));
return metadata;
}
auto_release_ptr<BSDF> PlasticBRDFFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<BSDF>(new PlasticBRDF(name, params));
}
} // namespace renderer
| est77/appleseed | src/appleseed/renderer/modeling/bsdf/plasticbrdf.cpp | C++ | mit | 21,564 |
#!/usr/bin/env python3.7
# coding=utf-8
"""Jerod Gawne, 2018.06.28
https://github.com/jerodg/hackerrank
"""
import sys
import traceback
if __name__ == '__main__':
try:
n, m = map(int, input().split())
for i in range(1, n, 2):
print(str('.|.') * i).center(m, '-')
print(str('WELCOME').center(m, '-'))
for i in range(n - 2, -1, -2):
print(str('.|.') * i).center(m, '-')
except Exception:
print(traceback.print_exception(*sys.exc_info()))
| jerodg/hackerrank-python | python/02.Strings/08.DesignerDoorMat/solution1.py | Python | mit | 510 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TheWorld.Services
{
using System.Diagnostics;
public class DebugMailService : IMailService
{
public void SendMail(string to, string from, string subject, string body)
{
Debug.WriteLine($"Sending Mail: To {to}, From {from}, Subject {subject}");
}
}
}
| tonyisaway/aspdotnetcore-efcore-bootstrap-angular-web-app | TheWorld/Services/DebugMailService.cs | C# | mit | 414 |
'use strict';
const { ManyToManyModifyMixin } = require('./ManyToManyModifyMixin');
const SQLITE_BUILTIN_ROW_ID = '_rowid_';
// We need to override this mixin for sqlite because sqlite doesn't support
// multi-column where in statements with subqueries. We need to use the
// internal _rowid_ column instead.
const ManyToManySqliteModifyMixin = (Operation) => {
return class extends ManyToManyModifyMixin(Operation) {
applyModifyFilterForRelatedTable(builder) {
const tableRef = builder.tableRefFor(this.relation.relatedModelClass);
const rowIdRef = `${tableRef}.${SQLITE_BUILTIN_ROW_ID}`;
const subquery = this.modifyFilterSubquery.clone().select(rowIdRef);
return builder.whereInComposite(rowIdRef, subquery);
}
applyModifyFilterForJoinTable(builder) {
const joinTableOwnerRefs = this.relation.joinTableOwnerProp.refs(builder);
const tableRef = builder.tableRefFor(this.relation.getJoinModelClass(builder));
const rowIdRef = `${tableRef}.${SQLITE_BUILTIN_ROW_ID}`;
const ownerValues = this.owner.getProps(this.relation);
const subquery = this.modifyFilterSubquery.clone().select(rowIdRef);
return builder
.whereInComposite(rowIdRef, subquery)
.whereInComposite(joinTableOwnerRefs, ownerValues);
}
};
};
module.exports = {
ManyToManySqliteModifyMixin,
};
| Vincit/objection.js | lib/relations/manyToMany/ManyToManySqliteModifyMixin.js | JavaScript | mit | 1,361 |
@extends('layouts.default')
@section('content')
@include('game.partials.header')
<!-- game menu -->
<div class="row">
<div class="col-sm-5 movie-production">
<p>Current loan: {{ $currentLoan }} € (max. 2000000 €)</p>
{{ Form::open(['route' => 'takeLoan_path']) }}
<div class="form-group">
{{ Form::label('amount', 'Loan:') }}
{{ Form::input('number', 'amount', 0, ['class' => 'input-sm form-control', 'max' => (2000000 - $currentLoan), 'min' => 0, 'step' => 100000]) }}
</div>
<div class="form-group div-button-footer">
{{ link_to_route('menu_path', 'Go back', null, ['class' => 'btn btn-sm btn-default']) }}
{{ Form::submit('Take loan!', ['class' => 'btn btn-sm btn-success']) }}
</div>
{{ Form::close() }}
</div>
</div>
@stop | teruk/movbizz | app/views/loan/take.blade.php | PHP | mit | 783 |
class AddIsCommentToAnswers < ActiveRecord::Migration[4.2]
def change
add_column :answers, :is_comment, :boolean, default: false
end
end
| wested/surveyor_gui | db/migrate/20140531012006_add_is_comment_to_answers.rb | Ruby | mit | 145 |
<!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" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Onboard Network - Advertise with Music Influencers</title>
<link type="text/css" rel="stylesheet" href="<?php echo asset_url();?>css/bootstrap.css" />
<link href="<?php echo asset_url();?>css/bootstrap-slider.css" rel="stylesheet">
<link href="<?php echo asset_url();?>css/style.css" type="text/css" rel="stylesheet" />
<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,200,200italic,300,300italic,400italic,600,600italic,700,900,900italic,700italic' rel='stylesheet' type='text/css'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<link type="text/css" rel="stylesheet" href="<?php echo asset_url();?>css/jquery.bxslider.css" />
<script src="<?php echo asset_url();?>js/bootstrap.js"></script>
<script>
$(document).ready(function (){
$("#frm_login").submit(function (e){
e.preventDefault();
var url = $(this).attr('action');
var method = $(this).attr('method');
var data = $(this).serialize();
console.log(data);
console.log(method);
console.log(url);
$.ajax({
url:url,
type:method,
data:data
}).done(function(data){
console.log(data);
if(data == false){
$("#error_section").html("Incorrect username/password");
} else {
window.location.href='<?php echo base_url() ?>Main/members';
}
});
});
$("#testt").on("click",function(){
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=95123&sensor=true";
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
success: function(result){
console.log(result);
}
})
});
$("#find_doctor").on("click",function(){
$("#modal_title").html("Please enter zipcode");
$("#modal_body").html('<div class="form-group"><div class="col-xs-3"></br><input type="zipCode" class="form-control" name="zipCode" id="zipCode" placeholder="Enter your zip code"></div></div><a href="<?php echo base_url() ?>Doctors"><button type="button" name="submit" class="btn btn-default">Submit</button></a>');
});
$("#find_clinic").on("click",function(){
$("#modal_title").html("Please enter zipcode");
$("#modal_body").html('<div class="form-group"><div class="col-xs-3"></br><input type="zipCode" class="form-control" name="zipCode" id="zipCode" placeholder="Enter your zip code"></div></div><a href="<?php echo base_url() ?>Clinics"><button type="button" name="submit" class="btn btn-default">Submit</button></a>');
});
// $("#sign_in").on("click", function(){
// $(".modal-title").html("Please sign in to your account.");
// $(".modal-body").html(' <div class="container"> <form method="post" id="frm_login" class="form-inline" role="form" accept-charset="utf-8" action="<?php echo base_url()?>Main/login_validation"> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" value="<?php $this->input->post('email')?>"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" name="password" id="password" placeholder="Enter password"> </div> <button type="submit" name="login_submit" class="btn btn-default">Submit</button> <a href="<?php echo base_url()?>main/signup"> Sign up!</a> <div class="form_validation_error" id="error_section"><?php echo validation_errors();?></div> </form> </div>');
// });
});
</script>
</head>
<body ng-app="fertility">
<section id="clinic">
</section>
<section id="header" class="inner clinic">
<div class="container">
<nav class="navbar navbar-default navbar-static-top responsive col-lg-12" role="navigation">
<div class="navbar-header responsive">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div id="logo" class="navbar-brand">
<a href="<?php echo base_url() ?>">FERTILITY COUNSELORS</a>
</div>
</div>
<div id="navbar" class="navbar-collapse text-right collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="<?php echo base_url() ?>">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">CONTACT</a></li>
<li><a data-toggle="modal" data-target="#myModal2" id="find_clinic">CLINICS</a></li>
<li><a data-toggle="modal" data-target="#myModal2" id="find_doctor">DOCTORS</a></li>
<li><a data-toggle="modal" data-target="#myModal">SIGN IN</a></li>
</ul>
</div><!--/.nav-collapse -->
</nav>
</div>
</section>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="background-color: #335764;color: white;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please sign in to your account.</h4>
</div>
<div class="modal-body">
<div class="container">
<form method="post" id="frm_login" class="form-inline" role="form" accept-charset="utf-8" action="<?php echo base_url()?>Main/login_validation">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter email" value="<?php $this->input->post('email')?>">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Enter password">
</div>
<button type="submit" name="login_submit" class="btn btn-default">Submit</button>
<a href="<?php echo base_url()?>main/signup"> Sign up!</a>
<div class="form_validation_error" id="error_section"><?php echo validation_errors();?></div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal2" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="background-color: #335764;color: white;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="modal_title"></h4>
</div>
<div class="modal-body" id="modal_body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div> | shahin1986/fertility_dev | application/views/header2.php | PHP | mit | 7,983 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Templating;
use Nette;
use Latte;
use Nette\Utils\Strings;
/**
* @deprecated
*/
class Helpers extends Latte\Runtime\Filters
{
private static $helpers = array(
'normalize' => 'Nette\Utils\Strings::normalize',
'toascii' => 'Nette\Utils\Strings::toAscii',
'webalize' => 'Nette\Utils\Strings::webalize',
'padleft' => 'Nette\Utils\Strings::padLeft',
'padright' => 'Nette\Utils\Strings::padRight',
'reverse' => 'Nette\Utils\Strings::reverse',
'url' => 'rawurlencode',
);
/**
* Try to load the requested helper.
* @param string helper name
* @return callable
*/
public static function loader($helper)
{
trigger_error(__CLASS__ . ' is deprecated.', E_USER_DEPRECATED);
if (method_exists(__CLASS__, $helper)) {
return array(__CLASS__, $helper);
} elseif (isset(self::$helpers[$helper])) {
return self::$helpers[$helper];
}
}
/**
* Date/time modification.
* @param string|int|\DateTime
* @param string|int
* @param string
* @return Nette\Utils\DateTime
*/
public static function modifyDate($time, $delta, $unit = NULL)
{
return $time == NULL // intentionally ==
? NULL
: Nette\Utils\DateTime::from($time)->modify($delta . $unit);
}
/**
* Returns array of string length.
* @param mixed
* @return int
*/
public static function length($var)
{
return is_string($var) ? Strings::length($var) : count($var);
}
/**
* /dev/null.
* @param mixed
* @return string
*/
public static function null()
{
return '';
}
public static function optimizePhp($source, $lineLength = 80)
{
return Latte\Helpers::optimizePhp($source, $lineLength);
}
}
| JanTvrdik/NetteComponentsExample | vendor/nette/deprecated/src/Templating/Helpers.php | PHP | mit | 1,793 |
<?php
require_once('includes/config.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>
<?php echo SITENAME; ?>
</title>
<meta name="description" content="<?php echo DESCRIPTION ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/main.css">
<link rel="alternate" href="rss.php" title="My RSS feed" type="application/rss+xml" />
<script type="text/javascript">
window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var n=t.forceSSL||"https:"===document.location.protocol,a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=(n?"https:":"http:")+"//cdn.heapanalytics.com/js/heap-"+e+".js";var o=document.getElementsByTagName("script")[0];o.parentNode.insertBefore(a,o);for(var r=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"],c=0;c<p.length;c++)heap[p[c]]=r(p[c])};
heap.load("14710187");
</script>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div id="wrapper">
<h1><?php echo SITENAME; ?></h1>
<div id="nav">
<ul>
<?php require_once('nav.php'); ?>
</div>
<div id='main'>
<?php
if(isset($_GET['month']) || isset($_GET['year'])) {
try {
//collect month and year data
$month = $_GET['month'];
$year = rtrim($_GET['year'], '.html');
//set from and to dates
$from = date('Y-m-01 00:00:00', strtotime("$year-$month"));
$to = date('Y-m-31 23:59:59', strtotime("$year-$month"));
$pages = new Paginator('5', 'p');
$stmt = $db->prepare('SELECT postID FROM blog_posts_seo WHERE postDate >= :from AND postDate <= :to AND published = 1');
$stmt->execute(array(
':from' => $from,
':to' => $to
));
//pass number of records to
$pages->set_total($stmt->rowCount());
$stmt = $db->prepare('SELECT p.postID, m.username, p.postTitle,
p.postDesc, p.postDate, p.postSlug FROM blog_posts_seo p,
blog_members m WHERE p.poster = m.memberID AND postDate
>= :from AND postDate <= :to AND published = 1 ORDER BY postID DESC ' .
$pages->get_limit());
$stmt->execute(array(
':from' => $from,
':to' => $to
));
while ($row = $stmt->fetch()) {
echo '<h1><a href="viewpost.php?id=' . $row['postID'] . '">' . $row['postTitle'] . '</a></h1>';
echo '<p>Posted on ' . date('jS M Y H:i:s', strtotime($row['postDate'])) . ' by <b>' . $row['username'] . '</b> in ';
$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat) {
$links[] = "<a href='c-" . $cat['catSlug'] . ".html'>" . $cat['catTitle'] . "</a>";
}
echo implode(", ", $links);
echo '</p>';
echo '<p>' . $row['postDesc'] . '</p>';
echo '<p><a href="' . $row["postSlug"] . '.html">Read More</a></p>';
}
echo $pages->page_links("a-$month-$year&");
} catch (PDOException $e) {
echo $e->getMessage();
}
} else {
echo('<p>Please choose a Month to view</p><ul>');
$stmt = $db->query("SELECT count(postDate) as Count, Month(postDate) as Month, Year(postDate) as Year FROM blog_posts_seo GROUP BY Month(postDate), Year(postDate) ORDER BY postDate DESC");
while($row = $stmt->fetch()){
$monthName = date("F", mktime(0, 0, 0, $row['Month'], 10));
$slug = 'a-'.$row['Month'].'-'.$row['Year'];
echo '<li><a href="' . $slug . '.html">' . $monthName . ' ' . $row['Year'] . ' (' . $row["Count"] . ' posts)</a></li>';
}
echo('</ul>');
}
?>
</div>
<div id='clear'></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.marctowler.co.uk"]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u=(("https:" == document.location.protocol) ? "https" : "http") + "://marctowler.co.uk/piwik/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript';
g.defer=true; g.async=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="https://www.marctowler.co.uk/piwik/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-37729517-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html> | MarcTowler/blog | archives.php | PHP | mit | 6,940 |
<?php
namespace AwsUpload\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;
abstract class BaseTestCase extends TestCase
{
protected $main_external;
protected $main_aws_home;
/**
* The directory that contain the AWSUPLOAD_HOME.
*
* Foreach test we want this folder clean.
* So, each time we use the class to make it unique.
*
* @var string
*/
protected $aws_home;
/**
* The directory to simulate outside of AWSUPLOAD_HOME.
*
* @var string
*/
protected $external;
/**
* {@inheritdoc}
*/
public function setUp()
{
$uid = strtolower(get_class($this));
$uid = str_replace('\\', '-', $uid);
$this->main_aws_home = __DIR__ . '/../../aws_upload/';
$this->aws_home = $this->main_aws_home . $uid;
putenv("AWSUPLOAD_HOME=" . $this->aws_home);
$this->main_external = __DIR__ . '/../../external/';
$this->external = $this->main_external . $uid;
$filesystem = new Filesystem();
$filesystem->mkdir($this->aws_home);
$filesystem->mkdir($this->external);
}
/**
* {@inheritdoc}
*/
public function tearDown()
{
unset($_ENV['AWSUPLOAD_HOME']);
$filesystem = new Filesystem();
$filesystem->remove($this->main_aws_home);
$filesystem->remove($this->main_external);
}
/**
* Clear the $_SERVER['argv'] array
*/
public static function clearArgv()
{
$_SERVER['argv'] = array();
$_SERVER['argc'] = 0;
}
/**
* Add one or more element(s) at the end of the $_SERVER['argv'] array
*
* @param string[] $args Value to add to the argv array.
*/
public static function pushToArgv($args)
{
if (is_string($args)) {
$args = explode(' ', $args);
}
foreach ($args as $arg) {
array_push($_SERVER['argv'], $arg);
}
$_SERVER['argc'] += count($args);
}
}
| borracciaBlu/aws-upload | tests/AwsUpload/BaseTestCase.php | PHP | mit | 2,048 |
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "TimeOutException.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
********************************* TimeOutException *****************************
********************************************************************************
*/
#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
const TimeOutException TimeOutException::kThe;
#endif
TimeOutException::TimeOutException ()
: TimeOutException{L"Timeout Expired"sv}
{
}
TimeOutException::TimeOutException (error_code ec)
: TimeOutException{ec, L"Timeout Expired"sv}
{
}
TimeOutException::TimeOutException (const Characters::String& message)
: TimeOutException{make_error_code (errc::timed_out), message}
{
}
/*
********************************************************************************
************************ Execution::ThrowTimeOutException **********************
********************************************************************************
*/
void Execution::ThrowTimeOutException ()
{
Throw (TimeOutException::kThe);
}
| SophistSolutions/Stroika | Library/Sources/Stroika/Foundation/Execution/TimeOutException.cpp | C++ | mit | 1,274 |
import { Component } from '@angular/core';
@Component({
templateUrl: './login.html'
})
export class Login {
}
| aikin/ghsm | app/src/pages/login/login.ts | TypeScript | mit | 117 |
class AppointmentCanceledNotification
attr_accessor :appointment
def initialize(appointment)
@appointment = appointment
end
def message
{
message: 'Seu horário foi cancelado :/',
data: {
appointment_id: appointment.id,
type: 'appointment_canceled'
}
}
end
def channel
"Customer_#{appointment.customer.token}"
end
end
| BarberHour/barber-hour-api | app/notifications/appointment_canceled_notification.rb | Ruby | mit | 385 |
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("uWebshop.DataAccess")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("uWebshop")]
[assembly: AssemblyProduct("uWebshop.DataAccess")]
[assembly: AssemblyCopyright("Copyright © uWebshop 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("df6aa836-1eb3-47b5-ac04-746221102822")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.6.1.0")]
[assembly: AssemblyFileVersion("2.6.1.0")]
| uWebshop/uWebshop-Releases | Core/uWebshop.DataAccess/Properties/AssemblyInfo.cs | C# | mit | 1,269 |
Liquid::Template.register_filter(YetAnotherTagCloud)
| vaudoc/jk | vendor/plugins/yet_another_tag_cloud/init.rb | Ruby | mit | 53 |
var searchData=
[
['bullet_2ecpp',['bullet.cpp',['../bullet_8cpp.html',1,'']]],
['bullet_2eh',['bullet.h',['../bullet_8h.html',1,'']]]
];
| SineJunky/ascii-game | ASCII-Game/docs/html/search/files_62.js | JavaScript | mit | 142 |
import React, { Component } from "react";
import { browserHistory, Link } from "react-router";
import update from "react-addons-update";
class AuthoredPost extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: {
display: "block"
},
post: {}
};
}
handleChange(event) {
let newState = update(this.state, {
$merge: {
[event.target.name]: event.target.value
}
});
this.setState(newState);
}
handleDelete() {
fetch(`http://localhost:3000/posts/${this.props.id}/${this.props.user_id}`, {
method: "DELETE"
})
.then(() => {
this.setState({ isVisible: { display: "none"}});
browserHistory.push('/dashboard');
})
.catch((err) => {
console.log("ERROR:", err);
});
}
render() {
return(
<div key={this.props.id} style={this.state.isVisible}>
<div className="authored_posts">
<h3>{this.props.title}</h3>
<img src={this.props.image_url} width="250px" />
<p>{this.props.post_text}</p>
<div className="source-category">
<p><a href={this.props.source_url} target="_blank">Source URL</a></p>
<p className="dashboard-category-icon">{this.props.category}</p>
</div>
<div className="dashboard-button-container">
<Link to={`/${this.props.id}/edit`}>
<button>Edit Post</button>
</Link>
<Link to="/dashboard">
<button onClick={this.handleDelete.bind(this)}>×</button>
</Link>
</div>
</div>
</div>
);
}
}
export default AuthoredPost;
| jeremypross/lcjr-frontend | src/components/Dashboard/AuthoredPost.js | JavaScript | mit | 1,691 |
<?php
namespace Sokil\State;
class Transition
{
private $name;
/**
* @var string
*/
private $initialStateName;
/**
* @var string
*/
private $resultingStateName;
/**
* @var callable which checks if transition acceptable
*/
private $acceptConditionCallable;
/**
* @var array Transition metadata
*/
private $metadata;
public function __construct($name, $initialState, $resultingState, callable $acceptConditionCallable = null, array $metadata = [])
{
$this->name = $name;
$this->initialStateName = $initialState;
$this->resultingStateName = $resultingState;
$this->acceptConditionCallable = $acceptConditionCallable;
$this->metadata = $metadata;
}
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getInitialStateName()
{
return $this->initialStateName;
}
/**
* @return string
*/
public function getResultingStateName()
{
return $this->resultingStateName;
}
public function isAcceptable()
{
if (!$this->acceptConditionCallable) {
return true;
}
return call_user_func($this->acceptConditionCallable);
}
public function getMetadata($key = null)
{
if (!$key) {
return $this->metadata;
}
if (!isset($this->metadata[$key])) {
return null;
}
return $this->metadata[$key];
}
public function __toString()
{
return $this->name;
}
}
| sokil/php-state | src/Transition.php | PHP | mit | 1,636 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// タックル それは 自機と同じ当たり判定を持った自爆攻撃
public class Tackle : BulletBase
{
[SerializeField] GameObject hitEffectPrefab;
void Start()
{
OnStart();
}
void Update()
{
if (shooter == null)
{
Destroy(this.gameObject);
return;
}
if (trans == null) return;
// 敵と同じ位置に移動する
trans.localPosition = shooter.localPosition;
}
void OnTriggerEnter2D(Collider2D other)
{
if (hitEffectPrefab != null)
{
var go = GameObject.Instantiate(hitEffectPrefab);
var effectTrans = go.transform;
effectTrans.SetParent(transform.parent); // 弾は消えるので親オブジェクトに関連付ける
effectTrans.localPosition = transform.localPosition;
effectTrans.localScale = Vector3.one;
}
HitSE.Play();
Destroy(this.gameObject);
Hp hp = shooter.gameObject.GetComponent<Hp> ();
if (hp != null)
hp.OnDamage(hp.MaxHP);
else
Destroy(shooter.gameObject);
}
}
| enpel/ggj2017-deliciousset | UnityProject/Assets/Scripts/Battle/Tackle.cs | C# | mit | 1,051 |
dependsOn("dependencyCircular2.js");
| SoloVid/grunt-ordered-concat | test/fixtures/dependencyCircular1.js | JavaScript | mit | 37 |
import {
FETCH_POSTS_REQUEST_VIDEO, FETCH_POSTS_SUCCESS_VIDEO,
FETCH_POSTS_FAILURE_VIDEO,
} from '../actions/VideoAction';
const initialState = {
videoAssets: [],
isFetching: false,
failure: false,
}
const fetchVideoAssets = (state = initialState, action) => {
switch (action.type) {
case FETCH_POSTS_REQUEST_VIDEO:
return { ...state, isFetching: true };
case FETCH_POSTS_SUCCESS_VIDEO:
return { ...state, isFetching: false, videoAssets: action.videoAssets };
case FETCH_POSTS_FAILURE_VIDEO:
return { ...state, failure: true };
default:
return state;
}
}
export default fetchVideoAssets;
| sikamedia/idol | src/reducers/VideoReducer.js | JavaScript | mit | 649 |
import math
d = int(input())
for _ in range(d):
t, a, b, c = [int(x) for x in input().split()]
l = [a, b, c]
l.sort()
if l[0] + l[1] < l[2]:
l[2] = l[0] + l[1]
print(min(t, math.floor((l[0]+l[1]+l[2])/2)))
| madeinqc/IEEEXtreme9.0 | 06-tacostand-moderate/main.py | Python | mit | 238 |
const React = require('react');
export default ({onQuantityChange, productId}) => (
<div className="product__element">
<img />
<input className="quantity"
onChange={(e) => {
e.preventDefault();
const inputValue = e.target.value;
onQuantityChange({
id: productId,
// in case of manual deleted input number (value === '')
quantity: inputValue !== '' ? parseInt(inputValue, 10) : 0
});
}}
type="number" min="1" defaultValue="1" />
<img />
</div>
);
| unam3/oshop_i | src/components/Quantity/Quantity.js | JavaScript | mit | 545 |
package com.devotedmc.ExilePearl.util;
import java.util.ArrayList;
/**
* String List class with an override for seeing if
* it contains a string value, ignoring case
* @author Gordon
*
*/
@SuppressWarnings("serial")
public class StringListIgnoresCase extends ArrayList<String> {
@Override
public boolean contains(Object o) {
String paramStr = (String)o;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return true;
}
return false;
}
}
| DevotedMC/ExilePearl | src/main/java/com/devotedmc/ExilePearl/util/StringListIgnoresCase.java | Java | mit | 506 |
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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. //
// ======================================================================== //
#include "scene.h"
#include "../bvh/bvh4_factory.h"
#include "../bvh/bvh8_factory.h"
namespace embree
{
/* error raising rtcIntersect and rtcOccluded functions */
void missing_rtcCommit() { throw_RTCError(RTC_INVALID_OPERATION,"scene got not committed"); }
void invalid_rtcIntersect1() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect and rtcOccluded not enabled"); }
void invalid_rtcIntersect4() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect4 and rtcOccluded4 not enabled"); }
void invalid_rtcIntersect8() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect8 and rtcOccluded8 not enabled"); }
void invalid_rtcIntersect16() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect16 and rtcOccluded16 not enabled"); }
void invalid_rtcIntersectN() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersectN and rtcOccludedN not enabled"); }
Scene::Scene (Device* device, RTCSceneFlags sflags, RTCAlgorithmFlags aflags)
: Accel(AccelData::TY_UNKNOWN),
device(device),
commitCounter(0),
commitCounterSubdiv(0),
numMappedBuffers(0),
flags(sflags), aflags(aflags),
needTriangleIndices(false), needTriangleVertices(false),
needQuadIndices(false), needQuadVertices(false),
needBezierIndices(false), needBezierVertices(false),
needLineIndices(false), needLineVertices(false),
needSubdivIndices(false), needSubdivVertices(false),
is_build(false), modified(true),
progressInterface(this), progress_monitor_function(nullptr), progress_monitor_ptr(nullptr), progress_monitor_counter(0),
numIntersectionFilters1(0), numIntersectionFilters4(0), numIntersectionFilters8(0), numIntersectionFilters16(0), numIntersectionFiltersN(0)
{
#if defined(TASKING_INTERNAL)
scheduler = nullptr;
#else
group = new tbb::task_group;
#endif
intersectors = Accel::Intersectors(missing_rtcCommit);
if (device->scene_flags != -1)
flags = (RTCSceneFlags) device->scene_flags;
if (aflags & RTC_INTERPOLATE) {
needTriangleIndices = true;
needQuadIndices = true;
needBezierIndices = true;
needLineIndices = true;
//needSubdivIndices = true; // not required for interpolation
needTriangleVertices = true;
needQuadVertices = true;
needBezierVertices = true;
needLineVertices = true;
needSubdivVertices = true;
}
createTriangleAccel();
createTriangleMBAccel();
createQuadAccel();
createQuadMBAccel();
createSubdivAccel();
createHairAccel();
createHairMBAccel();
createLineAccel();
createLineMBAccel();
#if defined(EMBREE_GEOMETRY_TRIANGLES)
accels.add(device->bvh4_factory->BVH4InstancedBVH4Triangle4ObjectSplit(this));
#endif
#if defined(EMBREE_GEOMETRY_USER)
accels.add(device->bvh4_factory->BVH4UserGeometry(this)); // has to be the last as the instID field of a hit instance is not invalidated by other hit geometry
accels.add(device->bvh4_factory->BVH4UserGeometryMB(this)); // has to be the last as the instID field of a hit instance is not invalidated by other hit geometry
#endif
}
void Scene::createTriangleAccel()
{
#if defined(EMBREE_GEOMETRY_TRIANGLES)
if (device->tri_accel == "default")
{
if (isStatic()) {
int mode = 2*(int)isCompact() + 1*(int)isRobust();
switch (mode) {
case /*0b00*/ 0:
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
{
if (isHighQuality())
{
/* new spatial split builder is now active per default */
accels.add(device->bvh8_factory->BVH8Triangle4SpatialSplit(this));
}
else
accels.add(device->bvh8_factory->BVH8Triangle4ObjectSplit(this));
}
else
#endif
{
if (isHighQuality())
{
/* new spatial split builder is now active per default */
accels.add(device->bvh4_factory->BVH4Triangle4SpatialSplit(this));
}
else accels.add(device->bvh4_factory->BVH4Triangle4ObjectSplit(this));
}
break;
case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Triangle4vObjectSplit(this)); break;
case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Triangle4iObjectSplit(this)); break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Triangle4iObjectSplit(this)); break;
}
}
else
{
int mode = 2*(int)isCompact() + 1*(int)isRobust();
switch (mode) {
case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4Triangle4Twolevel(this)); break;
case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Triangle4vTwolevel(this)); break;
case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Triangle4iTwolevel(this)); break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Triangle4iTwolevel(this)); break;
}
}
}
else if (device->tri_accel == "bvh4.triangle4") accels.add(device->bvh4_factory->BVH4Triangle4(this));
else if (device->tri_accel == "bvh4.triangle4v") accels.add(device->bvh4_factory->BVH4Triangle4v(this));
else if (device->tri_accel == "bvh4.triangle4i") accels.add(device->bvh4_factory->BVH4Triangle4i(this));
#if defined (__TARGET_AVX__)
else if (device->tri_accel == "bvh8.triangle4") accels.add(device->bvh8_factory->BVH8Triangle4(this));
else if (device->tri_accel == "qbvh8.triangle4i") accels.add(device->bvh8_factory->BVH8QuantizedTriangle4i(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown triangle acceleration structure "+device->tri_accel);
#endif
}
void Scene::createQuadAccel()
{
#if defined(EMBREE_GEOMETRY_QUADS)
if (device->quad_accel == "default")
{
int mode = 2*(int)isCompact() + 1*(int)isRobust();
switch (mode) {
case /*0b00*/ 0:
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
accels.add(device->bvh8_factory->BVH8Quad4v(this));
else
#endif
accels.add(device->bvh4_factory->BVH4Quad4v(this));
break;
case /*0b01*/ 1:
#if defined (__TARGET_AVX__) && 1
if (device->hasISA(AVX))
accels.add(device->bvh8_factory->BVH8Quad4i(this));
else
#endif
accels.add(device->bvh4_factory->BVH4Quad4i(this));
break;
case /*0b10*/ 2:
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
{
// FIXME: reduce performance overhead of 10% compared to uncompressed bvh8
// if (isExclusiveIntersect1Mode())
// accels.add(device->bvh8_factory->BVH8QuantizedQuad4i(this));
// else
accels.add(device->bvh8_factory->BVH8Quad4i(this));
}
else
#endif
{
accels.add(device->bvh4_factory->BVH4Quad4i(this));
}
break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Quad4i(this)); break;
}
}
else if (device->quad_accel == "bvh4.quad4v") accels.add(device->bvh4_factory->BVH4Quad4v(this));
else if (device->quad_accel == "bvh4.quad4i") accels.add(device->bvh4_factory->BVH4Quad4i(this));
else if (device->quad_accel == "qbvh4.quad4i") accels.add(device->bvh4_factory->BVH4QuantizedQuad4i(this));
#if defined (__TARGET_AVX__)
else if (device->quad_accel == "bvh8.quad4v") accels.add(device->bvh8_factory->BVH8Quad4v(this));
else if (device->quad_accel == "bvh8.quad4i") accels.add(device->bvh8_factory->BVH8Quad4i(this));
else if (device->quad_accel == "qbvh8.quad4i") accels.add(device->bvh8_factory->BVH8QuantizedQuad4i(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown quad acceleration structure "+device->quad_accel);
#endif
}
void Scene::createQuadMBAccel()
{
#if defined(EMBREE_GEOMETRY_QUADS)
if (device->quad_accel_mb == "default")
{
int mode = 2*(int)isCompact() + 1*(int)isRobust();
switch (mode) {
case /*0b00*/ 0:
case /*0b01*/ 1:
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
accels.add(device->bvh8_factory->BVH8Quad4iMB(this));
else
#endif
accels.add(device->bvh4_factory->BVH4Quad4iMB(this));
break;
case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Quad4iMB(this)); break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Quad4iMB(this)); break;
}
}
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown quad acceleration structure "+device->quad_accel);
#endif
}
void Scene::createTriangleMBAccel()
{
#if defined(EMBREE_GEOMETRY_TRIANGLES)
if (device->tri_accel_mb == "default")
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
{
accels.add(device->bvh8_factory->BVH8Triangle4vMB(this));
}
else
#endif
{
accels.add(device->bvh4_factory->BVH4Triangle4vMB(this));
}
}
else if (device->tri_accel_mb == "bvh4.triangle4vmb") accels.add(device->bvh4_factory->BVH4Triangle4vMB(this));
#if defined (__TARGET_AVX__)
else if (device->tri_accel_mb == "bvh8.triangle4vmb") accels.add(device->bvh8_factory->BVH8Triangle4vMB(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur triangle acceleration structure "+device->tri_accel_mb);
#endif
}
void Scene::createHairAccel()
{
#if defined(EMBREE_GEOMETRY_HAIR)
if (device->hair_accel == "default")
{
int mode = 2*(int)isCompact() + 1*(int)isRobust();
if (isStatic())
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX2)) // only enable on HSW machines, for SNB this codepath is slower
{
switch (mode) {
case /*0b00*/ 0: accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,isHighQuality())); break;
case /*0b01*/ 1: accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,isHighQuality())); break;
case /*0b10*/ 2: accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,isHighQuality())); break;
case /*0b11*/ 3: accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,isHighQuality())); break;
}
}
else
#endif
{
switch (mode) {
case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,isHighQuality())); break;
case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,isHighQuality())); break;
case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,isHighQuality())); break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,isHighQuality())); break;
}
}
}
else
{
switch (mode) {
case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4Bezier1v(this)); break;
case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Bezier1v(this)); break;
case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Bezier1i(this)); break;
case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Bezier1i(this)); break;
}
}
}
else if (device->hair_accel == "bvh4.bezier1v" ) accels.add(device->bvh4_factory->BVH4Bezier1v(this));
else if (device->hair_accel == "bvh4.bezier1i" ) accels.add(device->bvh4_factory->BVH4Bezier1i(this));
else if (device->hair_accel == "bvh4obb.bezier1v" ) accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,false));
else if (device->hair_accel == "bvh4obb.bezier1i" ) accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,false));
#if defined (__TARGET_AVX__)
else if (device->hair_accel == "bvh8obb.bezier1v" ) accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,false));
else if (device->hair_accel == "bvh8obb.bezier1i" ) accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,false));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown hair acceleration structure "+device->hair_accel);
#endif
}
void Scene::createHairMBAccel()
{
#if defined(EMBREE_GEOMETRY_HAIR)
if (device->hair_accel_mb == "default")
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX2)) // only enable on HSW machines, on SNB this codepath is slower
{
accels.add(device->bvh8_factory->BVH8OBBBezier1iMB(this,false));
}
else
#endif
{
accels.add(device->bvh4_factory->BVH4OBBBezier1iMB(this,false));
}
}
else if (device->hair_accel_mb == "bvh4obb.bezier1imb") accels.add(device->bvh4_factory->BVH4OBBBezier1iMB(this,false));
#if defined (__TARGET_AVX__)
else if (device->hair_accel_mb == "bvh8obb.bezier1imb") accels.add(device->bvh8_factory->BVH8OBBBezier1iMB(this,false));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur hair acceleration structure "+device->tri_accel_mb);
#endif
}
void Scene::createLineAccel()
{
#if defined(EMBREE_GEOMETRY_LINES)
if (device->line_accel == "default")
{
if (isStatic())
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX) && !isCompact())
accels.add(device->bvh8_factory->BVH8Line4i(this));
else
#endif
accels.add(device->bvh4_factory->BVH4Line4i(this));
}
else
{
accels.add(device->bvh4_factory->BVH4Line4iTwolevel(this));
}
}
else if (device->line_accel == "bvh4.line4i") accels.add(device->bvh4_factory->BVH4Line4i(this));
#if defined (__TARGET_AVX__)
else if (device->line_accel == "bvh8.line4i") accels.add(device->bvh8_factory->BVH8Line4i(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown line segment acceleration structure "+device->line_accel);
#endif
}
void Scene::createLineMBAccel()
{
#if defined(EMBREE_GEOMETRY_LINES)
if (device->line_accel_mb == "default")
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX) && !isCompact())
accels.add(device->bvh8_factory->BVH8Line4iMB(this));
else
#endif
accels.add(device->bvh4_factory->BVH4Line4iMB(this));
}
else if (device->line_accel_mb == "bvh4.line4imb") accels.add(device->bvh4_factory->BVH4Line4iMB(this));
#if defined (__TARGET_AVX__)
else if (device->line_accel_mb == "bvh8.line4imb") accels.add(device->bvh8_factory->BVH8Line4iMB(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur line segment acceleration structure "+device->line_accel_mb);
#endif
}
void Scene::createSubdivAccel()
{
#if defined(EMBREE_GEOMETRY_SUBDIV)
if (device->subdiv_accel == "default")
{
if (isIncoherent(flags) && isStatic())
{
#if defined (__TARGET_AVX__)
if (device->hasISA(AVX))
accels.add(device->bvh8_factory->BVH8SubdivGridEager(this));
else
#endif
accels.add(device->bvh4_factory->BVH4SubdivGridEager(this));
}
else
accels.add(device->bvh4_factory->BVH4SubdivPatch1Cached(this));
}
else if (device->subdiv_accel == "bvh4.subdivpatch1cached") accels.add(device->bvh4_factory->BVH4SubdivPatch1Cached(this));
else if (device->subdiv_accel == "bvh4.grid.eager" ) accels.add(device->bvh4_factory->BVH4SubdivGridEager(this));
#if defined (__TARGET_AVX__)
else if (device->subdiv_accel == "bvh8.grid.eager" ) accels.add(device->bvh8_factory->BVH8SubdivGridEager(this));
#endif
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown subdiv accel "+device->subdiv_accel);
#endif
}
Scene::~Scene ()
{
for (size_t i=0; i<geometries.size(); i++)
delete geometries[i];
#if TASKING_TBB
delete group; group = nullptr;
#endif
}
void Scene::clear() {
}
unsigned Scene::newUserGeometry (size_t items, size_t numTimeSteps)
{
Geometry* geom = new UserGeometry(this,items,numTimeSteps);
return geom->id;
}
unsigned Scene::newInstance (Scene* scene, size_t numTimeSteps)
{
Geometry* geom = new Instance(this,scene,numTimeSteps);
return geom->id;
}
unsigned Scene::newGeometryInstance (Geometry* geom) {
Geometry* instance = new GeometryInstance(this,geom);
return instance->id;
}
unsigned Scene::newTriangleMesh (RTCGeometryFlags gflags, size_t numTriangles, size_t numVertices, size_t numTimeSteps)
{
if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) {
throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries");
return -1;
}
if (numTimeSteps == 0 || numTimeSteps > 2) {
throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported");
return -1;
}
Geometry* geom = new TriangleMesh(this,gflags,numTriangles,numVertices,numTimeSteps);
return geom->id;
}
unsigned Scene::newQuadMesh (RTCGeometryFlags gflags, size_t numQuads, size_t numVertices, size_t numTimeSteps)
{
if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) {
throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries");
return -1;
}
if (numTimeSteps == 0 || numTimeSteps > 2) {
throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported");
return -1;
}
Geometry* geom = new QuadMesh(this,gflags,numQuads,numVertices,numTimeSteps);
return geom->id;
}
unsigned Scene::newSubdivisionMesh (RTCGeometryFlags gflags, size_t numFaces, size_t numEdges, size_t numVertices, size_t numEdgeCreases, size_t numVertexCreases, size_t numHoles, size_t numTimeSteps)
{
if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) {
throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries");
return -1;
}
if (numTimeSteps == 0 || numTimeSteps > 2) {
throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported");
return -1;
}
Geometry* geom = nullptr;
#if defined(__TARGET_AVX__)
if (device->hasISA(AVX))
geom = new SubdivMeshAVX(this,gflags,numFaces,numEdges,numVertices,numEdgeCreases,numVertexCreases,numHoles,numTimeSteps);
else
#endif
geom = new SubdivMesh(this,gflags,numFaces,numEdges,numVertices,numEdgeCreases,numVertexCreases,numHoles,numTimeSteps);
return geom->id;
}
unsigned Scene::newBezierCurves (BezierCurves::SubType subtype, RTCGeometryFlags gflags, size_t numCurves, size_t numVertices, size_t numTimeSteps)
{
if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) {
throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries");
return -1;
}
if (numTimeSteps == 0 || numTimeSteps > 2) {
throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported");
return -1;
}
Geometry* geom = new BezierCurves(this,subtype,gflags,numCurves,numVertices,numTimeSteps);
return geom->id;
}
unsigned Scene::newLineSegments (RTCGeometryFlags gflags, size_t numSegments, size_t numVertices, size_t numTimeSteps)
{
if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) {
throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries");
return -1;
}
if (numTimeSteps == 0 || numTimeSteps > 2) {
throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported");
return -1;
}
Geometry* geom = new LineSegments(this,gflags,numSegments,numVertices,numTimeSteps);
return geom->id;
}
unsigned Scene::add(Geometry* geometry)
{
Lock<SpinLock> lock(geometriesMutex);
if (usedIDs.size()) {
unsigned id = usedIDs.back();
usedIDs.pop_back();
geometries[id] = geometry;
return id;
} else {
geometries.push_back(geometry);
return unsigned(geometries.size()-1);
}
}
void Scene::deleteGeometry(size_t geomID)
{
Lock<SpinLock> lock(geometriesMutex);
if (isStatic())
throw_RTCError(RTC_INVALID_OPERATION,"rtcDeleteGeometry cannot get called in static scenes");
if (geomID >= geometries.size())
throw_RTCError(RTC_INVALID_OPERATION,"invalid geometry ID");
Geometry* geometry = geometries[geomID];
if (geometry == nullptr)
throw_RTCError(RTC_INVALID_OPERATION,"invalid geometry");
geometry->disable();
accels.deleteGeometry(unsigned(geomID));
usedIDs.push_back(unsigned(geomID));
geometries[geomID] = nullptr;
delete geometry;
}
void Scene::updateInterface()
{
/* update bounds */
is_build = true;
bounds = accels.bounds;
intersectors = accels.intersectors;
/* enable only algorithms choosen by application */
if ((aflags & RTC_INTERSECT_STREAM) == 0)
{
intersectors.intersectorN = Accel::IntersectorN(&invalid_rtcIntersectN);
if ((aflags & RTC_INTERSECT1) == 0) intersectors.intersector1 = Accel::Intersector1(&invalid_rtcIntersect1);
if ((aflags & RTC_INTERSECT4) == 0) intersectors.intersector4 = Accel::Intersector4(&invalid_rtcIntersect4);
if ((aflags & RTC_INTERSECT8) == 0) intersectors.intersector8 = Accel::Intersector8(&invalid_rtcIntersect8);
if ((aflags & RTC_INTERSECT16) == 0) intersectors.intersector16 = Accel::Intersector16(&invalid_rtcIntersect16);
}
/* update commit counter */
commitCounter++;
}
void Scene::build_task ()
{
progress_monitor_counter = 0;
/* select fast code path if no intersection filter is present */
accels.select(numIntersectionFiltersN+numIntersectionFilters4,
numIntersectionFiltersN+numIntersectionFilters8,
numIntersectionFiltersN+numIntersectionFilters16,
numIntersectionFiltersN);
/* build all hierarchies of this scene */
accels.build(0,0);
/* make static geometry immutable */
if (isStatic())
{
accels.immutable();
for (size_t i=0; i<geometries.size(); i++)
if (geometries[i]) geometries[i]->immutable();
}
/* clear modified flag */
for (size_t i=0; i<geometries.size(); i++)
{
Geometry* geom = geometries[i];
if (!geom) continue;
if (geom->isEnabled()) geom->clearModified(); // FIXME: should builders do this?
}
updateInterface();
if (device->verbosity(2)) {
std::cout << "created scene intersector" << std::endl;
accels.print(2);
std::cout << "selected scene intersector" << std::endl;
intersectors.print(2);
}
setModified(false);
}
#if defined(TASKING_INTERNAL)
void Scene::build (size_t threadIndex, size_t threadCount)
{
Lock<MutexSys> buildLock(buildMutex,false);
/* allocates own taskscheduler for each build */
Ref<TaskScheduler> scheduler = nullptr;
{
Lock<MutexSys> lock(schedulerMutex);
scheduler = this->scheduler;
if (scheduler == null) {
buildLock.lock();
this->scheduler = scheduler = new TaskScheduler;
}
}
/* worker threads join build */
if (!buildLock.isLocked()) {
scheduler->join();
return;
}
/* wait for all threads in rtcCommitThread mode */
if (threadCount != 0)
scheduler->wait_for_threads(threadCount);
/* fast path for unchanged scenes */
if (!isModified()) {
scheduler->spawn_root([&]() { this->scheduler = nullptr; }, 1, threadCount == 0);
return;
}
/* report error if scene not ready */
if (!ready()) {
scheduler->spawn_root([&]() { this->scheduler = nullptr; }, 1, threadCount == 0);
throw_RTCError(RTC_INVALID_OPERATION,"not all buffers are unmapped");
}
/* initiate build */
try {
scheduler->spawn_root([&]() { build_task(); this->scheduler = nullptr; }, 1, threadCount == 0);
}
catch (...) {
accels.clear();
updateInterface();
throw;
}
}
#endif
#if defined(TASKING_TBB)
void Scene::build (size_t threadIndex, size_t threadCount)
{
/* let threads wait for build to finish in rtcCommitThread mode */
if (threadCount != 0) {
if (threadIndex > 0) {
group_barrier.wait(threadCount); // FIXME: use barrier that waits in condition
group->wait();
return;
}
}
/* try to obtain build lock */
Lock<MutexSys> lock(buildMutex,buildMutex.try_lock());
/* join hierarchy build */
if (!lock.isLocked()) {
#if USE_TASK_ARENA
device->arena->execute([&]{ group->wait(); });
#else
group->wait();
#endif
while (!buildMutex.try_lock()) {
__pause_cpu();
yield();
#if USE_TASK_ARENA
device->arena->execute([&]{ group->wait(); });
#else
group->wait();
#endif
}
buildMutex.unlock();
return;
}
if (!isModified()) {
if (threadCount) group_barrier.wait(threadCount);
return;
}
if (!ready()) {
if (threadCount) group_barrier.wait(threadCount);
throw_RTCError(RTC_INVALID_OPERATION,"not all buffers are unmapped");
return;
}
/* for best performance set FTZ and DAZ flags in the MXCSR control and status register */
unsigned int mxcsr = _mm_getcsr();
_mm_setcsr(mxcsr | /* FTZ */ (1<<15) | /* DAZ */ (1<<6));
try {
#if TBB_INTERFACE_VERSION_MAJOR < 8
tbb::task_group_context ctx( tbb::task_group_context::isolated, tbb::task_group_context::default_traits);
#else
tbb::task_group_context ctx( tbb::task_group_context::isolated, tbb::task_group_context::default_traits | tbb::task_group_context::fp_settings );
#endif
//ctx.set_priority(tbb::priority_high);
#if USE_TASK_ARENA
device->arena->execute([&]{
#endif
group->run([&]{
tbb::parallel_for (size_t(0), size_t(1), size_t(1), [&] (size_t) { build_task(); }, ctx);
});
if (threadCount) group_barrier.wait(threadCount);
group->wait();
#if USE_TASK_ARENA
});
#endif
/* reset MXCSR register again */
_mm_setcsr(mxcsr);
}
catch (...) {
/* reset MXCSR register again */
_mm_setcsr(mxcsr);
accels.clear();
updateInterface();
throw;
}
}
#endif
void Scene::write(std::ofstream& file)
{
int magick = 0x35238765LL;
file.write((char*)&magick,sizeof(magick));
size_t numGroups = size();
file.write((char*)&numGroups,sizeof(numGroups));
for (size_t i=0; i<numGroups; i++) {
if (geometries[i]) geometries[i]->write(file);
else { int type = -1; file.write((char*)&type,sizeof(type)); }
}
}
void Scene::setProgressMonitorFunction(RTCProgressMonitorFunc func, void* ptr)
{
static MutexSys mutex;
mutex.lock();
progress_monitor_function = func;
progress_monitor_ptr = ptr;
mutex.unlock();
}
void Scene::progressMonitor(double dn)
{
if (progress_monitor_function) {
size_t n = size_t(dn) + progress_monitor_counter.fetch_add(size_t(dn));
if (!progress_monitor_function(progress_monitor_ptr, n / (double(numPrimitives())))) {
throw_RTCError(RTC_CANCELLED,"progress monitor forced termination");
}
}
}
}
| 01alchemist/x-ray-kernel | src/embree/kernels/common/scene.cpp | C++ | mit | 28,173 |