code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
package akka.dispatch
import com.typesafe.config.Config
import java.util.concurrent.ExecutorService
class EventLoopExecutorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends ExecutorServiceConfigurator(config, prerequisites) {
def createExecutorServiceFactory(id: String): ExecutorServiceFactory =
new ExecutorServiceFactory {
def createExecutorService: ExecutorService = {
new EventLoopExecutor
}
}
}
| unicredit/akka.js | akka-js-actor/js/src/main/scala/akka/dispatch/EventLoopExecutorConfigurator.scala | Scala | bsd-3-clause | 461 |
/********************************************************************************
* *
* F o u r - W a y S p l i t t e r *
* *
*********************************************************************************
* Copyright (C) 1999,2002 by Jeroen van der Zijp. All Rights Reserved. *
*********************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*********************************************************************************
* $Id: FX4Splitter.h,v 1.21 2002/01/18 22:42:51 jeroen Exp $ *
********************************************************************************/
#ifndef FX4SPLITTER_H
#define FX4SPLITTER_H
#ifndef FXCOMPOSITE_H
#include "FXComposite.h"
#endif
// Splitter options
enum {
FOURSPLITTER_TRACKING = 0x00008000, // Track continuously during split
FOURSPLITTER_NORMAL = 0
};
/**
* The four-way splitter is a layout manager which manages
* four children like four panes in a window.
* You can use a four-way splitter for example in a CAD program
* where you may want to maintain three orthographic views, and
* one oblique view of a model.
* The four-way splitter allows interactive repartitioning of the
* panes by means of moving the central splitter bars.
* When the four-way splitter is itself resized, each child is
* proportionally resized, maintaining the same split-percentage.
* The four-way splitter widget sends a SEL_CHANGED to its target
* during the resizing of the panes; at the end of the resize interaction,
* it sends a SEL_COMMAND to signify that the resize operation is complete.
*/
class FXAPI FX4Splitter : public FXComposite {
FXDECLARE(FX4Splitter)
private:
FXint splitx; // Current x split
FXint splity; // Current y split
FXint expanded; // Panes which are expanded
FXint barsize; // Size of the splitter bar
FXint fhor; // Horizontal split fraction
FXint fver; // Vertical split fraction
FXint offx;
FXint offy;
FXuchar mode;
protected:
FX4Splitter();
FXuchar getMode(FXint x,FXint y);
void moveSplit(FXint x,FXint y);
void drawSplit(FXint x,FXint y);
void adjustLayout();
virtual void layout();
private:
FX4Splitter(const FX4Splitter&);
FX4Splitter &operator=(const FX4Splitter&);
public:
long onLeftBtnPress(FXObject*,FXSelector,void*);
long onLeftBtnRelease(FXObject*,FXSelector,void*);
long onMotion(FXObject*,FXSelector,void*);
long onFocusUp(FXObject*,FXSelector,void*);
long onFocusDown(FXObject*,FXSelector,void*);
long onFocusLeft(FXObject*,FXSelector,void*);
long onFocusRight(FXObject*,FXSelector,void*);
long onCmdExpand(FXObject*,FXSelector,void*);
long onUpdExpand(FXObject*,FXSelector,void*);
public:
enum {
ID_EXPAND_ALL=FXComposite::ID_LAST,
ID_EXPAND_TOPLEFT,
ID_EXPAND_TOPRIGHT,
ID_EXPAND_BOTTOMLEFT,
ID_EXPAND_BOTTOMRIGHT,
ID_LAST
};
public:
/// Create 4-way splitter, initially shown as four unexpanded panes
FX4Splitter(FXComposite* p,FXuint opts=FOURSPLITTER_NORMAL,FXint x=0,FXint y=0,FXint w=0,FXint h=0);
/// Create 4-way splitter, initially shown as four unexpanded panes; notifies target about size changes
FX4Splitter(FXComposite* p,FXObject* tgt,FXSelector sel,FXuint opts=FOURSPLITTER_NORMAL,FXint x=0,FXint y=0,FXint w=0,FXint h=0);
/// Get top left child, if any
FXWindow *getTopLeft() const;
/// Get top right child, if any
FXWindow *getTopRight() const;
/// Get bottom left child, if any
FXWindow *getBottomLeft() const;
/// Get bottom right child, if any
FXWindow *getBottomRight() const;
/// Get horizontal split fraction
FXint getHSplit() const { return fhor; }
/// Get vertical split fraction
FXint getVSplit() const { return fver; }
/// Change horizontal split fraction
void setHSplit(FXint s);
/// Change vertical split fraction
void setVSplit(FXint s);
/// Get default width
virtual FXint getDefaultWidth();
/// Get default height
virtual FXint getDefaultHeight();
/// Return current splitter style
FXuint getSplitterStyle() const;
/// Change splitter style
void setSplitterStyle(FXuint style);
/// Change splitter bar width
void setBarSize(FXint bs);
/// Get splitter bar width
FXint getBarSize() const { return barsize; }
/// Expand child (ex=0..3), or restore to 4-way split (ex=-1)
void setExpanded(FXint ex);
/// Get expanded child, or -1 if not expanded
FXint getExpanded() const { return expanded; }
/// Save to stream
virtual void save(FXStream& store) const;
/// Load from stream
virtual void load(FXStream& store);
};
#endif
| ldematte/beppe | include/fox/FX4Splitter.h | C | bsd-3-clause | 5,923 |
import os
import tempfile
from rest_framework import status
from hs_core.hydroshare import resource
from .base import HSRESTTestCase
class TestPublicResourceFlagsEndpoint(HSRESTTestCase):
def setUp(self):
super(TestPublicResourceFlagsEndpoint, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
self.rtype = 'GenericResource'
self.title = 'My Test resource'
res = resource.create_resource(self.rtype,
self.user,
self.title)
metadata_dict = [
{'description': {'abstract': 'My test abstract'}},
{'subject': {'value': 'sub-1'}}
]
file_one = "test1.txt"
open(file_one, "w").close()
self.file_one = open(file_one, "r")
self.txt_file_path = os.path.join(self.tmp_dir, 'text.txt')
txt = open(self.txt_file_path, 'w')
txt.write("Hello World\n")
txt.close()
self.rtype = 'GenericResource'
self.title = 'My Test resource'
res_two = resource.create_resource(self.rtype,
self.user,
self.title,
files=(self.file_one,),
metadata=metadata_dict)
self.pid = res.short_id
self.pid_two = res_two.short_id
self.resources_to_delete.append(self.pid)
self.resources_to_delete.append(self.pid_two)
def test_set_resource_flag_make_public(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_public"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
flag_url = "/hsapi/resource/%s/flag/" % self.pid_two
response = self.client.post(flag_url, {
"t": "make_public"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_private(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_private"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_discoverable(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid_two
response = self.client.post(flag_url, {
"t": "make_discoverable"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_not_discoverable(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_not_discoverable"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_not_shareable(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_not_shareable"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_shareable(self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_shareable"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
| RENCI/xDCIShare | hs_core/tests/api/rest/test_resource_flags.py | Python | bsd-3-clause | 3,544 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public function attributeLabels()
{
return [
'username' => 'Потребителско име',
'password' => 'Парола',
];
}
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Неправилно потребителско име или парола.');
}
}
}
/**
* Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findOne(['username' => $this->username]);
}
return $this->_user;
}
}
| AsenNikolov80/magnet | models/LoginForm.php | PHP | bsd-3-clause | 2,195 |
{-# LANGUAGE PatternSignatures #-}
module Main where
import GHC.Conc
import Control.Exception
import Foreign.StablePtr
import System.IO
import GHC.Conc.Sync (atomicallyWithIO)
inittvar :: STM (TVar String)
inittvar = newTVar "Hello world"
deadlock0 :: STM String
deadlock0 = retry
deadlock1 :: TVar String -> STM String
deadlock1 v1 = do s1 <- readTVar v1
retry
atomically_ x = atomicallyWithIO x (\x -> putStrLn "IO" >> return x)
-- Basic single-threaded operations with retry
main = do newStablePtr stdout
putStr "Before\n"
t1 <- atomically ( newTVar 0 )
-- Atomic block that contains a retry but does not perform it
r <- atomically_ ( do r1 <- readTVar t1
if (r1 /= 0) then retry else return ()
return r1 )
putStr ("Survived unused retry\n")
-- Atomic block that retries after reading 0 TVars
s1 <- Control.Exception.catch (atomically_ retry )
(\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n"))
putStr s1
-- Atomic block that retries after reading 1 TVar
t1 <- atomically ( inittvar )
s1 <- Control.Exception.catch (atomically_ ( deadlock1 t1 ))
(\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n"))
putStr s1
return ()
| mcschroeder/ghc | libraries/base/tests/Concurrent/stmio047.hs | Haskell | bsd-3-clause | 1,402 |
/*
* net.c
*
* Network implementation
* All network related functions are grouped here
*
* a Net::DNS like library for C
*
* (c) NLnet Labs, 2004-2006
*
* See the file LICENSE for the license
*/
#include <ldns/config.h>
#include <ldns/ldns.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_POLL
#include <poll.h>
#endif
ldns_status
ldns_send(ldns_pkt **result_packet, ldns_resolver *r, const ldns_pkt *query_pkt)
{
ldns_buffer *qb;
ldns_status result;
ldns_rdf *tsig_mac = NULL;
qb = ldns_buffer_new(LDNS_MIN_BUFLEN);
if (query_pkt && ldns_pkt_tsig(query_pkt)) {
tsig_mac = ldns_rr_rdf(ldns_pkt_tsig(query_pkt), 3);
}
if (!query_pkt ||
ldns_pkt2buffer_wire(qb, query_pkt) != LDNS_STATUS_OK) {
result = LDNS_STATUS_ERR;
} else {
result = ldns_send_buffer(result_packet, r, qb, tsig_mac);
}
ldns_buffer_free(qb);
return result;
}
/* code from rdata.c */
static struct sockaddr_storage *
ldns_rdf2native_sockaddr_storage_port(
const ldns_rdf *rd, uint16_t port, size_t *size)
{
struct sockaddr_storage *data;
struct sockaddr_in *data_in;
struct sockaddr_in6 *data_in6;
data = LDNS_MALLOC(struct sockaddr_storage);
if (!data) {
return NULL;
}
/* zero the structure for portability */
memset(data, 0, sizeof(struct sockaddr_storage));
switch(ldns_rdf_get_type(rd)) {
case LDNS_RDF_TYPE_A:
#ifndef S_SPLINT_S
data->ss_family = AF_INET;
#endif
data_in = (struct sockaddr_in*) data;
data_in->sin_port = (in_port_t)htons(port);
memcpy(&(data_in->sin_addr), ldns_rdf_data(rd), ldns_rdf_size(rd));
*size = sizeof(struct sockaddr_in);
return data;
case LDNS_RDF_TYPE_AAAA:
#ifndef S_SPLINT_S
data->ss_family = AF_INET6;
#endif
data_in6 = (struct sockaddr_in6*) data;
data_in6->sin6_port = (in_port_t)htons(port);
memcpy(&data_in6->sin6_addr, ldns_rdf_data(rd), ldns_rdf_size(rd));
*size = sizeof(struct sockaddr_in6);
return data;
default:
LDNS_FREE(data);
return NULL;
}
}
struct sockaddr_storage *
ldns_rdf2native_sockaddr_storage(
const ldns_rdf *rd, uint16_t port, size_t *size)
{
return ldns_rdf2native_sockaddr_storage_port(
rd, (port == 0 ? (uint16_t)LDNS_PORT : port), size);
}
/** best effort to set nonblocking */
static void
ldns_sock_nonblock(int sockfd)
{
#ifdef HAVE_FCNTL
int flag;
if((flag = fcntl(sockfd, F_GETFL)) != -1) {
flag |= O_NONBLOCK;
if(fcntl(sockfd, F_SETFL, flag) == -1) {
/* ignore error, continue blockingly */
}
}
#elif defined(HAVE_IOCTLSOCKET)
unsigned long on = 1;
if(ioctlsocket(sockfd, FIONBIO, &on) != 0) {
/* ignore error, continue blockingly */
}
#endif
}
/** best effort to set blocking */
static void
ldns_sock_block(int sockfd)
{
#ifdef HAVE_FCNTL
int flag;
if((flag = fcntl(sockfd, F_GETFL)) != -1) {
flag &= ~O_NONBLOCK;
if(fcntl(sockfd, F_SETFL, flag) == -1) {
/* ignore error, continue */
}
}
#elif defined(HAVE_IOCTLSOCKET)
unsigned long off = 0;
if(ioctlsocket(sockfd, FIONBIO, &off) != 0) {
/* ignore error, continue */
}
#endif
}
/** wait for a socket to become ready */
static int
ldns_sock_wait(int sockfd, struct timeval timeout, int write)
{
int ret;
#ifndef HAVE_POLL
#ifndef S_SPLINT_S
fd_set fds;
FD_ZERO(&fds);
FD_SET(FD_SET_T sockfd, &fds);
if(write)
ret = select(sockfd+1, NULL, &fds, NULL, &timeout);
else
ret = select(sockfd+1, &fds, NULL, NULL, &timeout);
#endif
#else
struct pollfd pfds[2];
memset(&pfds[0], 0, sizeof(pfds[0]) * 2);
pfds[0].fd = sockfd;
pfds[0].events = POLLIN|POLLERR;
if (write) {
pfds[0].events |= POLLOUT;
}
ret = poll(pfds, 1, (int)(timeout.tv_sec * 1000
+ timeout.tv_usec / 1000));
#endif
if(ret == 0)
/* timeout expired */
return 0;
else if(ret == -1)
/* error */
return 0;
return 1;
}
static int
ldns_tcp_connect_from(const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_STREAM,
IPPROTO_TCP)) == SOCK_INVALID) {
return -1;
}
#endif
if (from && bind(sockfd, (const struct sockaddr*)from, fromlen) == SOCK_INVALID){
close_socket(sockfd);
return -1;
}
/* perform nonblocking connect, to be able to wait with select() */
ldns_sock_nonblock(sockfd);
if (connect(sockfd, (struct sockaddr*)to, tolen) == SOCK_INVALID) {
#ifndef USE_WINSOCK
#ifdef EINPROGRESS
if(errno != EINPROGRESS) {
#else
if(1) {
#endif
close_socket(sockfd);
return -1;
}
#else /* USE_WINSOCK */
if(WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEWOULDBLOCK) {
close_socket(sockfd);
return -1;
}
#endif
/* error was only telling us that it would block */
}
/* wait(write) until connected or error */
while(1) {
int error = 0;
socklen_t len = (socklen_t)sizeof(error);
if(!ldns_sock_wait(sockfd, timeout, 1)) {
close_socket(sockfd);
return -1;
}
/* check if there is a pending error for nonblocking connect */
if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void*)&error,
&len) < 0) {
#ifndef USE_WINSOCK
error = errno; /* on solaris errno is error */
#else
error = WSAGetLastError();
#endif
}
#ifndef USE_WINSOCK
#if defined(EINPROGRESS) && defined(EWOULDBLOCK)
if(error == EINPROGRESS || error == EWOULDBLOCK)
continue; /* try again */
#endif
else if(error != 0) {
close_socket(sockfd);
/* error in errno for our user */
errno = error;
return -1;
}
#else /* USE_WINSOCK */
if(error == WSAEINPROGRESS)
continue;
else if(error == WSAEWOULDBLOCK)
continue;
else if(error != 0) {
close_socket(sockfd);
errno = error;
return -1;
}
#endif /* USE_WINSOCK */
/* connected */
break;
}
/* set the socket blocking again */
ldns_sock_block(sockfd);
return sockfd;
}
int
ldns_tcp_connect(const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
int s = ldns_tcp_connect_from(to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_tcp_connect2(const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
return ldns_tcp_connect_from(to, tolen, NULL, 0, timeout);
}
static int
ldns_tcp_bgsend_from(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
sockfd = ldns_tcp_connect_from(to, tolen, from, fromlen, timeout);
if (sockfd >= 0 && ldns_tcp_send_query(qbin, sockfd, to, tolen) == 0) {
close_socket(sockfd);
return -1;
}
return sockfd;
}
int
ldns_tcp_bgsend(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
int s = ldns_tcp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_tcp_bgsend2(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
return ldns_tcp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
}
/* keep in mind that in DNS tcp messages the first 2 bytes signal the
* amount data to expect
*/
static ldns_status
ldns_tcp_send_from(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout, size_t *answer_size)
{
int sockfd;
uint8_t *answer;
sockfd = ldns_tcp_bgsend_from(qbin, to, tolen, from, fromlen, timeout);
if (sockfd == -1) {
return LDNS_STATUS_ERR;
}
answer = ldns_tcp_read_wire_timeout(sockfd, answer_size, timeout);
close_socket(sockfd);
if (!answer) {
/* oops */
return LDNS_STATUS_NETWORK_ERR;
}
*result = answer;
return LDNS_STATUS_OK;
}
ldns_status
ldns_tcp_send(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout, size_t *answer_size)
{
return ldns_tcp_send_from(result, qbin,
to, tolen, NULL, 0, timeout, answer_size);
}
int
ldns_udp_connect(const struct sockaddr_storage *to, struct timeval ATTR_UNUSED(timeout))
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_DGRAM,
IPPROTO_UDP))
== SOCK_INVALID) {
return 0;
}
#endif
return sockfd;
}
int
ldns_udp_connect2(const struct sockaddr_storage *to, struct timeval ATTR_UNUSED(timeout))
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_DGRAM,
IPPROTO_UDP))
== SOCK_INVALID) {
return -1;
}
#endif
return sockfd;
}
static int
ldns_udp_bgsend_from(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
sockfd = ldns_udp_connect2(to, timeout);
if (sockfd == -1) {
return -1;
}
if (from && bind(sockfd, (const struct sockaddr*)from, fromlen) == -1){
close_socket(sockfd);
return -1;
}
if (ldns_udp_send_query(qbin, sockfd, to, tolen) == 0) {
close_socket(sockfd);
return -1;
}
return sockfd;
}
int
ldns_udp_bgsend(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout)
{
int s = ldns_udp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_udp_bgsend2(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout)
{
return ldns_udp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
}
static ldns_status
ldns_udp_send_from(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout, size_t *answer_size)
{
int sockfd;
uint8_t *answer;
sockfd = ldns_udp_bgsend_from(qbin, to, tolen, from, fromlen, timeout);
if (sockfd == -1) {
return LDNS_STATUS_SOCKET_ERROR;
}
/* wait for an response*/
if(!ldns_sock_wait(sockfd, timeout, 0)) {
close_socket(sockfd);
return LDNS_STATUS_NETWORK_ERR;
}
/* set to nonblocking, so if the checksum is bad, it becomes
* an EAGAIN error and the ldns_udp_send function does not block,
* but returns a 'NETWORK_ERROR' much like a timeout. */
ldns_sock_nonblock(sockfd);
answer = ldns_udp_read_wire(sockfd, answer_size, NULL, NULL);
close_socket(sockfd);
if (!answer) {
/* oops */
return LDNS_STATUS_NETWORK_ERR;
}
*result = answer;
return LDNS_STATUS_OK;
}
ldns_status
ldns_udp_send(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout, size_t *answer_size)
{
return ldns_udp_send_from(result, qbin, to, tolen, NULL, 0,
timeout, answer_size);
}
ldns_status
ldns_send_buffer(ldns_pkt **result, ldns_resolver *r, ldns_buffer *qb, ldns_rdf *tsig_mac)
{
uint8_t i;
struct sockaddr_storage *src = NULL;
size_t src_len = 0;
struct sockaddr_storage *ns;
size_t ns_len;
struct timeval tv_s;
struct timeval tv_e;
ldns_rdf **ns_array;
size_t *rtt;
ldns_pkt *reply;
bool all_servers_rtt_inf;
uint8_t retries;
uint8_t *reply_bytes = NULL;
size_t reply_size = 0;
ldns_status status, send_status;
assert(r != NULL);
status = LDNS_STATUS_OK;
rtt = ldns_resolver_rtt(r);
ns_array = ldns_resolver_nameservers(r);
reply = NULL;
ns_len = 0;
all_servers_rtt_inf = true;
if (ldns_resolver_random(r)) {
ldns_resolver_nameservers_randomize(r);
}
if(ldns_resolver_source(r)) {
src = ldns_rdf2native_sockaddr_storage_port(
ldns_resolver_source(r), 0, &src_len);
}
/* loop through all defined nameservers */
for (i = 0; i < ldns_resolver_nameserver_count(r); i++) {
if (rtt[i] == LDNS_RESOLV_RTT_INF) {
/* not reachable nameserver! */
continue;
}
/* maybe verbosity setting?
printf("Sending to ");
ldns_rdf_print(stdout, ns_array[i]);
printf("\n");
*/
ns = ldns_rdf2native_sockaddr_storage(ns_array[i],
ldns_resolver_port(r), &ns_len);
#ifndef S_SPLINT_S
if ((ns->ss_family == AF_INET) &&
(ldns_resolver_ip6(r) == LDNS_RESOLV_INET6)) {
/* not reachable */
LDNS_FREE(ns);
continue;
}
if ((ns->ss_family == AF_INET6) &&
(ldns_resolver_ip6(r) == LDNS_RESOLV_INET)) {
/* not reachable */
LDNS_FREE(ns);
continue;
}
#endif
all_servers_rtt_inf = false;
gettimeofday(&tv_s, NULL);
send_status = LDNS_STATUS_ERR;
/* reply_bytes implicitly handles our error */
if (ldns_resolver_usevc(r)) {
for (retries = ldns_resolver_retry(r); retries > 0; retries--) {
send_status =
ldns_tcp_send_from(&reply_bytes, qb,
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(r),
&reply_size);
if (send_status == LDNS_STATUS_OK) {
break;
}
}
} else {
for (retries = ldns_resolver_retry(r); retries > 0; retries--) {
/* ldns_rdf_print(stdout, ns_array[i]); */
send_status =
ldns_udp_send_from(&reply_bytes, qb,
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(r),
&reply_size);
if (send_status == LDNS_STATUS_OK) {
break;
}
}
}
if (send_status != LDNS_STATUS_OK) {
ldns_resolver_set_nameserver_rtt(r, i, LDNS_RESOLV_RTT_INF);
status = send_status;
}
/* obey the fail directive */
if (!reply_bytes) {
/* the current nameserver seems to have a problem, blacklist it */
if (ldns_resolver_fail(r)) {
if(src) {
LDNS_FREE(src);
}
LDNS_FREE(ns);
return LDNS_STATUS_ERR;
} else {
LDNS_FREE(ns);
continue;
}
}
status = ldns_wire2pkt(&reply, reply_bytes, reply_size);
if (status != LDNS_STATUS_OK) {
if(src) LDNS_FREE(src);
LDNS_FREE(reply_bytes);
LDNS_FREE(ns);
return status;
}
assert(reply);
LDNS_FREE(ns);
gettimeofday(&tv_e, NULL);
if (reply) {
ldns_pkt_set_querytime(reply, (uint32_t)
((tv_e.tv_sec - tv_s.tv_sec) * 1000) +
(tv_e.tv_usec - tv_s.tv_usec) / 1000);
ldns_pkt_set_answerfrom(reply,
ldns_rdf_clone(ns_array[i]));
ldns_pkt_set_timestamp(reply, tv_s);
ldns_pkt_set_size(reply, reply_size);
break;
} else {
if (ldns_resolver_fail(r)) {
/* if fail is set bail out, after the first
* one */
break;
}
}
/* wait retrans seconds... */
sleep((unsigned int) ldns_resolver_retrans(r));
}
if(src) {
LDNS_FREE(src);
}
if (all_servers_rtt_inf) {
LDNS_FREE(reply_bytes);
return LDNS_STATUS_RES_NO_NS;
}
#ifdef HAVE_SSL
if (tsig_mac && reply && reply_bytes) {
if (!ldns_pkt_tsig_verify(reply,
reply_bytes,
reply_size,
ldns_resolver_tsig_keyname(r),
ldns_resolver_tsig_keydata(r), tsig_mac)) {
status = LDNS_STATUS_CRYPTO_TSIG_BOGUS;
}
}
#else
(void)tsig_mac;
#endif /* HAVE_SSL */
LDNS_FREE(reply_bytes);
if (result) {
*result = reply;
}
return status;
}
ssize_t
ldns_tcp_send_query(ldns_buffer *qbin, int sockfd,
const struct sockaddr_storage *to, socklen_t tolen)
{
uint8_t *sendbuf;
ssize_t bytes;
/* add length of packet */
sendbuf = LDNS_XMALLOC(uint8_t, ldns_buffer_position(qbin) + 2);
if(!sendbuf) return 0;
ldns_write_uint16(sendbuf, ldns_buffer_position(qbin));
memcpy(sendbuf + 2, ldns_buffer_begin(qbin), ldns_buffer_position(qbin));
bytes = sendto(sockfd, (void*)sendbuf,
ldns_buffer_position(qbin) + 2, 0, (struct sockaddr *)to, tolen);
LDNS_FREE(sendbuf);
if (bytes == -1 || (size_t) bytes != ldns_buffer_position(qbin) + 2 ) {
return 0;
}
return bytes;
}
/* don't wait for an answer */
ssize_t
ldns_udp_send_query(ldns_buffer *qbin, int sockfd, const struct sockaddr_storage *to,
socklen_t tolen)
{
ssize_t bytes;
bytes = sendto(sockfd, (void*)ldns_buffer_begin(qbin),
ldns_buffer_position(qbin), 0, (struct sockaddr *)to, tolen);
if (bytes == -1 || (size_t)bytes != ldns_buffer_position(qbin)) {
return 0;
}
return bytes;
}
uint8_t *
ldns_udp_read_wire(int sockfd, size_t *size, struct sockaddr_storage *from,
socklen_t *fromlen)
{
uint8_t *wire, *wireout;
ssize_t wire_size;
wire = LDNS_XMALLOC(uint8_t, LDNS_MAX_PACKETLEN);
if (!wire) {
*size = 0;
return NULL;
}
wire_size = recvfrom(sockfd, (void*)wire, LDNS_MAX_PACKETLEN, 0,
(struct sockaddr *)from, fromlen);
/* recvfrom can also return 0 */
if (wire_size == -1 || wire_size == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
*size = (size_t)wire_size;
wireout = LDNS_XREALLOC(wire, uint8_t, (size_t)wire_size);
if(!wireout) LDNS_FREE(wire);
return wireout;
}
uint8_t *
ldns_tcp_read_wire_timeout(int sockfd, size_t *size, struct timeval timeout)
{
uint8_t *wire;
uint16_t wire_size;
ssize_t bytes = 0, rc = 0;
wire = LDNS_XMALLOC(uint8_t, 2);
if (!wire) {
*size = 0;
return NULL;
}
while (bytes < 2) {
if(!ldns_sock_wait(sockfd, timeout, 0)) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (2 - bytes), 0);
if (rc == -1 || rc == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
bytes += rc;
}
wire_size = ldns_read_uint16(wire);
LDNS_FREE(wire);
wire = LDNS_XMALLOC(uint8_t, wire_size);
if (!wire) {
*size = 0;
return NULL;
}
bytes = 0;
while (bytes < (ssize_t) wire_size) {
if(!ldns_sock_wait(sockfd, timeout, 0)) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (wire_size - bytes), 0);
if (rc == -1 || rc == 0) {
LDNS_FREE(wire);
*size = 0;
return NULL;
}
bytes += rc;
}
*size = (size_t) bytes;
return wire;
}
uint8_t *
ldns_tcp_read_wire(int sockfd, size_t *size)
{
uint8_t *wire;
uint16_t wire_size;
ssize_t bytes = 0, rc = 0;
wire = LDNS_XMALLOC(uint8_t, 2);
if (!wire) {
*size = 0;
return NULL;
}
while (bytes < 2) {
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (2 - bytes), 0);
if (rc == -1 || rc == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
bytes += rc;
}
wire_size = ldns_read_uint16(wire);
LDNS_FREE(wire);
wire = LDNS_XMALLOC(uint8_t, wire_size);
if (!wire) {
*size = 0;
return NULL;
}
bytes = 0;
while (bytes < (ssize_t) wire_size) {
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (wire_size - bytes), 0);
if (rc == -1 || rc == 0) {
LDNS_FREE(wire);
*size = 0;
return NULL;
}
bytes += rc;
}
*size = (size_t) bytes;
return wire;
}
#ifndef S_SPLINT_S
ldns_rdf *
ldns_sockaddr_storage2rdf(const struct sockaddr_storage *sock, uint16_t *port)
{
ldns_rdf *addr;
struct sockaddr_in *data_in;
struct sockaddr_in6 *data_in6;
switch(sock->ss_family) {
case AF_INET:
data_in = (struct sockaddr_in*)sock;
if (port) {
*port = ntohs((uint16_t)data_in->sin_port);
}
addr = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_A,
LDNS_IP4ADDRLEN, &data_in->sin_addr);
break;
case AF_INET6:
data_in6 = (struct sockaddr_in6*)sock;
if (port) {
*port = ntohs((uint16_t)data_in6->sin6_port);
}
addr = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_AAAA,
LDNS_IP6ADDRLEN, &data_in6->sin6_addr);
break;
default:
if (port) {
*port = 0;
}
return NULL;
}
return addr;
}
#endif
/* code from resolver.c */
ldns_status
ldns_axfr_start(ldns_resolver *resolver, const ldns_rdf *domain, ldns_rr_class class)
{
ldns_pkt *query;
ldns_buffer *query_wire;
struct sockaddr_storage *src = NULL;
size_t src_len = 0;
struct sockaddr_storage *ns = NULL;
size_t ns_len = 0;
size_t ns_i;
ldns_status status;
if (!resolver || ldns_resolver_nameserver_count(resolver) < 1) {
return LDNS_STATUS_ERR;
}
query = ldns_pkt_query_new(ldns_rdf_clone(domain), LDNS_RR_TYPE_AXFR, class, 0);
if (!query) {
return LDNS_STATUS_ADDRESS_ERR;
}
if(ldns_resolver_source(resolver)) {
src = ldns_rdf2native_sockaddr_storage_port(
ldns_resolver_source(resolver), 0, &src_len);
}
/* For AXFR, we have to make the connection ourselves */
/* try all nameservers (which usually would mean v4 fallback if
* @hostname is used */
for (ns_i = 0;
ns_i < ldns_resolver_nameserver_count(resolver) &&
resolver->_socket == SOCK_INVALID;
ns_i++) {
if (ns != NULL) {
LDNS_FREE(ns);
}
ns = ldns_rdf2native_sockaddr_storage(
resolver->_nameservers[ns_i],
ldns_resolver_port(resolver), &ns_len);
#ifndef S_SPLINT_S
if ((ns->ss_family == AF_INET) &&
(ldns_resolver_ip6(resolver) == LDNS_RESOLV_INET6)) {
/* not reachable */
LDNS_FREE(ns);
ns = NULL;
continue;
}
if ((ns->ss_family == AF_INET6) &&
(ldns_resolver_ip6(resolver) == LDNS_RESOLV_INET)) {
/* not reachable */
LDNS_FREE(ns);
ns = NULL;
continue;
}
#endif
resolver->_socket = ldns_tcp_connect_from(
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(resolver));
}
if (src) {
LDNS_FREE(src);
}
if (resolver->_socket == SOCK_INVALID) {
ldns_pkt_free(query);
LDNS_FREE(ns);
return LDNS_STATUS_NETWORK_ERR;
}
#ifdef HAVE_SSL
if (ldns_resolver_tsig_keyname(resolver) && ldns_resolver_tsig_keydata(resolver)) {
status = ldns_pkt_tsig_sign(query,
ldns_resolver_tsig_keyname(resolver),
ldns_resolver_tsig_keydata(resolver),
300, ldns_resolver_tsig_algorithm(resolver), NULL);
if (status != LDNS_STATUS_OK) {
/* to prevent problems on subsequent calls to
* ldns_axfr_start we have to close the socket here! */
close_socket(resolver->_socket);
resolver->_socket = 0;
ldns_pkt_free(query);
LDNS_FREE(ns);
return LDNS_STATUS_CRYPTO_TSIG_ERR;
}
}
#endif /* HAVE_SSL */
/* Convert the query to a buffer
* Is this necessary?
*/
query_wire = ldns_buffer_new(LDNS_MAX_PACKETLEN);
if(!query_wire) {
ldns_pkt_free(query);
LDNS_FREE(ns);
close_socket(resolver->_socket);
return LDNS_STATUS_MEM_ERR;
}
status = ldns_pkt2buffer_wire(query_wire, query);
if (status != LDNS_STATUS_OK) {
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/* to prevent problems on subsequent calls to ldns_axfr_start
* we have to close the socket here! */
close_socket(resolver->_socket);
resolver->_socket = 0;
return status;
}
/* Send the query */
if (ldns_tcp_send_query(query_wire, resolver->_socket, ns,
(socklen_t)ns_len) == 0) {
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/* to prevent problems on subsequent calls to ldns_axfr_start
* we have to close the socket here! */
close_socket(resolver->_socket);
return LDNS_STATUS_NETWORK_ERR;
}
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/*
* The AXFR is done once the second SOA record is sent
*/
resolver->_axfr_soa_count = 0;
return LDNS_STATUS_OK;
}
| NLnetLabs/ldns | net.c | C | bsd-3-clause | 24,586 |
<?php
/**
* UMI.Framework (http://umi-framework.ru/)
*
* @link http://github.com/Umisoft/framework for the canonical source repository
* @copyright Copyright (c) 2007-2013 Umisoft ltd. (http://umisoft.ru/)
* @license http://umi-framework.ru/license/bsd-3 BSD-3 License
*/
namespace utest\toolkit\unit\factory;
use umi\config\entity\Config;
use umi\toolkit\factory\IFactory;
use umi\toolkit\factory\TFactory;
use umi\toolkit\prototype\PrototypeFactory;
use umi\toolkit\Toolkit;
use utest\TestCase;
use utest\toolkit\mock\TestFactory;
/**
* Тестирование фабрики
*/
class FactoryTest extends TestCase implements IFactory
{
use TFactory;
public $factories = [];
protected function setUpFixtures()
{
$toolkit = new Toolkit();
$prototypeFactory = new PrototypeFactory($toolkit);
$toolkit->setPrototypeFactory($prototypeFactory);
$this->setToolkit($toolkit);
$this->setPrototypeFactory($prototypeFactory);
}
public function testPrototypeFactory()
{
$this->assertInstanceOf(
'umi\toolkit\prototype\IPrototypeFactory',
$this->getPrototypeFactory(),
'Ожидается, что у любой фабрики есть фабрика прототипов'
);
$this->_prototypeFactory = null;
$e = null;
try {
$this->getPrototypeFactory();
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'umi\toolkit\exception\RequiredDependencyException',
$e,
'Ожидается, что нельзя получить фабрику прототипов, если она не была внедрена'
);
}
public function testRegisterFactory()
{
$this->assertInstanceOf(
'utest\toolkit\unit\factory\FactoryTest',
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory'),
'Ожидается, что TFactory::registerFactory() вернет себя'
);
$e = null;
try {
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'umi\toolkit\exception\AlreadyRegisteredException',
$e,
'Ожидается, что нельзя повторно зарегистрировать фабрику'
);
}
public function testHasFactory()
{
$this->assertFalse($this->hasFactory('TestFactory'), 'Ожидается, что фабрика еще не зарегистрирована');
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
$this->assertTrue($this->hasFactory('TestFactory'), 'Ожидается, что фабрика зарегистрирована');
}
public function testGetFactory()
{
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
$factory = $this->getFactory('TestFactory');
$this->assertInstanceOf(
'umi\toolkit\factory\IFactory',
$factory,
'Ожидается, что, если фабрика была зарегистрирована, ее можно получить'
);
$this->assertTrue(
$factory === $this->getFactory('TestFactory'),
'Ожидается, что TFactory::getFactory() всегда возвращает единственный экземпляр фабрики'
);
}
public function testCreateFactory()
{
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
$createdFactory = $this->createFactory('TestFactory');
$this->assertInstanceOf(
'umi\toolkit\factory\IFactory',
$createdFactory,
'Ожидается, что, если фабрика была зарегистрирована, можно создать ее экземпляр'
);
$this->assertFalse(
$createdFactory === $this->createFactory('TestFactory'),
'Ожидается, что TFactory::createFactory() всегда возвращает новый экземпляр фабрики'
);
}
public function testChildFactoriesArrayConfig()
{
$this->factories = ['TestFactory' => ['option' => 'injectedValue']];
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
/**
* @var TestFactory $factory
*/
$factory = $this->getFactory('TestFactory');
$this->assertEquals(
'injectedValue',
$factory->option,
'Ожидается, что при создании фабрике были внедрены все опции конфигурации'
);
}
public function testChildFactoriesTraversableConfig()
{
$factories = ['TestFactory' => ['option' => 'injectedValue']];
$this->factories = new Config($factories);
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
/**
* @var TestFactory $factory
*/
$factory = $this->getFactory('TestFactory');
$this->assertEquals(
'injectedValue',
$factory->option,
'Ожидается, что при создании фабрике были внедрены все опции конфигурации тулбокса'
);
}
public function testFactoriesWrongConfig()
{
$this->factories = 'wrongConfig';
$this->registerFactory('TestFactory', 'utest\toolkit\mock\TestFactory');
$e = null;
try {
$this->getFactory('TestFactory');
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'\InvalidArgumentException',
$e,
'Ожидается исключение при некорректной конфигурации фабрик тулбокса'
);
}
public function testWrongChildFactory()
{
$this->registerFactory('WrongFactory', 'utest\toolkit\mock\TestFactory', ['NonexistentInterface']);
$e = null;
try {
$this->getFactory('WrongFactory');
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'umi\toolkit\exception\RuntimeException',
$e,
'Ожидается, что нельзя получить фабрику, если не удалось создать ее экземпляр'
);
$e = null;
try {
$this->createFactory('WrongFactory');
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'umi\toolkit\exception\RuntimeException',
$e,
'Ожидается, что нельзя получить новый экземпляр фабрики, если его не удалось'
);
$e = null;
try {
$this->getFactory('NonexistentFactory');
} catch (\Exception $e) {
}
$this->assertInstanceOf(
'umi\toolkit\exception\NotRegisteredException',
$e,
'Ожидается, что нельзя получить незарегистрированную фабрику'
);
}
}
| Umisoft/umi-framework | tests/utest/toolkit/unit/factory/FactoryTest.php | PHP | bsd-3-clause | 7,452 |
<?php
/**
* Mol_Util_Stringifier
*
* @category PHP
* @package Mol_Util
* @author Matthias Molitor <matthias@matthimatiker.de>
* @copyright 2012 Matthias Molitor
* @license http://www.opensource.org/licenses/BSD-3-Clause BSD License
* @link https://github.com/Matthimatiker/MolComponents
* @since 31.10.2012
*/
/**
* Class that converts data into simple strings.
*
* This class does *not* serialize data, the generated strings
* are just meant for output.
*
* @category PHP
* @package Mol_Util
* @author Matthias Molitor <matthias@matthimatiker.de>
* @copyright 2012 Matthias Molitor
* @license http://www.opensource.org/licenses/BSD-3-Clause BSD License
* @link https://github.com/Matthimatiker/MolComponents
* @since 31.10.2012
*/
class Mol_Util_Stringifier
{
/**
* Converts the given value into a string.
*
* @param array(mixed)|object|string|integer|double|boolean|null|resource $value
* @return string
*/
public static function stringify($value)
{
if ($value === null) {
return 'null';
}
if (is_string($value)) {
return '"' . $value . '"';
}
if (is_bool($value)) {
return ($value) ? 'true' : 'false';
}
if (is_object($value)) {
return get_class($value);
}
if (is_resource($value)) {
return self::stringifyResource($value);
}
if (is_array($value)) {
return self::stringifyArray($value);
}
// It is a simple type that can be rendered directly.
return $value;
}
/**
* Creates a string representation of the given resource.
*
* @param resource $resource
* @return string
*/
protected static function stringifyResource($resource)
{
$type = get_resource_type($resource);
if ($type === 'stream') {
$metaData = stream_get_meta_data($resource);
$type = $metaData['stream_type'] . ' ' . $type . ' (' . $metaData['uri'] . ')';
}
return $type;
}
/**
* Creates a string representation of the given array.
*
* Distinguishes between numerical and associative arrays.
*
* @param array(mixed) $array
* @return string
*/
protected static function stringifyArray(array $array)
{
if (self::isNumericalIndexed($array)) {
$values = array_map(array(__CLASS__, 'stringify'), array_values($array));
return '[' . implode(', ', $values) . ']';
}
$stringifiedItems = array();
foreach ($array as $key => $value) {
$stringifiedItems[] = self::stringify($key) . ': ' . self::stringify($value);
}
return '{' . implode(', ', $stringifiedItems) . '}';
}
/**
* Checks if the given array is numerical indexed.
*
* Keys of numerical arrays are starting at 0 and they are
* increasing in steps of 1.
*
* @param array(mixed) $array
* @return boolean True if the array is numerical indexed, false otherwise.
*/
protected static function isNumericalIndexed(array $array)
{
$numberOfElements = count($array);
$keys = array_keys($array);
// Calculate a checksum and check if the keys
// sum up correctly.
return array_sum($keys) == (($numberOfElements - 1) / 2.0) * $numberOfElements;
}
/**
* Stringifies an exception and all of its inner exceptions.
*
* In contrast to stringify() this specialized method returns
* much more information about the given exception.
*
* @param Exception $exception
* @return string
*/
public static function stringifyException(Exception $exception)
{
$level = 0;
$stringified = '';
while ($exception !== null) {
$representation = 'Type: ' . get_class($exception) . PHP_EOL
. 'Code: ' . $exception->getCode() . PHP_EOL
. 'Message: ' . $exception->getMessage() . PHP_EOL
. 'Trace: ' . ltrim(self::indent($exception->getTraceAsString(), ' '));
$indention = ltrim(str_repeat('>', $level) . ' ');
$stringified .= self::indent($representation, $indention) . PHP_EOL;
// Check if there is a nested exception.
$exception = (method_exists($exception, 'getPrevious')) ? $exception->getPrevious() : null;
$level++;
}
return $stringified;
}
/**
* Prepends the given prefix to each line of the provided text.
*
* @param string $text
* @param string $prefix
* @return string
*/
protected static function indent($text, $prefix)
{
// Unify line endings.
$text = str_replace("\r\n", "\n", $text);
$lines = explode("\n", $text);
return $prefix . implode(PHP_EOL . $prefix, $lines);
}
}
| Matthimatiker/MolComponents | src/Mol/Util/Stringifier.php | PHP | bsd-3-clause | 5,050 |
var Catcher = Class.create({
initialize: function(world) {
this.bodyLeft = createBox(world, 570, 450, 5, 35, true, 'catcher', 1.0);
this.bodyRight = createBox(world, 630, 450, 5, 35, true, 'catcher', 1.0);
this.bodyMiddle = createBox(world, 600, 483, 25, 2, true, 'catcher', 1.0);
this.bodyMiddleInside = createBox(world, 600, 478, 25, 2, true, 'catcherInside', 1.0);
return this;
},
Destroy: function(world){
world.DestroyBody(this.bodyLeft);
world.DestroyBody(this.bodyRight);
world.DestroyBody(this.bodyMiddle);
world.DestroyBody(this.bodyMiddleInside);
},
Step: function(timeStep)
{
//if(this.body.GetCenterPosition().x>456)
// this.body.SetCenterPosition(new b2Vec2(this.body.GetCenterPosition().x-1, this.body.GetCenterPosition().y), 0);
},
Rotate: function(pi)
{
this.rotation++;
if(this.rotation > 3) this.rotation = 0;
switch(this.rotation) {
case 0:
this.bodyLeft.SetCenterPosition(new b2Vec2(570,450), 0);
this.bodyRight.SetCenterPosition(new b2Vec2(630,450), 0);
this.bodyMiddle.SetCenterPosition(new b2Vec2(600,483), 0);
this.bodyMiddleInside.SetCenterPosition(new b2Vec2(600,478), 0);
break;
case 1:
this.bodyLeft.SetCenterPosition(new b2Vec2(600,420), pi/2);
this.bodyRight.SetCenterPosition(new b2Vec2(600,480), pi/2);
this.bodyMiddle.SetCenterPosition(new b2Vec2(567,450), pi/2);
this.bodyMiddleInside.SetCenterPosition(new b2Vec2(572,450), pi/2);
break;
case 2:
this.bodyRight.SetCenterPosition(new b2Vec2(570,450), 0);
this.bodyLeft.SetCenterPosition(new b2Vec2(630,450), 0);
this.bodyMiddle.SetCenterPosition(new b2Vec2(600,417), 0);
this.bodyMiddleInside.SetCenterPosition(new b2Vec2(600,422), 0);
break;
case 3:
this.bodyRight.SetCenterPosition(new b2Vec2(600,420), pi/2);
this.bodyLeft.SetCenterPosition(new b2Vec2(600,480), pi/2);
this.bodyMiddle.SetCenterPosition(new b2Vec2(633,450), pi/2);
this.bodyMiddleInside.SetCenterPosition(new b2Vec2(628,450), pi/2);
break;
}
},
bodyLeft: null,
bodyRight: null,
bodyMiddle: null,
bodyMiddleInside: null,
rotation: 0
}); | maseek/maseek-codes | src/quarter-brain/js/catcher.js | JavaScript | bsd-3-clause | 2,108 |
package main
import (
"bufio"
"flag"
"fmt"
"github.com/nutrun/lentil"
"log"
"os"
"strings"
)
var listener *bool = flag.Bool("listen", false, "Start listener")
var help *bool = flag.Bool("help", false, "Show help")
var mailto *string = flag.String("mailto", "", "Who to email on failure (comma separated) [submit]")
var workdir *string = flag.String("workdir", "/tmp", "Directory to run job from [submit]")
var stdout *string = flag.String("stdout", "/dev/null", "File to send job's stdout [submit]")
var stderr *string = flag.String("stderr", "/dev/null", "File to send job's stderr [submit]")
var tube *string = flag.String("tube", "", "Beanstalkd tube to send the job to [submit]")
var stats *bool = flag.Bool("stats", false, "Show queue stats")
var drain *string = flag.String("drain", "", "Empty tubes (comma separated)")
var verbose *bool = flag.Bool("v", false, "Increase verbosity")
var exclude *string = flag.String("exclude", "", "Tubes to ignore (comma separated) [listen]")
var priority *int = flag.Int("pri", 0, "Job priority (smaller runs first) [submit]")
var delay *int = flag.Int("delay", 0, "Job delay in seconds [submit]")
var local *bool = flag.Bool("local", false, "Run locally, reporting errors to the configured beanstalk")
var pause *string = flag.String("pause", "", "Pause tubes (comma separated)")
var pausedelay *int = flag.Int("pause-delay", 0, "How many seconds to pause tubes for")
var mailfrom *string = flag.String("mail-from", "glow@example.com", "Email 'from' field [listen]")
var smtpserver *string = flag.String("smtp-server", "", "Server to use for sending emails [listen]")
var deps *string = flag.String("deps", "", "Path to tube dependency config file [listen]")
var logpath *string = flag.String("log", "/dev/stderr", "Path to log file [listen]")
var mlen *int = flag.Int("mlen", 65536, "Max length of messeges sent to beanstalk in bytes [submit]")
var Config *Configuration
func main() {
flag.Parse()
Config = NewConfig(*deps, *smtpserver, *mailfrom)
lentil.ReaderSize = *mlen
if *listener {
include := false
filter := make([]string, 0)
if *exclude != "" {
filter = strings.Split(*exclude, ",")
}
l, e := NewListener(*verbose, include, filter, *logpath)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
l.run()
return
} else if *help {
flag.Usage()
os.Exit(1)
}
if *local {
executable, arguments := parseCommand()
// hack: local doesn't need tube, defaulting it to respect the Message API
msg, e := NewMessage(executable, arguments, *mailto, *workdir, *stdout, *stderr, "localignore", 0, 0)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
logfile, e := os.OpenFile(*logpath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
runner, e := NewRunner(*verbose, log.New(logfile, "", log.LstdFlags))
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
e = runner.execute(msg)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
return
}
c, e := NewClient(*verbose)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
if *drain != "" {
e = c.drain(*drain)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
} else if *pause != "" {
if *pausedelay == 0 {
fmt.Fprintln(os.Stderr, "Usage: glow -pause=<tube1,tube2,...> -pause-delay=<seconds>")
os.Exit(1)
}
e = c.pause(*pause, *pausedelay)
} else if *stats {
e = c.stats()
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
} else if len(flag.Args()) == 0 { // Queue up many jobs from STDIN
in := bufio.NewReaderSize(os.Stdin, 1024*1024)
input := make([]byte, 0)
for {
line, e := in.ReadSlice('\n')
if e != nil {
if e.Error() == "EOF" {
break
}
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
input = append(input, line...)
}
e = c.putMany(input)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
} else { // Queue up one job
executable, arguments := parseCommand()
msg, e := NewMessage(executable, arguments, *mailto, *workdir, *stdout, *stderr, *tube, *priority, *delay)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
e = c.put(msg)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
}
}
func parseCommand() (string, []string) {
return flag.Args()[0], flag.Args()[1:len(flag.Args())]
}
| nutrun/glow | main.go | GO | bsd-3-clause | 4,385 |
<?php
/**
* Created by PhpStorm.
* User : xin.zhang
* Date : 15/4/20
* Time : 下午1:24
* Email: zhangxinmailvip@foxmail.com
*/
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form onsubmit="return false" id=form_validate class="form-horizontal" novalidate="novalidate">
<input id="countryId" value="<?= $city->countryId ?>"/>
<input id="cityId" value="<?= $city->id ?>"/>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="false"></button>
<h4 class="modal-title">
添加城市
</h4>
</div>
<div class="modal-body">
<div class="scroller" style="height: 240px" data-always-visible="1" data-rail-visible1="1">
<div class="row">
<div class="col-md-12">
<div class="portlet-body form">
<!-- BEGIN FORM-->
<div class="form-body">
<div class="alert alert-danger display-hide" style="display: none;">
<button class="close" data-close="alert"></button>
<span></span>
</div>
<div class="alert alert-success display-hide" style="display: none;">
<button class="close" data-close="alert"></button>
<span></span>
</div>
<div class="form-group">
<label class="control-label col-md-3">中文名称<span class="required">*</span></label>
<div class="col-md-7 valdate">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="cname" name="cname" class="form-control" value="<?= $city->cname; ?>" required maxlength=20 />
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">英文名称<span class="required">*</span></label>
<div class="col-md-7 valdate">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="ename" name="ename" class="form-control" value="<?= $city->ename; ?>" required maxlength=20 />
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">代码 </label>
<div class="col-md-7 valdate">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="code" name="code" class="form-control" value="<?= $city->code; ?>" maxlength=20 />
</div>
</div>
</div>
</div>
<!-- END FORM-->
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn green-meadow">
保存
</button>
<button type="button" id="modal_close" data-dismiss="modal" class="btn default">
关闭
</button>
</div>
</div>
</div>
</form>
<!-- END PAGE LEVEL STYLES -->
<script type="text/javascript" src="<?=Yii::$app->params['res_url'] ?>/assets/global/plugins/jquery-validation/dist/jquery.validate.min.js"></script>
<script type="text/javascript" src="<?=Yii::$app->params['res_url'] ?>/assets/global/plugins/jquery-validation/dist/additional-methods.min.js"></script>
<script type="text/javascript" src="<?=Yii::$app->params['res_url'] ?>/assets/admin/pages/scripts/form-validation.js?<?=time().rand(100,999)?>"></script>
<script type="text/javascript" src="<?=Yii::$app->params['res_url'] ?>/assets/global/plugins/jquery-validation/localization/messages_zh.js" ></script>
<script type="text/javascript">
jQuery(document).ready(function() {
FormValidation.init("editCity");
});
function editCity(){
$.ajax({
type:"POST",
url:"/country/update-city",
data:{
id:$("#cityId").val(),
cname:$("#cname").val(),
ename:$("#ename").val(),
code:$("#code").val(),
countryId:$("#countryId").val()
},beforeSend:function(){
Main.showWait(".modal-dialog");
},
error:function(){
Main.errorTip("系统异常");
},
success:function(data){
data=eval("("+data+")");
Main.hideWait();
if(data.status==1){
Main.successTip("保存城市成功");
$("#modal_close").click();
Main.refrenshTableCurrent();
}else{
Main.errorTip("保存失败");
}
}
});
}
</script>
</body>
</html>
| suiuuwebandapp/Web-Backend | backend/views/country/editCity.php | PHP | bsd-3-clause | 6,138 |
/*--------------------------------------------------------------------------
File : isha256.c
Author : Hoang Nguyen Hoan Aug. 17, 2014
Desc : SHA-256 computation
Copyright (c) 2014, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "istddef.h"
#include "isha256.h"
/*
* Test cases
* Data : null, zero length
* SHA256 : e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
*
* Data : "abc"
* SHA256 : BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD
*
* Data : "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
* SHA256 : 248D6A61 D20638B8 E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1
*
* Data : repeat 'a' 1000000 times
* SHA256 : cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0
*
* Data : "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
* SHA256 : cf5b16a7 78af8380 036ce59e 7b049237 0b249b11 e8f07a51 afac4503 7afee9d1
*
*/
#define H0 0x6a09e667
#define H1 0xbb67ae85
#define H2 0x3c6ef372
#define H3 0xa54ff53a
#define H4 0x510e527f
#define H5 0x9b05688c
#define H6 0x1f83d9ab
#define H7 0x5be0cd19
static uint32_t g_Sha256KValue[] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
inline uint32_t ROTR(uint32_t x, uint32_t n)
{
return (x >> n) | (x << (32-n));
}
inline uint32_t ROTL(uint32_t x, uint32_t n)
{
return (x << n) | (x >> (32 - n));
}
inline uint32_t SUM0(uint32_t x)
{
return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22);
}
inline uint32_t SUM1(uint32_t x)
{
return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25);
}
inline uint32_t SIGMA0(uint32_t x)
{
return ROTR(x, 7) ^ ROTR(x, 18) ^ (x >> 3);
}
inline uint32_t SIGMA1(uint32_t x)
{
return ROTR(x, 17) ^ ROTR(x, 19) ^ (x >> 10);
}
inline uint32_t CH(uint32_t x, uint32_t y, uint32_t z)
{
return (x & y) ^ (~x & z);
}
inline uint32_t MAJ(uint32_t x, uint32_t y, uint32_t z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
void Sha256Compute(uint32_t *W, uint32_t *H)
{
uint32_t a, b, c, d, e, f, g, h;
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
f = H[5];
g = H[6];
h = H[7];
for (int t = 0; t < 64; t++)
{
uint32_t T1;
uint32_t T2;
if (t > 15)
W[t] = (SIGMA1(W[t-2]) + W[t-7] + SIGMA0(W[t-15]) + W[t-16]) & 0xffffffff;
T1 = h + SUM1(e) + CH(e, f, g) + g_Sha256KValue[t] + W[t];
T2 = SUM0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = (d + T1);
d = c;
c = b;
b = a;
a = (T1 + T2);
}
H[0] = (H[0] + a);
H[1] = (H[1] + b);
H[2] = (H[2] + c);
H[3] = (H[3] + d);
H[4] = (H[4] + e);
H[5] = (H[5] + f);
H[6] = (H[6] + g);
H[7] = (H[7] + h);
}
static int g_LastWIdx = 0;
static int g_LastOctet = 0;
static uint64_t g_TotalBitLen = 0;
static char g_Sha256Digest[66] = { 0,};
static uint32_t H[8] = { H0, H1, H2, H3, H4, H5, H6, H7 };
static uint32_t W[64];
/*
* Generate SHA digest code. Call this function until all data are processed.
* set bLast parameter to true for last data packet to process.
*
* Make sure to have enough memory for returning results. pRes must have at
* least 65 bytes.
*
* @param pSrc : Pointer to source data
* SrcLen : Source data length in bytes
* bLast : set true to indicate last data packet
* pRes : Pointer to buffer to store results of 64 characters
* if NULL is passed, internal buffer will be used
*
* @return Pointer to digest string. If pRes is NULL, internal buffer is returned
* NULL if incomplete
*/
char *Sha256(uint8_t *pData, int DataLen, bool bLast, char *pRes)
{
uint8_t *p = pData;
int t = 0, j = 0;
char *digest = g_Sha256Digest;
g_TotalBitLen += DataLen << 3;
if (g_LastOctet || g_LastWIdx)
{
// We have incomplete buffer from previous call
t = g_LastWIdx;
// Fill up left over from previous 32bits
for (int j = g_LastOctet; j < 4; j++)
{
W[t] |= *p << (24 - (j << 3));
DataLen--;
p++;
}
t++;
// Fill up th rest of the 512 bits message
for (; t < 16 && DataLen > 3; t++)
{
W[t] = p[3] | (p[2] << 8) | (p[1] << 16) | (p[0] << 24);
p += 4;
DataLen -= 4;
}
if (t >= 16)
{
// We have complete 512
Sha256Compute(W, H);
memset(W, 0, sizeof(W));
t = 0; j = 0;
}
}
if (DataLen > 64)
{
// Process N complete 512 bits message
int n = DataLen / 64;
for (int i = 0; i < n; i++)
{
for (t = 0; t < 16; t++)
{
W[t] = p[3] | (p[2] << 8) | (p[1] << 16) | (p[0] << 24);
p += 4;
DataLen -= 4;
}
Sha256Compute(W, H);
}
t = 0;
j = 0;
memset(W, 0, sizeof(W));
}
g_LastWIdx = 0;
g_LastOctet = 0;
if (DataLen)
{
// Still have incompleted data
for (t = 0; t < 16 && DataLen > 3; t++)
{
W[t] = p[3] | (p[2] << 8) | (p[1] << 16) | (p[0] << 24);
p += 4;
DataLen -= 4;
}
for (j = 0; j < DataLen; j++)
{
W[t] |= *p << (24 - (j << 3));
p++;
}
}
if (bLast == false)
{
// More data to come, remember where we are
g_LastWIdx = t;
g_LastOctet = j;
return NULL;
}
if (bLast)
{
// All data processed. add the 1 bit & data len
W[t] |= 0x80 << (24 - (j << 3));
t++;
if (t > 14)
Sha256Compute(W, H);
{
W[14] = g_TotalBitLen >> 32;
W[15] = g_TotalBitLen & 0xffffffff;
}
Sha256Compute(W, H);
if (pRes)
digest = pRes;
//sprintf(digest, "%08lX%08lX%08lX%08lX%08lX%08lX%08lX%08lX", H[0], H[1], H[2], H[3], H[4], H[5], H[6], H[7]);
// Reset memory, ready for new processing
H[0] = H0;
H[1] = H1;
H[2] = H2;
H[3] = H3;
H[4] = H4;
H[5] = H5;
H[6] = H6;
H[7] = H7;
memset(W, 0, sizeof(W));
g_LastWIdx = 0;
g_LastOctet = 0;
g_TotalBitLen = 0;
}
return digest;
}
| I-SYST/EHAL | src/isha256.c | C | bsd-3-clause | 7,819 |
################################################################
# File: e621.py
# Title: MANGAdownloader's site scraper
# Author: ASL97/ASL <asl97@outlook.com>
# Version: 1
# Notes : DON'T EMAIL ME UNLESS YOU NEED TO
# TODO: *blank*
################################################################
import misc
# used in __main__, download using id is currently not implemented yet
id_supported = False
_type = ["1","10"]
def scrap_manga(link, chapter):
chapter[1] = {}
tmp = link.split("/")[-1]
if tmp.isdigit():
id_ = tmp
link = "http://e621.net/pool/show.json?id=%s"%(id_)
j = misc.download_json(link)
name = j["name"]
total = j["post_count"]
page_ = 1
page = 0
for d in j["posts"]:
chapter[1][page] = {"link": d['file_url'],
"name": d['file_url'].split("/")[-1]}
page += 1
while page < total:
page_ += 1
link = "http://e621.net/pool/show.json?id=%s&page=%d"%(id_,page_)
j = misc.download_json(link)
for d in j["posts"]:
chapter[1][page] = {"link": d['file_url'],
"name": d['file_url'].split("/")[-1]}
page += 1
return name
else:
misc.Exit("fail to get id")
| asl97/MANGAdownloader | scrapers/e621.py | Python | bsd-3-clause | 1,343 |
package engine
import (
"os"
"testing"
"time"
"golang.org/x/net/context"
"github.com/keybase/client/go/libkb"
"github.com/keybase/clockwork"
"github.com/stretchr/testify/require"
)
func TestLoginOffline(t *testing.T) {
tc := SetupEngineTest(t, "login")
defer tc.Cleanup()
u1 := CreateAndSignupFakeUser(tc, "login")
Logout(tc)
u1.LoginOrBust(tc)
// do a upak load to make sure it is cached
arg := libkb.NewLoadUserByUIDArg(context.TODO(), tc.G, u1.UID())
_, _, err := tc.G.GetUPAKLoader().Load(arg)
require.NoError(t, err)
// Simulate restarting the service by wiping out the
// passphrase stream cache and cached secret keys
clearCaches(tc.G)
tc.G.GetUPAKLoader().ClearMemory()
// set server uri to nonexistent ip so api calls will fail
prev := os.Getenv("KEYBASE_SERVER_URI")
os.Setenv("KEYBASE_SERVER_URI", "http://127.0.0.127:3333")
defer os.Setenv("KEYBASE_SERVER_URI", prev)
err = tc.G.ConfigureAPI()
require.NoError(t, err)
eng := NewLoginOffline(tc.G)
m := NewMetaContextForTest(tc)
if err := RunEngine2(m, eng); err != nil {
t.Fatal(err)
}
uv, deviceID, deviceName, skey, ekey := tc.G.ActiveDevice.AllFields()
if uv.IsNil() {
t.Errorf("uid is nil, expected it to exist")
}
if !uv.Uid.Equal(u1.UID()) {
t.Errorf("uid: %v, expected %v", uv, u1)
}
if deviceID.IsNil() {
t.Errorf("deviceID is nil, expected it to exist")
}
if deviceName != defaultDeviceName {
t.Errorf("device name: %q, expected %q", deviceName, defaultDeviceName)
}
if skey == nil {
t.Errorf("signing key is nil, expected it to exist")
}
if ekey == nil {
t.Errorf("encryption key is nil, expected it to exist")
}
if tc.G.ActiveDevice.Name() != defaultDeviceName {
t.Errorf("device name: %q, expected %q", tc.G.ActiveDevice.Name(), defaultDeviceName)
}
}
// Use fake clock to test login offline after significant delay
// (make sure upak loader won't use network)
func TestLoginOfflineDelay(t *testing.T) {
tc := SetupEngineTest(t, "login")
defer tc.Cleanup()
fakeClock := clockwork.NewFakeClockAt(time.Now())
tc.G.SetClock(fakeClock)
u1 := CreateAndSignupFakeUser(tc, "login")
Logout(tc)
u1.LoginOrBust(tc)
// do a upak load to make sure it is cached
arg := libkb.NewLoadUserByUIDArg(context.TODO(), tc.G, u1.UID())
_, _, err := tc.G.GetUPAKLoader().Load(arg)
require.NoError(t, err)
// Simulate restarting the service by wiping out the
// passphrase stream cache and cached secret keys
clearCaches(tc.G)
tc.G.GetUPAKLoader().ClearMemory()
// set server uri to nonexistent ip so api calls will fail
prev := os.Getenv("KEYBASE_SERVER_URI")
os.Setenv("KEYBASE_SERVER_URI", "http://127.0.0.127:3333")
defer os.Setenv("KEYBASE_SERVER_URI", prev)
err = tc.G.ConfigureAPI()
require.NoError(t, err)
// advance the clock past the cache timeout
fakeClock.Advance(libkb.CachedUserTimeout * 10)
eng := NewLoginOffline(tc.G)
m := NewMetaContextForTest(tc)
if err := RunEngine2(m, eng); err != nil {
t.Fatal(err)
}
uv, deviceID, deviceName, skey, ekey := tc.G.ActiveDevice.AllFields()
if uv.IsNil() {
t.Errorf("uid is nil, expected it to exist")
}
if !uv.Uid.Equal(u1.UID()) {
t.Errorf("uid: %v, expected %v", uv, u1.UID())
}
if deviceID.IsNil() {
t.Errorf("deviceID is nil, expected it to exist")
}
if deviceName != defaultDeviceName {
t.Errorf("device name: %q, expected %q", deviceName, defaultDeviceName)
}
if skey == nil {
t.Errorf("signing key is nil, expected it to exist")
}
if ekey == nil {
t.Errorf("encryption key is nil, expected it to exist")
}
}
// Login offline with nothing in upak cache for self user.
func TestLoginOfflineNoUpak(t *testing.T) {
tc := SetupEngineTest(t, "login")
defer tc.Cleanup()
u1 := CreateAndSignupFakeUser(tc, "login")
Logout(tc)
u1.LoginOrBust(tc)
// Simulate restarting the service by wiping out the
// passphrase stream cache and cached secret keys
tc.SimulateServiceRestart()
tc.G.GetUPAKLoader().ClearMemory()
// invalidate the cache for uid
tc.G.GetUPAKLoader().Invalidate(context.Background(), u1.UID())
// set server uri to nonexistent ip so api calls will fail
prev := os.Getenv("KEYBASE_SERVER_URI")
os.Setenv("KEYBASE_SERVER_URI", "http://127.0.0.127:3333")
defer os.Setenv("KEYBASE_SERVER_URI", prev)
err := tc.G.ConfigureAPI()
require.NoError(t, err)
eng := NewLoginOffline(tc.G)
m := NewMetaContextForTest(tc)
err = RunEngine2(m, eng)
if err != nil {
t.Fatalf("LoginOffline should still work after upak cache invalidation; got %s", err)
}
}
| keybase/client | go/engine/login_offline_test.go | GO | bsd-3-clause | 4,525 |
//
// viztool - a tool for visualizing collections of java classes
// Copyright (c) 2001-2013, Michael Bayne - All rights reserved.
// http://github.com/samskivert/viztool/blob/master/LICENSE
package com.samskivert.viztool;
/**
* A placeholder class that contains a reference to the log object used by
* the viztool package.
*/
public class Log
{
public static com.samskivert.util.Log log =
new com.samskivert.util.Log("viztool");
/** Convenience function. */
public static void debug (String message)
{
log.debug(message);
}
/** Convenience function. */
public static void info (String message)
{
log.info(message);
}
/** Convenience function. */
public static void warning (String message)
{
log.warning(message);
}
/** Convenience function. */
public static void logStackTrace (Throwable t)
{
log.logStackTrace(com.samskivert.util.Log.WARNING, t);
}
}
| samskivert/viztool | src/main/java/com/samskivert/viztool/Log.java | Java | bsd-3-clause | 972 |
#!/usr/bin/env python
import setuptools
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/util.py _exit_function when
# running python setup.py test (see
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
assert multiprocessing
except ImportError:
pass
setuptools.setup(
name='orwell.agent',
version='0.0.1',
description='Agent connecting to the game server.',
author='',
author_email='',
packages=setuptools.find_packages(exclude="test"),
test_suite='nose.collector',
install_requires=['pyzmq', 'cliff'],
tests_require=['nose', 'coverage', 'mock'],
entry_points={
'console_scripts': [
'thought_police = orwell.agent.main:main',
]
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6'],
python_requires='>=3.6.0',
)
| orwell-int/agent-server-game-python | setup.py | Python | bsd-3-clause | 1,239 |
/*
I/O interface class for loading, storing and manipulating
optical flow fields in KITTI format. This file requires libpng
and libpng++ to be installed (for accessing png files). More
detailed format specifications can be found in the readme.txt
(c) Andreas Geiger
*/
#ifndef IO_FLOW_H
#define IO_FLOW_H
#include <string.h>
#include <stdint.h>
#include <png++/png.hpp>
class FlowImage {
public:
// default constructor
FlowImage () {
data_ = 0;
width_ = 0;
height_ = 0;
}
// construct flow image from png file
FlowImage (const std::string file_name) {
readFlowField(file_name);
}
// copy constructor
FlowImage (const FlowImage &F) {
width_ = F.width_;
height_ = F.height_;
data_ = (float*)malloc(width_*height_*3*sizeof(float));
memcpy(data_,F.data_,width_*height_*3*sizeof(float));
}
// construct flow field from data
FlowImage (const float* data, const int32_t width, const int32_t height) : width_(width), height_(height) {
data_ = (float*)malloc(width*height*3*sizeof(float));
memcpy(data_,data,width*height*3*sizeof(float));
}
// construct empty (= all pixels invalid) flow field of given width / height
FlowImage (const int32_t width, const int32_t height) : width_(width), height_(height) {
data_ = (float*)malloc(width*height*3*sizeof(float));
for (int32_t i=0; i<width*height*3; i++)
data_[i] = 0;
}
// deconstructor
virtual ~FlowImage () {
if (data_) { free(data_); data_ = 0; }
}
// read flow field from png file
void read (const std::string file_name) {
if (data_) { free(data_); data_ = 0; }
readFlowField(file_name);
}
// write flow field to png file
void write (const std::string file_name) {
writeFlowField (file_name);
}
// write flow field to false color map using the Middlebury colormap
void writeColor (const std::string file_name,float max_flow=-1.0f) {
if (max_flow<=1.0f)
max_flow = std::max(maxFlow(),1.0f);
writeFalseColors (file_name,max_flow);
}
// get optical flow u-component at given pixel
inline float getFlowU (const int32_t u,const int32_t v) {
return data_[3*(v*width_+u)+0];
}
// get optical flow v-component at given pixel
inline float getFlowV (const int32_t u,const int32_t v) {
return data_[3*(v*width_+u)+1];
}
// check if optical flow at given pixel is valid
inline bool isValid (const int32_t u,const int32_t v) {
return data_[3*(v*width_+u)+2]>0.5;
}
// get optical flow magnitude at given pixel
inline float getFlowMagnitude (const int32_t u,const int32_t v) {
float fu = getFlowU(u,v);
float fv = getFlowV(u,v);
return sqrt(fu*fu+fv*fv);
}
// set optical flow u-component at given pixel
inline void setFlowU (const int32_t u,const int32_t v,const float val) {
data_[3*(v*width_+u)+0] = val;
}
// set optical flow v-component at given pixel
inline void setFlowV (const int32_t u,const int32_t v,const float val) {
data_[3*(v*width_+u)+1] = val;
}
// set optical flow at given pixel to valid / invalid
inline void setValid (const int32_t u,const int32_t v,const bool valid) {
data_[3*(v*width_+u)+2] = valid ? 1 : 0;
}
// get maximal optical flow magnitude
float maxFlow () {
float max_flow = 0;
for (int32_t u=0; u<width_; u++)
for (int32_t v=0; v<height_; v++)
if (isValid(u,v) && getFlowMagnitude(u,v)>max_flow)
max_flow = getFlowMagnitude(u,v);
return max_flow;
}
// interpolate all missing (=invalid) optical flow vectors
void interpolateBackground () {
// for each row do
for (int32_t v=0; v<height_; v++) {
// init counter
int32_t count = 0;
// for each pixel do
for (int32_t u=0; u<width_; u++) {
// if flow is valid
if (isValid(u,v)) {
// at least one pixel requires interpolation
if (count>=1) {
// first and last value for interpolation
int32_t u1 = u-count;
int32_t u2 = u-1;
// set pixel to min flow
if (u1>0 && u2<width_-1) {
float fu_ipol = std::min(getFlowU(u1-1,v),getFlowU(u2+1,v));
float fv_ipol = std::min(getFlowV(u1-1,v),getFlowV(u2+1,v));
for (int32_t u_curr=u1; u_curr<=u2; u_curr++) {
setFlowU(u_curr,v,fu_ipol);
setFlowV(u_curr,v,fv_ipol);
setValid(u_curr,v,true);
}
}
}
// reset counter
count = 0;
// otherwise increment counter
} else {
count++;
}
}
// extrapolate to the left
for (int32_t u=0; u<width_; u++) {
if (isValid(u,v)) {
for (int32_t u2=0; u2<u; u2++) {
setFlowU(u2,v,getFlowU(u,v));
setFlowV(u2,v,getFlowV(u,v));
setValid(u2,v,true);
}
break;
}
}
// extrapolate to the right
for (int32_t u=width_-1; u>=0; u--) {
if (isValid(u,v)) {
for (int32_t u2=u+1; u2<=width_-1; u2++) {
setFlowU(u2,v,getFlowU(u,v));
setFlowV(u2,v,getFlowV(u,v));
setValid(u2,v,true);
}
break;
}
}
}
// for each column do
for (int32_t u=0; u<width_; u++) {
// extrapolate to the top
for (int32_t v=0; v<height_; v++) {
if (isValid(u,v)) {
for (int32_t v2=0; v2<v; v2++) {
setFlowU(u,v2,getFlowU(u,v));
setFlowV(u,v2,getFlowV(u,v));
setValid(u,v2,true);
}
break;
}
}
// extrapolate to the bottom
for (int32_t v=height_-1; v>=0; v--) {
if (isValid(u,v)) {
for (int32_t v2=v+1; v2<=height_-1; v2++) {
setFlowU(u,v2,getFlowU(u,v));
setFlowV(u,v2,getFlowV(u,v));
setValid(u,v2,true);
}
break;
}
}
}
}
// compute error map of flow field, given the non-occluded and occluded
// ground truth optical flow maps. stores result as color png image.
png::image<png::rgb_pixel> errorImage (FlowImage &F_noc,FlowImage &F_occ) {
png::image<png::rgb_pixel> image(width(),height());
for (int32_t v=1; v<height()-1; v++) {
for (int32_t u=1; u<width()-1; u++) {
if (F_occ.isValid(u,v)) {
float dfu = getFlowU(u,v)-F_occ.getFlowU(u,v);
float dfv = getFlowV(u,v)-F_occ.getFlowV(u,v);
float f_err = std::min(sqrt(dfu*dfu+dfv*dfv),5.0)/5.0;
png::rgb_pixel val;
val.red = (uint8_t)(f_err*255.0);
val.green = (uint8_t)(f_err*255.0);
val.blue = (uint8_t)(f_err*255.0);
if (!F_noc.isValid(u,v)) {
val.green = 0;
val.blue = 0;
}
for (int32_t v2=v-1; v2<=v+1; v2++)
for (int32_t u2=u-1; u2<=u+1; u2++)
image.set_pixel(u2,v2,val);
}
}
}
return image;
}
// direct access to private variables
float* data () { return data_; }
int32_t width () { return width_; }
int32_t height () { return height_; }
private:
void readFlowField (const std::string file_name) {
png::image< png::rgb_pixel_16 > image(file_name);
width_ = image.get_width();
height_ = image.get_height();
data_ = (float*)malloc(width_*height_*3*sizeof(float));
for (int32_t v=0; v<height_; v++) {
for (int32_t u=0; u<width_; u++) {
png::rgb_pixel_16 val = image.get_pixel(u,v);
if (val.blue>0) {
setFlowU(u,v,((float)val.red -32768.0f)/64.0f);
setFlowV(u,v,((float)val.green-32768.0f)/64.0f);
setValid(u,v,true);
} else {
setFlowU(u,v,0);
setFlowV(u,v,0);
setValid(u,v,false);
}
}
}
}
void writeFlowField (const std::string file_name) {
png::image< png::rgb_pixel_16 > image(width_,height_);
for (int32_t v=0; v<height_; v++) {
for (int32_t u=0; u<width_; u++) {
png::rgb_pixel_16 val;
val.red = 0;
val.green = 0;
val.blue = 0;
if (isValid(u,v)) {
val.red = (uint16_t)std::max(std::min(getFlowU(u,v)*64.0f+32768.0f,65535.0f),0.0f);
val.green = (uint16_t)std::max(std::min(getFlowV(u,v)*64.0f+32768.0f,65535.0f),0.0f);
val.blue = 1;
}
image.set_pixel(u,v,val);
}
}
image.write(file_name);
}
inline float hsvToRgb (float h, float s, float v, float &r, float &g, float &b) {
float c = v*s;
float h2 = 6.0*h;
float x = c*(1.0-fabs(fmod(h2,2.0)-1.0));
if (0<=h2&&h2<1) { r = c; g = x; b = 0; }
else if (1<=h2&&h2<2) { r = x; g = c; b = 0; }
else if (2<=h2&&h2<3) { r = 0; g = c; b = x; }
else if (3<=h2&&h2<4) { r = 0; g = x; b = c; }
else if (4<=h2&&h2<5) { r = x; g = 0; b = c; }
else if (5<=h2&&h2<=6) { r = c; g = 0; b = x; }
else if (h2>6) { r = 1; g = 0; b = 0; }
else if (h2<0) { r = 0; g = 1; b = 0; }
}
void writeFalseColors (const std::string file_name, const float max_flow) {
float n = 8; // multiplier
png::image< png::rgb_pixel > image(width_,height_);
for (int32_t v=0; v<height_; v++) {
for (int32_t u=0; u<width_; u++) {
float r=0,g=0,b=0;
if (isValid(u,v)) {
float mag = getFlowMagnitude(u,v);
float dir = atan2(getFlowV(u,v),getFlowU(u,v));
float h = fmod(dir/(2.0*M_PI)+1.0,1.0);
float s = std::min(std::max(mag*n/max_flow,0.0f),1.0f);
float v = std::min(std::max(n-s,0.0f),1.0f);
hsvToRgb(h,s,v,r,g,b);
}
image.set_pixel(u,v,png::rgb_pixel(r*255.0f,g*255.0f,b*255.0f));
}
}
image.write(file_name);
}
private:
float *data_;
int32_t width_;
int32_t height_;
};
#endif // IO_FLOW_H
| ivankreso/stereo-vision | reconstruction/evaluation/io_flow.h | C | bsd-3-clause | 10,036 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ABI44_0_0SliderMeasurementsManager.h"
#include <fbjni/fbjni.h>
#include <ABI44_0_0React/ABI44_0_0jni/ReadableNativeMap.h>
#include <ABI44_0_0React/ABI44_0_0renderer/core/conversions.h>
using namespace ABI44_0_0facebook::jni;
namespace ABI44_0_0facebook {
namespace ABI44_0_0React {
Size SliderMeasurementsManager::measure(
SurfaceId surfaceId,
LayoutConstraints layoutConstraints) const {
{
std::lock_guard<std::mutex> lock(mutex_);
if (hasBeenMeasured_) {
return cachedMeasurement_;
}
}
const jni::global_ref<jobject> &fabricUIManager =
contextContainer_->at<jni::global_ref<jobject>>("FabricUIManager");
static auto measure =
jni::findClassStatic("com/facebook/ABI44_0_0React/fabric/FabricUIManager")
->getMethod<jlong(
jint,
jstring,
ReadableMap::javaobject,
ReadableMap::javaobject,
ReadableMap::javaobject,
jfloat,
jfloat,
jfloat,
jfloat)>("measure");
auto minimumSize = layoutConstraints.minimumSize;
auto maximumSize = layoutConstraints.maximumSize;
local_ref<JString> componentName = make_jstring("ABI44_0_0RCTSlider");
auto measurement = yogaMeassureToSize(measure(
fabricUIManager,
surfaceId,
componentName.get(),
nullptr,
nullptr,
nullptr,
minimumSize.width,
maximumSize.width,
minimumSize.height,
maximumSize.height));
// Explicitly release smart pointers to free up space faster in JNI tables
componentName.reset();
{
std::lock_guard<std::mutex> lock(mutex_);
cachedMeasurement_ = measurement;
}
return measurement;
}
} // namespace ABI44_0_0React
} // namespace ABI44_0_0facebook
| exponentjs/exponent | ios/versioned-react-native/ABI44_0_0/ReactNative/ReactCommon/react/renderer/components/slider/platform/android/react/renderer/components/slider/ABI44_0_0SliderMeasurementsManager.cpp | C++ | bsd-3-clause | 1,974 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace Date;
use Date\assets\AppAsset;
use Yii;
/**
* //Date range picker
* $('#reservation').daterangepicker();
* //Date range picker with time picker
* $('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
* //Date range as a button
* $('#daterange-btn').daterangepicker(
* {
* ranges: {
* 'Today': [moment(), moment()],
* 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
* 'Last 7 Days': [moment().subtract(6, 'days'), moment()],
* 'Last 30 Days': [moment().subtract(29, 'days'), moment()],
* 'This Month': [moment().startOf('month'), moment().endOf('month')],
* 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
* },
* startDate: moment().subtract(29, 'days'),
* endDate: moment()
* },
* function (start, end) {
* $('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
* }
* );
*
* //Date picker
* $('#datepicker').datepicker({
* autoclose: true
* });
*/
class Date extends \yii\bootstrap\Widget
{
public $form;
public $type = 1;
public $model;
public $attribute;
public $file_options;
public $config = <<<JSON
{
ranges: {
'今天': [moment(), moment()],
'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'7天前': [moment().subtract(6, 'days'), moment()],
'30天前': [moment().subtract(29, 'days'), moment()],
'这个月': [moment().startOf('month'), moment().endOf('month')],
'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
// startDate: moment().subtract(29, 'days'),
// endDate: moment()
},
function (start, end) {
$('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
JSON;
public function init()
{
parent::init();
$model = $this->model;
$attribute = $this->attribute;
$config = $this->config;
$form = $this->form;
$type = $this->type;
$file_options = $this->file_options;
AppAsset::register($this->view);
if ($form) {
echo $form->field($model, $attribute, $file_options)->textInput(['id' => "reservationtime"]);
}
if ($type === 1) {
$js = <<<JS
$('#reservationtime').datepicker($config);
JS;
} else if ($type === 2) {
$js = <<<JS
$('#reservationtime').daterangepicker($config);
JS;
}
$this->view->registerJs($js);
}
}
| little-bit-shy/yii-advanced-app-2.0.9 | common/widgets/date/Date.php | PHP | bsd-3-clause | 2,888 |
/*
* Copyright (c) 1994, 1995. Netscape Communications Corporation. All
* rights reserved.
*
* Use of this software is governed by the terms of the license agreement for
* the Netscape Communications or Netscape Comemrce Server between the
* parties.
*/
/* ------------------------------------------------------------------------ */
/*
* ereport.h: Records transactions, reports errors to administrators, etc.
*
* Rob McCool
*/
#ifndef EREPORT_H
#define EREPORT_H
#include "../base/session.h" /* Session structure */
#ifdef XP_UNIX
#include <pwd.h> /* struct passwd */
#endif /* XP_UNIX */
/* ------------------------------ Constants ------------------------------- */
/*
* The maximum length of an error message. NOT RUN-TIME CHECKED
*/
#define MAX_ERROR_LEN 8192
/* A warning is a minor mishap, such as a 404 being issued. */
#define LOG_WARN 0
/*
* A misconfig is when there is a syntax error or permission violation in
* a config. file.
*/
#define LOG_MISCONFIG 1
/*
* Security warnings are issued when authentication fails, or a host is
* given a 403 return code.
*/
#define LOG_SECURITY 2
/*
* A failure is when a request could not be fulfilled due to an internal
* problem, such as a CGI script exiting prematurely, or a filesystem
* permissions problem.
*/
#define LOG_FAILURE 3
/*
* A catastrophe is a fatal server error such as running out of
* memory or processes, or a system call failing, or even a server crash.
* The server child cannot recover from a catastrophe.
*/
#define LOG_CATASTROPHE 4
/*
* Informational message, of no concern.
*/
#define LOG_INFORM 5
/*
* The time format to use in the error log
*/
#define ERR_TIMEFMT "[%d/%b/%Y:%H:%M:%S]"
/* The fd you will get if you are reporting errors to SYSLOG */
#define ERRORS_TO_SYSLOG -1
/* ------------------------------ Prototypes ------------------------------ */
/*
* ereport logs an error of the given degree and formats the arguments with
* the printf() style fmt. Returns whether the log was successful. Records
* the current date.
*/
int ereport(int degree, char *fmt, ...);
/*
* ereport_init initializes the error logging subsystem and opens the static
* file descriptors. It returns NULL upon success and an error string upon
* error. If a userpw is given, the logs will be chowned to that user.
*
* email is the address of a person to mail upon catastrophic error. It
* can be NULL if no e-mail is desired. ereport_init will not duplicate
* its own copy of this string; you must make sure it stays around and free
* it when you shut down the server.
*/
char *ereport_init(char *err_fn, char *email, struct passwd *pw);
/*
* log_terminate closes the error and common log file descriptors.
*/
void ereport_terminate(void);
/* For restarts */
SYS_FILE ereport_getfd(void);
#endif
| wfnex/openbras | src/ace/ACE_wrappers/apps/JAWS/clients/WebSTONE/src/nsapi-includes/base/ereport.h | C | bsd-3-clause | 2,848 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.btree;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class SetParentLoggable extends BTAbstractLoggable {
protected long pageNum;
protected long parentNum;
/**
* @param fileId
* @param pageNum
* @param parentNum
* @param transaction
*/
public SetParentLoggable(Txn transaction, byte fileId, long pageNum, long parentNum) {
super(BTree.LOG_SET_PARENT, fileId, transaction);
this.pageNum = pageNum;
this.parentNum = parentNum;
}
/**
* @param broker
* @param transactionId
*/
public SetParentLoggable(DBBroker broker, long transactionId) {
super(BTree.LOG_SET_PARENT, broker, transactionId);
}
/* (non-Javadoc)
* @see org.exist.storage.log.Loggable#write(java.nio.ByteBuffer)
*/
public void write(ByteBuffer out) {
super.write(out);
out.putLong(pageNum);
out.putLong(parentNum);
}
/* (non-Javadoc)
* @see org.exist.storage.log.Loggable#read(java.nio.ByteBuffer)
*/
public void read(ByteBuffer in) {
super.read(in);
pageNum = in.getLong();
parentNum = in.getLong();
}
/* (non-Javadoc)
* @see org.exist.storage.log.Loggable#getLogSize()
*/
public int getLogSize() {
return super.getLogSize() + 16;
}
public void redo() throws LogException {
getStorage().redoSetParent(this);
}
public String dump() {
return super.dump() + " - set parent for page: " + pageNum + ": " + parentNum;
}
}
| NCIP/cadsr-cgmdr-nci-uk | src/org/exist/storage/btree/SetParentLoggable.java | Java | bsd-3-clause | 2,856 |
# -*- coding: utf8 -*-
"""
.. module:: burpui.misc.backend.burp2
:platform: Unix
:synopsis: Burp-UI burp2 backend module.
.. moduleauthor:: Ziirish <hi+burpui@ziirish.me>
"""
import re
import os
import time
import json
from collections import OrderedDict
from .burp1 import Burp as Burp1
from .interface import BUIbackend
from .utils.burp2 import Monitor
from .utils.constant import BURP_REVERSE_COUNTERS, BURP_STATUS_FORMAT_V2
from ..parser.burp2 import Parser
from ...utils import human_readable as _hr, utc_to_local
from ...exceptions import BUIserverException
from ..._compat import to_unicode
# Some functions are the same as in Burp1 backend
class Burp(Burp1):
"""The :class:`burpui.misc.backend.burp2.Burp` class provides a consistent
backend for ``burp-2`` servers.
It extends the :class:`burpui.misc.backend.burp1.Burp` class because a few
functions can be reused. The rest is just overrided.
:param server: ``Burp-UI`` server instance in order to access logger
and/or some global settings
:type server: :class:`burpui.engines.server.BUIServer`
:param conf: Configuration to use
:type conf: :class:`burpui.config.BUIConfig`
"""
# backend version
_vers = 2
# cache to store the guessed OS
_os_cache = {}
def __init__(self, server=None, conf=None):
"""
:param server: ``Burp-UI`` server instance in order to access logger
and/or some global settings
:type server: :class:`burpui.engines.server.BUIServer`
:param conf: Configuration to use
:type conf: :class:`burpui.config.BUIConfig`
"""
BUIbackend.__init__(self, server, conf)
self.monitor = Monitor(self.burpbin, self.burpconfcli, self.app, self.timeout)
self.batch_list_supported = self.monitor.batch_list_supported
self.parser = Parser(self)
self.logger.info(f"burp binary: {self.burpbin}")
self.logger.info(f"strip binary: {self.stripbin}")
self.logger.info(f"burp conf cli: {self.burpconfcli}")
self.logger.info(f"burp conf srv: {self.burpconfsrv}")
self.logger.info(f"command timeout: {self.timeout}")
self.logger.info(f"tmpdir: {self.tmpdir}")
self.logger.info(f"zip64: {self.zip64}")
self.logger.info(f"includes: {self.includes}")
self.logger.info(f"enforce: {self.enforce}")
self.logger.info(f"revoke: {self.revoke}")
self.logger.info(f"client version: {self.client_version}")
self.logger.info(f"server version: {self.server_version}")
@property
def client_version(self):
return self.monitor.client_version
@property
def server_version(self):
return self.monitor.server_version
@staticmethod
def _human_st_mode(mode):
"""Convert the st_mode returned by stat in human readable (ls-like)
format
"""
hur = ""
if os.path.stat.S_ISREG(mode):
hur = "-"
elif os.path.stat.S_ISLNK(mode):
hur = "l"
elif os.path.stat.S_ISSOCK(mode):
hur = "s"
elif os.path.stat.S_ISDIR(mode):
hur = "d"
elif os.path.stat.S_ISBLK(mode):
hur = "b"
elif os.path.stat.S_ISFIFO(mode):
hur = "p"
elif os.path.stat.S_ISCHR(mode):
hur = "c"
else:
hur = "-"
for who in "USR", "GRP", "OTH":
for perm in "R", "W", "X":
if mode & getattr(os.path.stat, "S_I" + perm + who):
hur += perm.lower()
else:
hur += "-"
return hur
def statistics(self, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.statistics`"""
return {
"alive": self.monitor.alive,
"server_version": self.server_version,
"client_version": self.client_version,
}
def status(self, query="c:\n", timeout=None, cache=True, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.status`"""
return self.monitor.status(query, timeout, cache)
def _get_backup_logs(self, number, client, forward=False, deep=False):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.get_backup_logs`
"""
ret = {}
ret2 = {}
if not client or not number:
return ret
query = self.status("c:{0}:b:{1}\n".format(client, number))
if not query:
return ret
try:
logs = query["clients"][0]["backups"][0]["logs"]["list"]
except KeyError:
self.logger.warning("No logs found")
return ret
if "backup_stats" in logs:
ret = self._parse_backup_stats(number, client, forward)
if "backup" in logs and deep:
ret2 = self._parse_backup_log(number, client)
ret.update(ret2)
ret["encrypted"] = False
if "files_enc" in ret and ret["files_enc"]["total"] > 0:
ret["encrypted"] = True
return ret
@staticmethod
def _do_parse_backup_log(data, client):
# tests ordered as the logs order
ret = OrderedDict()
ret["client_version"] = None
ret["protocol"] = 1
ret["is_windows"] = False
ret["server_version"] = None
if not data:
return ret
try:
log = data["clients"][0]["backups"][0]["logs"]["backup"]
except KeyError:
# Assume protocol 1 in all cases unless explicitly found Protocol 2
return ret
# pre-compile regex since they'll be called on every log line
regex = {
"client_version": re.compile(r"Client version: (\d+\.\d+\.\d+)$"),
"server_version": re.compile(
r"WARNING: Client '{}' version '\d+\.\d+\.\d+' does not match server version '(\d+\.\d+\.\d+)'. An upgrade is recommended.$".format(
client
)
),
"protocol": re.compile(r"Protocol: (\d)$"),
"is_windows": re.compile(r"Client is Windows$"),
}
expressions_list = list(ret.keys())
catching_expressions = ["client_version", "server_version", "protocol"]
casting_expressions = {
"protocol": int,
}
def __dummy(val):
return val
for line in log:
expressions = expressions_list
for expression in expressions:
if expression in catching_expressions:
catch = regex[expression].search(line)
if catch:
cast = casting_expressions.get(expression, __dummy)
ret[expression] = cast(catch.group(1))
# don't search this expression twice
expressions_list.remove(expression)
break
else:
if expression in regex and regex[expression].search(line):
ret[expression] = True
# don't search this expression twice
expressions_list.remove(expression)
break
return ret
def _parse_backup_log(self, number, client):
"""The :func:`burpui.misc.backend.burp2.Burp._parse_backup_log`
function helps you determine if the backup is protocol 2 or 1 and various
useful details.
:param number: Backup number to work on
:type number: int
:param client: Client name to work on
:type client: str
:returns: a dict with some useful details
"""
data = self.status("c:{0}:b:{1}:l:backup\n".format(client, number))
return self._do_parse_backup_log(data, client)
def _do_parse_backup_stats(
self, data, result, number, client, forward=False, agent=None
):
ret = {}
translate = {
"time_start": "start",
"time_end": "end",
"time_taken": "duration",
"bytes": "totsize",
"bytes_received": "received",
"bytes_estimated": "estimated_bytes",
"files": "files",
"files_encrypted": "files_enc",
"directories": "dir",
"soft_links": "softlink",
"hard_links": "hardlink",
"meta_data": "meta",
"meta_data_encrypted": "meta_enc",
"special_files": "special",
"efs_files": "efs",
"vss_headers": "vssheader",
"vss_headers_encrypted": "vssheader_enc",
"vss_footers": "vssfooter",
"vss_footers_encrypted": "vssfooter_enc",
"total": "total",
"grand_total": "total",
}
counts = {
"new": "count",
"changed": "changed",
"unchanged": "same",
"deleted": "deleted",
"total": "scanned",
"scanned": "scanned",
}
single = [
"time_start",
"time_end",
"time_taken",
"bytes_received",
"bytes_estimated",
"bytes",
]
if not data:
return ret
try:
back = data["clients"][0]["backups"][0]
except KeyError:
self.logger.warning("No backup found")
return ret
if "backup_stats" not in back["logs"]:
self.logger.warning("No stats found for backup")
return ret
stats = None
try:
stats = json.loads("".join(back["logs"]["backup_stats"]))
except:
stats = back["logs"]["backup_stats"]
if not stats:
return ret
# server was upgraded but backup comes from an older version
if "counters" not in stats:
return super(Burp, self)._parse_backup_stats(
number, client, forward, stats, agent
)
counters = stats["counters"]
for counter in counters:
name = counter["name"]
if name in translate:
name = translate[name]
if counter["name"] in single:
result[name] = counter["count"]
else:
result[name] = {}
for (key, val) in counts.items():
if val in counter:
result[name][key] = counter[val]
else:
result[name][key] = 0
if "start" in result and "end" in result:
result["duration"] = result["end"] - result["start"]
# convert utc timestamp to local
# example: 1468850307 -> 1468857507
result["start"] = utc_to_local(result["start"])
result["end"] = utc_to_local(result["end"])
# Needed for graphs
if "received" not in result:
result["received"] = 1
return result
def _parse_backup_stats(self, number, client, forward=False, agent=None):
"""The :func:`burpui.misc.backend.burp2.Burp._parse_backup_stats`
function is used to parse the burp logs.
:param number: Backup number to work on
:type number: int
:param client: Client name to work on
:type client: str
:param forward: Is the client name needed in later process
:type forward: bool
:param agent: What server to ask (only in multi-agent mode)
:type agent: str
:returns: Dict containing the backup log
"""
backup = {"os": self._guess_os(client), "number": int(number)}
if forward:
backup["name"] = client
query = self.status("c:{0}:b:{1}:l:backup_stats\n".format(client, number))
return self._do_parse_backup_stats(
query, backup, number, client, forward, agent
)
# TODO: support old clients
# NOTE: this should now be partly done since we fallback to the Burp1 code
# def _parse_backup_log(self, fh, number, client=None, agent=None):
# """
# parse_backup_log parses the log.gz of a given backup and returns a
# dict containing different stats used to render the charts in the
# reporting view
# """
# return {}
# def get_clients_report(self, clients, agent=None):
def get_counters(self, name=None, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.get_counters`"""
ret = {}
query = self.status("c:{0}\n".format(name), cache=False)
# check the status returned something
if not query:
return ret
try:
client = query["clients"][0]
except KeyError:
self.logger.warning("Client not found")
return ret
return self._do_get_counters(client)
def _do_get_counters(self, data):
ret = {}
client = data
# check the client is currently backing-up
if "run_status" not in client or client["run_status"] != "running":
return ret
backup = None
phases = ["working", "finishing"]
try:
for child in client["children"]:
if "action" in child and child["action"] == "backup":
backup = child
break
except KeyError:
for back in client["backups"]:
if "flags" in back and any(x in back["flags"] for x in phases):
backup = back
break
# check we found a working backup
if not backup:
return ret
# list of single counters (type CNTR_SINGLE_FIELD in cntr.c)
single = [
"bytes_estimated",
"bytes",
"bytes_received",
"bytes_sent",
"time_start",
"time_end",
"warnings",
"errors",
]
# translation table to be compatible with burp1
def translate(cntr):
translate_table = {"bytes_estimated": "estimated_bytes"}
try:
return translate_table[cntr]
except KeyError:
return cntr
for counter in backup.get("counters", {}):
name = translate(counter["name"])
if counter["name"] not in single:
# Prior burp-2.1.6 some counters are reversed
# See https://github.com/grke/burp/commit/adeb3ad68477303991a393fa7cd36bc94ff6b429
if self.server_version and self.server_version < BURP_REVERSE_COUNTERS:
ret[name] = [
counter["count"],
counter["same"], # reversed
counter["changed"], # reversed
counter["deleted"],
counter["scanned"],
]
else:
ret[name] = [
counter["count"],
counter["changed"],
counter["same"],
counter["deleted"],
counter["scanned"],
]
else:
ret[name] = counter["count"]
if "phase" in backup:
ret["phase"] = backup["phase"]
else:
for phase in phases:
if phase in backup.get("flags", []):
ret["phase"] = phase
break
if "bytes" not in ret:
ret["bytes"] = 0
if set(["time_start", "estimated_bytes", "bytes"]) <= set(ret.keys()):
try:
diff = time.time() - int(ret["time_start"])
byteswant = int(ret["estimated_bytes"])
bytesgot = int(ret["bytes"])
bytespersec = bytesgot / diff
bytesleft = byteswant - bytesgot
ret["speed"] = bytespersec
if bytespersec > 0:
timeleft = int(bytesleft / bytespersec)
ret["timeleft"] = timeleft
else:
ret["timeleft"] = -1
except:
ret["timeleft"] = -1
try:
ret["percent"] = round(
float(ret["bytes"]) / float(ret["estimated_bytes"]) * 100
)
except (ZeroDivisionError, KeyError):
# You know... division by 0
ret["percent"] = 0
return ret
def is_backup_running(self, name=None, agent=None):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.is_backup_running`
"""
if not name:
return False
try:
query = self.status("c:{0}\n".format(name))
except BUIserverException:
return False
return self._do_is_backup_running(query)
def _do_is_backup_running(self, data):
if data:
try:
return data["clients"][0]["run_status"] in ["running"]
except KeyError:
pass
return False
def is_one_backup_running(self, agent=None):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.is_one_backup_running`
"""
ret = []
try:
clients = self.get_all_clients(last_attempt=False)
except BUIserverException:
return ret
return self._do_is_one_backup_running(clients)
def _do_is_one_backup_running(self, data):
ret = []
for client in data:
if client["state"] in ["running"]:
ret.append(client["name"])
return ret
def _status_human_readable(self, status):
"""The label has changed in burp2, we override it to be compatible with
burp1's format
:param status: The status returned by the burp2 server
:type status: str
:returns: burp1 status compatible
"""
if not status:
return None
if status == "c crashed":
return "client crashed"
if status == "s crashed":
return "server crashed"
return status
def _get_last_backup(self, name, working=True):
"""Return the last backup of a given client
:param name: Name of the client
:type name: str
:param working: Also return uncomplete backups
:type working: bool
:returns: The last backup
"""
try:
clients = self.status("c:{}".format(name))
client = clients["clients"][0]
i = 0
while True:
ret = client["backups"][i]
if not working and "working" in ret["flags"]:
i += 1
continue
return ret
except (KeyError, TypeError, IndexError, BUIserverException):
return None
def _guess_os(self, name):
"""Return the OS of the given client based on the magic *os* label
:param name: Name of the client
:type name: str
:returns: The guessed OS of the client
::
grep label /etc/burp/clientconfdir/toto
label = os: Darwin OS
"""
ret = "Unknown"
if name in self._os_cache:
return self._os_cache[name]
labels = self.get_client_labels(name)
OSES = []
for label in labels:
if re.match("os:", label, re.IGNORECASE):
_os = label.split(":", 1)[1].strip()
if _os not in OSES:
OSES.append(_os)
if OSES:
ret = OSES[-1]
else:
# more aggressive check
last = self._get_last_backup(name, False)
if last:
try:
tree = self.get_tree(name, last["number"])
if tree[0]["name"] != "/":
ret = "Windows"
else:
ret = "Unix/Linux"
except (IndexError, KeyError, BUIserverException):
pass
self._os_cache[name] = ret
return ret
def get_all_clients(self, agent=None, last_attempt=True):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.get_all_clients`
"""
ret = []
query = self.status()
if not query or "clients" not in query:
return ret
clients = query["clients"]
for client in clients:
cli = {}
cli["name"] = client["name"]
cli["state"] = self._status_human_readable(client["run_status"])
infos = client["backups"]
if cli["state"] in ["running"]:
cli["last"] = "now"
cli["last_attempt"] = "now"
elif not infos:
cli["last"] = "never"
cli["last_attempt"] = "never"
else:
convert = True
infos = infos[0]
if self.server_version and self.server_version < BURP_STATUS_FORMAT_V2:
cli["last"] = infos["timestamp"]
convert = False
# only do deep inspection when server >= BURP_STATUS_FORMAT_V2
elif self.deep_inspection:
logs = self.get_backup_logs(infos["number"], client["name"])
cli["last"] = logs["start"]
else:
cli["last"] = utc_to_local(infos["timestamp"])
if last_attempt:
last_backup = self._get_last_backup(client["name"])
if convert:
cli["last_attempt"] = utc_to_local(last_backup["timestamp"])
else:
cli["last_attempt"] = last_backup["timestamp"]
ret.append(cli)
return ret
def get_client_status(self, name=None, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.get_client_status`"""
ret = {}
if not name:
return ret
query = self.status("c:{0}\n".format(name))
if not query:
return ret
try:
client = query["clients"][0]
except (KeyError, IndexError):
self.logger.warning("Client not found")
return ret
return self._do_get_client_status(client)
def _do_get_client_status(self, data):
ret = {}
client = data
ret["state"] = self._status_human_readable(client["run_status"])
infos = client["backups"]
if ret["state"] in ["running"]:
try:
ret["phase"] = client["phase"]
except KeyError:
for child in client.get("children", []):
if "action" in child and child["action"] == "backup":
ret["phase"] = child["phase"]
break
counters = self._do_get_counters(client)
if "percent" in counters:
ret["percent"] = counters["percent"]
else:
ret["percent"] = 0
ret["last"] = "now"
elif not infos:
ret["last"] = "never"
else:
infos = infos[0]
ret["last"] = infos["timestamp"]
return ret
def get_client(self, name=None, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.get_client`"""
return self.get_client_filtered(name)
def get_client_filtered(
self, name=None, limit=-1, page=None, start=None, end=None, agent=None
):
"""See :func:`burpui.misc.backend.interface.BUIbackend.get_client_filtered`"""
ret = []
if not name:
return ret
query = self.status("c:{0}\n".format(name))
if not query:
return ret
try:
backups = query["clients"][0]["backups"]
except (KeyError, IndexError):
self.logger.warning("Client not found")
return ret
for idx, backup in enumerate(backups):
# skip the first elements if we are in a page
if page and page > 1 and limit > 0:
if idx < (page - 1) * limit:
continue
back = {}
# skip running backups since data will be inconsistent
if "flags" in backup and "working" in backup["flags"]:
continue
back["number"] = backup["number"]
if "flags" in backup and "deletable" in backup["flags"]:
back["deletable"] = True
else:
back["deletable"] = False
back["date"] = backup["timestamp"]
# skip backups before "start"
if start and backup["timestamp"] < start:
continue
# skip backups after "end"
if end and backup["timestamp"] > end:
continue
def __get_log(client, bkp, res):
log = self.get_backup_logs(bkp["number"], client)
try:
res["encrypted"] = log["encrypted"]
try:
res["received"] = log["received"]
except KeyError:
res["received"] = 0
try:
res["size"] = log["totsize"]
except KeyError:
res["size"] = 0
res["end"] = log["end"]
# override date since the timestamp is odd
res["date"] = log["start"]
except Exception:
self.logger.warning("Unable to parse logs")
return None
return res
with_log = __get_log(name, backup, back)
if with_log:
ret.append(with_log)
# stop after "limit" elements
if page and page > 1 and limit > 0:
if idx >= page * limit:
break
elif limit > 0 and idx >= limit:
break
# Here we need to reverse the array so the backups are sorted by num
# ASC
ret.reverse()
return ret
def is_backup_deletable(self, name=None, backup=None, agent=None):
"""Check if a given backup is deletable"""
if not name or not backup:
return False
query = self.status("c:{0}:b:{1}\n".format(name, backup))
if not query:
return False
return self._do_is_backup_deletable(query)
def _do_is_backup_deletable(self, data):
query = data
try:
flags = query["clients"][0]["backups"][0]["flags"]
return "deletable" in flags
except KeyError:
return False
def _format_tree(self, data, top, level):
ret = []
if not data:
return ret
try:
backup = data["clients"][0]["backups"][0]
except KeyError:
return ret
for entry in backup["browse"]["entries"]:
data = {}
base = None
dirn = None
if top == "*":
base = os.path.basename(entry["name"])
dirn = os.path.dirname(entry["name"])
if entry["name"] == ".":
continue
else:
data["name"] = base or entry["name"]
data["mode"] = self._human_st_mode(entry["mode"])
if re.match("^(d|l)", data["mode"]):
data["type"] = "d"
data["folder"] = True
else:
data["type"] = "f"
data["folder"] = False
data["inodes"] = entry["nlink"]
data["uid"] = entry["uid"]
data["gid"] = entry["gid"]
data["parent"] = dirn or top
data["size"] = "{0:.1eM}".format(_hr(entry["size"]))
data["date"] = entry["mtime"]
data["fullname"] = (
os.path.join(top, entry["name"]) if top != "*" else entry["name"]
)
data["level"] = level
data["children"] = []
ret.append(data)
return ret
def get_tree(self, name=None, backup=None, root=None, level=-1, agent=None):
"""See :func:`burpui.misc.backend.interface.BUIbackend.get_tree`"""
if not name or not backup:
return []
if not root:
top = ""
else:
top = to_unicode(root)
# we know this operation may take a while so we arbitrary increase the
# read timeout
timeout = None
if top == "*":
timeout = max(self.timeout, 300)
query = self.status("c:{0}:b:{1}:p:{2}\n".format(name, backup, top), timeout)
return self._format_tree(query, top, level)
def get_client_version(self, agent=None):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.get_client_version`
"""
return self.client_version
def get_server_version(self, agent=None):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.get_server_version`
"""
if not self.server_version:
self.status()
return self.server_version
def get_client_labels(self, client=None, agent=None):
"""See
:func:`burpui.misc.backend.interface.BUIbackend.get_client_labels`
"""
ret = []
if not client:
return ret
# micro optimization since the status results are cached in memory for a
# couple seconds, using the same global query and iterating over it
# will be more efficient than filtering burp-side
query = self.status("c:\n")
if not query:
return ret
try:
for cli in query["clients"]:
if cli["name"] == client:
return cli["labels"]
except KeyError:
return ret
# Same as in Burp1 backend
# def restore_files(
# self,
# name=None,
# backup=None,
# files=None,
# strip=None,
# archive='zip',
# password=None,
# agent=None):
# def read_conf_cli(self, agent=None):
# def read_conf_srv(self, agent=None):
# def store_conf_cli(self, data, agent=None):
# def store_conf_srv(self, data, agent=None):
# def get_parser_attr(self, attr=None, agent=None):
| ziirish/burp-ui | burpui/misc/backend/burp2.py | Python | bsd-3-clause | 30,550 |
<?php
/*
* Copyright 2007-2011 Charles du Jeu <contact (at) cdujeu.me>
* This file is part of AjaXplorer.
*
* AjaXplorer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AjaXplorer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with AjaXplorer. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://www.ajaxplorer.info/>.
*/
defined('AJXP_EXEC') or die( 'Access not allowed');
require_once(AJXP_BIN_FOLDER . '/class.AbstractTest.php');
/**
* @package AjaXplorer_Plugins
* @subpackage Access
*/
class fsAccessTest extends AbstractTest
{
function fsAccessTest() { parent::AbstractTest("Filesystem Plugin", ""); }
/**
* Test Repository
*
* @param Repository $repo
* @return Boolean
*/
function doRepositoryTest($repo){
if ($repo->accessType != 'fs' ) return -1;
// Check the destination path
$this->failedInfo = "";
$path = $repo->getOption("PATH", false);
$createOpt = $repo->getOption("CREATE");
$create = (($createOpt=="true"||$createOpt===true)?true:false);
if(strstr($path, "AJXP_USER")!==false) return TRUE; // CANNOT TEST THIS CASE!
if (!$create && !@is_dir($path))
{
$this->failedInfo .= "Selected repository path ".$path." doesn't exist, and the CREATE option is false"; return FALSE;
}
else if (!$create && !is_writeable($path))
{ $this->failedInfo .= "Selected repository path ".$path." isn't writeable"; return FALSE; }
// Do more tests here
return TRUE;
}
};
?>
| Tlapi/Noodle | public/ajaxplorer/plugins/access.fs/test.fsAccess.php | PHP | bsd-3-clause | 2,083 |
<?php
namespace frontend\controllers;
use Yii;
use frontend\models\Produse;
use frontend\models\Produse_Search;
use frontend\models\LogStergere;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\models\Amanetare;
use yii\web\UploadedFile;
use yii\helpers\Json;
/**
* ProduseController implements the CRUD actions for Produse model.
*/
class ProduseController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Produse models.
* @return mixed
*/
public function actionIndex()
{
if(isset($_POST['situatie']))
{
$situatie=$_POST['situatie'];
if($situatie == 'amanetare' || $situatie == 'vandut') {
$actions = 0;
$delete = 0;
} else
{
if($situatie == 'amanetat' || $situatie == 'vandut') {
$actions = 0;
$delete = 0;
} else {
$actions = 1;
$delete = 1;
}
$searchModel = new Produse_Search();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$situatie);
$data['html'] = $this->renderPartial('partialindex', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
$data['actions'] = $actions;
$data['hasDelete'] = $delete;
return Json::encode($data);
}
else
{
$situatie = 'in stoc';
$searchModel = new Produse_Search();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$situatie);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
// public function actionIndex2()
// {
// $amanetare = new Amanetare();
// $amanetare->actualizareProduse();
// $searchModel = new Produse_Search();
// $dataProvider = $searchModel->search2(Yii::$app->request->queryParams);
// return $this->render('index', [
// 'searchModel' => $searchModel,
// 'dataProvider' => $dataProvider,
// ]);
// }
// public function actionIndex3()
// {
// $amanetare = new Amanetare();
// $amanetare->actualizareProduse();
// $searchModel = new Produse_Search();
// $dataProvider = $searchModel->search3(Yii::$app->request->queryParams);
// return $this->render('index', [
// 'searchModel' => $searchModel,
// 'dataProvider' => $dataProvider,
// ]);
// }
public function sendProductID($id)
{
return $id;
echo "Id-ul ". $id;
}
/**
* Displays a single Produse model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Produse model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Produse();
$model->situatie="in stoc";
if ($model->load(Yii::$app->request->post())) {
$model->file=UploadedFile::getInstance($model,'file');
if($model->file)
{
$imagepath='images/';
$model->foto= $imagepath . rand(10,100) . $model->file->name;
}
$model->save();
if($model->file)
{
$model->file->saveAs($model->foto);
}
return $this->redirect(['view', 'id' => $model->_cod]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Produse model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) ) {
$model->file=UploadedFile::getInstance($model,'file');
if($model->file)
{
$imagepath='images/';
$model->foto=$imagepath. rand (10,100). $model->file->name;
}
$model->save();
if($model->file){
$model->file->saveAs($model->foto);
}
return $this->redirect(['view', 'id' => $model->_cod]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Produse model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$logModel = new LogStergere();
$logModel->id_angajat = Yii::$app->user->id;
$logModel->value = $id;
$logModel->type = LogStergere::typeProdus;
if(!$logModel->save()) {
var_dump($logModel->errors); die();
}
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Produse model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Produse the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
public function findModel($id)
{
if (($model = Produse::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| Mitza1993/advanced | frontend/controllers/ProduseController.php | PHP | bsd-3-clause | 6,312 |
from enum import Enum
from typing import List, Any, cast
import yass
from tutorial.base_types_external import Integer
# shows how to use contract internal base types
class ExpirationHandler(yass.BaseTypeHandler):
def readBase(self, reader: yass.Reader) -> 'Expiration':
return Expiration(
reader.readZigZagInt()
)
def writeBase(self, value: 'Expiration', writer: yass.Writer) -> None:
writer.writeZigZagInt(value.year)
class Expiration:
TYPE_DESC = yass.TypeDesc(yass.FIRST_DESC_ID + 1, ExpirationHandler())
def __init__(self, year: int) -> None:
self.year = year
def __str__(self) -> str:
return f"{self.year}"
class PriceKind(Enum):
BID = 0
ASK = 1
class Price:
def __init__(self) -> None:
self.instrumentId: Integer = cast(Integer, None)
self.kind: PriceKind = cast(PriceKind, None)
self.value: Integer = cast(Integer, None)
@yass.abstract
class Instrument:
def __init__(self) -> None:
self.id: Integer = cast(Integer, None)
self.name: str = cast(str, None)
class SystemException(Exception):
def __init__(self) -> None:
self.details: str = cast(str, None)
@yass.abstract
class ApplicationException(Exception):
def __init__(self) -> None:
pass
class UnknownInstrumentsException(ApplicationException):
def __init__(self) -> None:
ApplicationException.__init__(self)
self.instrumentIds: List[Integer] = cast(List[Integer], None)
self.onlyNeededForTests1: Any = cast(Any, None)
self.onlyNeededForTests2: bytes = cast(bytes, None)
self.onlyNeededForTests3: Exception = cast(Exception, None)
class Node:
def __init__(self) -> None:
self.id: float = cast(float, None)
self.links: List[Node] = cast(List[Node], None)
self.next: Node = cast(Node, None)
class EchoService:
def echo(self, value: Any) -> Any:
raise NotImplementedError()
class PriceEngine:
def subscribe(self, instrumentIds: List[Integer]) -> None:
raise NotImplementedError()
class PriceListener:
def newPrices(self, prices: List[Price]) -> None:
raise NotImplementedError()
| softappeal/yass | py3/tutorial/generated/contract/__init__.py | Python | bsd-3-clause | 2,223 |
import re
from nexusmaker.tools import natsort
is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""")
class CognateParser(object):
UNIQUE_IDENTIFIER = "u_"
def __init__(self, strict=True, uniques=True, sort=True):
"""
Parses cognates.
- strict (default=True): remove dubious cognates (?)
- uniques (default=True): non-cognate items get unique states
- sort (default=True): normalise ordering with natsort (i.e. 2,1 => 1,2)
"""
self.uniques = uniques
self.strict = strict
self.sort = sort
self.unique_id = 0
def is_unique_cognateset(self, cog, labelled=False):
if not labelled:
return str(cog).startswith(self.UNIQUE_IDENTIFIER)
else:
return "_%s" % self.UNIQUE_IDENTIFIER in str(cog)
def _split_combined_cognate(self, cognate):
m = is_combined_cognate.findall(cognate)
return [m[0][0], cognate] if m else [cognate]
def get_next_unique(self):
if not self.uniques:
return []
self.unique_id = self.unique_id + 1
return ["%s%d" % (self.UNIQUE_IDENTIFIER, self.unique_id)]
def parse_cognate(self, value):
raw = value
if value is None:
return self.get_next_unique()
elif value == '':
return self.get_next_unique()
elif str(value).lower() == 's': # error
return self.get_next_unique()
elif 'x' in str(value).lower(): # error
return self.get_next_unique()
elif isinstance(value, str):
if value.startswith(","):
raise ValueError("Possible broken combined cognate %r" % raw)
if value.endswith("-"):
raise ValueError("Possible broken combined cognate %r" % raw)
elif ';' in value:
raise ValueError("Possible broken combined cognate %r" % raw)
value = value.replace('.', ',').replace("/", ",")
# parse out subcognates
value = [
self._split_combined_cognate(v.strip()) for v in value.split(",")
]
value = [item for sublist in value for item in sublist]
if self.strict:
# remove dubious cognates
value = [v for v in value if '?' not in v]
# exit if all are dubious, setting to unique state
if len(value) == 0:
return self.get_next_unique()
else:
value = [v.replace("?", "") for v in value]
# remove any empty things in the list
value = [v for v in value if len(v) > 0]
if self.sort:
value = natsort(value)
return value
else:
raise ValueError("%s" % type(value))
| SimonGreenhill/NexusMaker | nexusmaker/CognateParser.py | Python | bsd-3-clause | 2,824 |
#!/usr/bin/env python
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for analyzer
"""
import json
import TestGyp
found = 'Found dependency'
found_all = 'Found dependency (all)'
not_found = 'No dependencies'
def _CreateConfigFile(files, additional_compile_targets, test_targets=[]):
"""Creates the analyzer config file, which is used as the input to analyzer.
See description of analyzer.py for description of the arguments."""
f = open('test_file', 'w')
to_write = {'files': files,
'test_targets': test_targets,
'additional_compile_targets': additional_compile_targets }
json.dump(to_write, f)
f.close()
def _CreateBogusConfigFile():
f = open('test_file','w')
f.write('bogus')
f.close()
def _ReadOutputFileContents():
f = open('analyzer_output', 'r')
result = json.load(f)
f.close()
return result
# NOTE: this would be clearer if it subclassed TestGypCustom, but that trips
# over a bug in pylint (E1002).
test = TestGyp.TestGypCustom(format='analyzer')
def CommonArgs():
return ('-Gconfig_path=test_file',
'-Ganalyzer_output_path=analyzer_output')
def run_analyzer(*args, **kw):
"""Runs the test specifying a particular config and output path."""
args += CommonArgs()
test.run_gyp('test.gyp', *args, **kw)
def run_analyzer2(*args, **kw):
"""Same as run_analyzer(), but passes in test2.gyp instead of test.gyp."""
args += CommonArgs()
test.run_gyp('test2.gyp', *args, **kw)
def run_analyzer3(*args, **kw):
"""Same as run_analyzer(), but passes in test3.gyp instead of test.gyp."""
args += CommonArgs()
test.run_gyp('test3.gyp', *args, **kw)
def run_analyzer4(*args, **kw):
"""Same as run_analyzer(), but passes in test3.gyp instead of test.gyp."""
args += CommonArgs()
test.run_gyp('test4.gyp', *args, **kw)
def EnsureContains(matched=False, compile_targets=set(), test_targets=set()):
"""Verifies output contains |compile_targets|."""
result = _ReadOutputFileContents()
if result.get('error', None):
print 'unexpected error', result.get('error')
test.fail_test()
if result.get('invalid_targets', None):
print 'unexpected invalid_targets', result.get('invalid_targets')
test.fail_test()
actual_compile_targets = set(result['compile_targets'])
if actual_compile_targets != compile_targets:
print 'actual compile_targets:', actual_compile_targets, \
'\nexpected compile_targets:', compile_targets
test.fail_test()
actual_test_targets = set(result['test_targets'])
if actual_test_targets != test_targets:
print 'actual test_targets:', actual_test_targets, \
'\nexpected test_targets:', test_targets
test.fail_test()
if matched and result['status'] != found:
print 'expected', found, 'got', result['status']
test.fail_test()
elif not matched and result['status'] != not_found:
print 'expected', not_found, 'got', result['status']
test.fail_test()
def EnsureMatchedAll(compile_targets, test_targets=set()):
result = _ReadOutputFileContents()
if result.get('error', None):
print 'unexpected error', result.get('error')
test.fail_test()
if result.get('invalid_targets', None):
print 'unexpected invalid_targets', result.get('invalid_targets')
test.fail_test()
if result['status'] != found_all:
print 'expected', found_all, 'got', result['status']
test.fail_test()
actual_compile_targets = set(result['compile_targets'])
if actual_compile_targets != compile_targets:
print ('actual compile_targets:', actual_compile_targets,
'\nexpected compile_targets:', compile_targets)
test.fail_test()
actual_test_targets = set(result['test_targets'])
if actual_test_targets != test_targets:
print ('actual test_targets:', actual_test_targets,
'\nexpected test_targets:', test_targets)
test.fail_test()
def EnsureError(expected_error_string):
"""Verifies output contains the error string."""
result = _ReadOutputFileContents()
if result.get('error', '').find(expected_error_string) == -1:
print 'actual error:', result.get('error', ''), '\nexpected error:', \
expected_error_string
test.fail_test()
def EnsureStdoutContains(expected_error_string):
if test.stdout().find(expected_error_string) == -1:
print 'actual stdout:', test.stdout(), '\nexpected stdout:', \
expected_error_string
test.fail_test()
def EnsureInvalidTargets(expected_invalid_targets):
"""Verifies output contains invalid_targets."""
result = _ReadOutputFileContents()
actual_invalid_targets = set(result['invalid_targets'])
if actual_invalid_targets != expected_invalid_targets:
print 'actual invalid_targets:', actual_invalid_targets, \
'\nexpected :', expected_invalid_targets
test.fail_test()
# Two targets, A and B (both static_libraries) and A depends upon B. If a file
# in B changes, then both A and B are output. It is not strictly necessary that
# A is compiled in this case, only B.
_CreateConfigFile(['b.c'], ['all'])
test.run_gyp('static_library_test.gyp', *CommonArgs())
EnsureContains(matched=True, compile_targets={'a' ,'b'})
# Verifies config_path must be specified.
test.run_gyp('test.gyp')
EnsureStdoutContains('Must specify files to analyze via config_path')
# Verifies config_path must point to a valid file.
test.run_gyp('test.gyp', '-Gconfig_path=bogus_file',
'-Ganalyzer_output_path=analyzer_output')
EnsureError('Unable to open file bogus_file')
# Verify 'invalid_targets' is present when bad target is specified.
_CreateConfigFile(['exe2.c'], ['bad_target'])
run_analyzer()
EnsureInvalidTargets({'bad_target'})
# Verifies config_path must point to a valid json file.
_CreateBogusConfigFile()
run_analyzer()
EnsureError('Unable to parse config file test_file')
# Trivial test of a source.
_CreateConfigFile(['foo.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Conditional source that is excluded.
_CreateConfigFile(['conditional_source.c'], ['all'])
run_analyzer()
EnsureContains(matched=False)
# Conditional source that is included by way of argument.
_CreateConfigFile(['conditional_source.c'], ['all'])
run_analyzer('-Dtest_variable=1')
EnsureContains(matched=True, compile_targets={'exe'})
# Two unknown files.
_CreateConfigFile(['unknown1.c', 'unoknow2.cc'], ['all'])
run_analyzer()
EnsureContains()
# Two unknown files.
_CreateConfigFile(['unknown1.c', 'subdir/subdir_sourcex.c'], ['all'])
run_analyzer()
EnsureContains()
# Included dependency
_CreateConfigFile(['unknown1.c', 'subdir/subdir_source.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe', 'exe3'})
# Included inputs to actions.
_CreateConfigFile(['action_input.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Don't consider outputs.
_CreateConfigFile(['action_output.c'], ['all'])
run_analyzer()
EnsureContains(matched=False)
# Rule inputs.
_CreateConfigFile(['rule_input.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Ignore path specified with PRODUCT_DIR.
_CreateConfigFile(['product_dir_input.c'], ['all'])
run_analyzer()
EnsureContains(matched=False)
# Path specified via a variable.
_CreateConfigFile(['subdir/subdir_source2.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Verifies paths with // are fixed up correctly.
_CreateConfigFile(['parent_source.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe', 'exe3'})
# Verifies relative paths are resolved correctly.
_CreateConfigFile(['subdir/subdir_source.h'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Verifies relative paths in inputs are resolved correctly.
_CreateConfigFile(['rel_path1.h'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Various permutations when passing in targets.
_CreateConfigFile(['exe2.c', 'subdir/subdir2b_source.c'],
['all'], ['exe', 'exe3'])
run_analyzer()
EnsureContains(matched=True, test_targets={'exe3'},
compile_targets={'exe2', 'exe3'})
_CreateConfigFile(['exe2.c', 'subdir/subdir2b_source.c'], ['all'], ['exe'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2', 'exe3'})
# Verifies duplicates are ignored.
_CreateConfigFile(['exe2.c', 'subdir/subdir2b_source.c'], ['all'],
['exe', 'exe'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2', 'exe3'})
_CreateConfigFile(['exe2.c'], ['all'], ['exe'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2'})
_CreateConfigFile(['exe2.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2'})
_CreateConfigFile(['subdir/subdir2b_source.c', 'exe2.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2', 'exe3'})
_CreateConfigFile(['subdir/subdir2b_source.c'], ['all'], ['exe3'])
run_analyzer()
EnsureContains(matched=True, test_targets={'exe3'}, compile_targets={'exe3'})
_CreateConfigFile(['exe2.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2'})
_CreateConfigFile(['foo.c'], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe'})
# Assertions when modifying build (gyp/gypi) files, especially when said files
# are included.
_CreateConfigFile(['subdir2/d.cc'], ['all'], ['exe', 'exe2', 'foo', 'exe3'])
run_analyzer2()
EnsureContains(matched=True, test_targets={'exe', 'foo'},
compile_targets={'exe'})
_CreateConfigFile(['subdir2/subdir.includes.gypi'], ['all'],
['exe', 'exe2', 'foo', 'exe3'])
run_analyzer2()
EnsureContains(matched=True, test_targets={'exe', 'foo'},
compile_targets={'exe'})
_CreateConfigFile(['subdir2/subdir.gyp'], ['all'],
['exe', 'exe2', 'foo', 'exe3'])
run_analyzer2()
EnsureContains(matched=True, test_targets={'exe', 'foo'},
compile_targets={'exe'})
_CreateConfigFile(['test2.includes.gypi'], ['all'],
['exe', 'exe2', 'foo', 'exe3'])
run_analyzer2()
EnsureContains(matched=True, test_targets={'exe', 'exe2', 'exe3'},
compile_targets={'exe', 'exe2', 'exe3'})
# Verify modifying a file included makes all targets dirty.
_CreateConfigFile(['common.gypi'], ['all'], ['exe', 'exe2', 'foo', 'exe3'])
run_analyzer2('-Icommon.gypi')
EnsureMatchedAll({'all', 'exe', 'exe2', 'foo', 'exe3'},
{'exe', 'exe2', 'foo', 'exe3'})
# Assertions from test3.gyp.
_CreateConfigFile(['d.c', 'f.c'], ['all'], ['a'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a', 'b'})
_CreateConfigFile(['f.c'], ['all'], ['a'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a', 'b'})
_CreateConfigFile(['f.c'], ['all'])
run_analyzer3()
EnsureContains(matched=True, compile_targets={'a', 'b'})
_CreateConfigFile(['c.c', 'e.c'], ['all'])
run_analyzer3()
EnsureContains(matched=True, compile_targets={'a', 'b', 'c', 'e'})
_CreateConfigFile(['d.c'], ['all'], ['a'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a', 'b'})
_CreateConfigFile(['a.c'], ['all'], ['a', 'b'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a'})
_CreateConfigFile(['a.c'], ['all'], ['a', 'b'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a'})
_CreateConfigFile(['d.c'], ['all'], ['a', 'b'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a', 'b'},
compile_targets={'a', 'b'})
_CreateConfigFile(['f.c'], ['all'], ['a'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a', 'b'})
_CreateConfigFile(['a.c'], ['all'], ['a'])
run_analyzer3()
EnsureContains(matched=True, test_targets={'a'}, compile_targets={'a'})
_CreateConfigFile(['a.c'], ['all'])
run_analyzer3()
EnsureContains(matched=True, compile_targets={'a'})
_CreateConfigFile(['d.c'], ['all'])
run_analyzer3()
EnsureContains(matched=True, compile_targets={'a', 'b'})
# Assertions around test4.gyp.
_CreateConfigFile(['f.c'], ['all'])
run_analyzer4()
EnsureContains(matched=True, compile_targets={'e', 'f'})
_CreateConfigFile(['d.c'], ['all'])
run_analyzer4()
EnsureContains(matched=True, compile_targets={'a', 'b', 'c', 'd'})
_CreateConfigFile(['i.c'], ['all'])
run_analyzer4()
EnsureContains(matched=True, compile_targets={'h', 'i'})
# Assertions where 'all' is not supplied in compile_targets.
_CreateConfigFile(['exe2.c'], [], ['exe2'])
run_analyzer()
EnsureContains(matched=True, test_targets={'exe2'}, compile_targets={'exe2'})
_CreateConfigFile(['exe20.c'], [], ['exe2'])
run_analyzer()
EnsureContains(matched=False)
_CreateConfigFile(['exe2.c', 'exe3.c'], [], ['exe2', 'exe3'])
run_analyzer()
EnsureContains(matched=True, test_targets={'exe2', 'exe3'},
compile_targets={'exe2', 'exe3'})
_CreateConfigFile(['exe2.c', 'exe3.c'], ['exe3'], ['exe2'])
run_analyzer()
EnsureContains(matched=True, test_targets={'exe2'},
compile_targets={'exe2', 'exe3'})
_CreateConfigFile(['exe3.c'], ['exe2'], ['exe2'])
run_analyzer()
EnsureContains(matched=False)
# Assertions with 'all' listed as a test_target.
_CreateConfigFile(['exe3.c'], [], ['all'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe3'}, test_targets={'all'})
_CreateConfigFile(['exe2.c'], [], ['all', 'exe2'])
run_analyzer()
EnsureContains(matched=True, compile_targets={'exe2'},
test_targets={'all', 'exe2'})
test.pass_test()
| pnigos/gyp | test/analyzer/gyptest-analyzer.py | Python | bsd-3-clause | 13,761 |
# Join model between {Mdm::Service} and {Mdm::Task} that signifies that the {#task} found the {#service}.
class Mdm::TaskService < ApplicationRecord
#
# Associations
#
# The {Mdm::Service} found by {#task}.
belongs_to :service,
class_name: 'Mdm::Service',
inverse_of: :task_services
# An {Mdm::Task} that found {#service}.
belongs_to :task,
class_name: 'Mdm::Task',
inverse_of: :task_services
#
# Attributes
#
# @!attribute created_at
# When this task service was created.
#
# @return [DateTime]
# @!attribute updated_at
# The last time this task service was updated.
#
# @return [DateTime]
#
# Validations
#
validates :service_id,
:uniqueness => {
:scope => :task_id
}
Metasploit::Concern.run(self)
end
| rapid7/metasploit_data_models | app/models/mdm/task_service.rb | Ruby | bsd-3-clause | 858 |
/*
* Copyright (c) 2004-2021, University of Oslo
* 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 the HISP 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 OWNER 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 org.hisp.dhis.android.testapp.fileresource;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import org.apache.commons.io.FileUtils;
import org.hisp.dhis.android.core.arch.helpers.FileResourceDirectoryHelper;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.common.State;
import org.hisp.dhis.android.core.data.fileresource.RandomGeneratedInputStream;
import org.hisp.dhis.android.core.fileresource.FileResource;
import org.hisp.dhis.android.core.fileresource.FileResourceTableInfo;
import org.hisp.dhis.android.core.fileresource.internal.FileResourceUtil;
import org.hisp.dhis.android.core.maintenance.D2Error;
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestFullDispatcher;
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner;
import org.hisp.dhis.android.core.wipe.internal.TableWiper;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import static com.google.common.truth.Truth.assertThat;
@RunWith(D2JunitRunner.class)
public class FileResourceCollectionRepositoryMockIntegrationShould extends BaseMockIntegrationTestFullDispatcher {
@Test
public void find_all() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_uid() throws D2Error, IOException {
cleanFileResources();
String fileUid = d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byUid().eq(fileUid)
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_name() throws D2Error, IOException {
cleanFileResources();
String fileUid = d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byName().eq(fileUid+ ".png")
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_last_updated() throws D2Error, IOException, ParseException {
cleanFileResources();
String BEFORE_DATE = "2007-12-24T12:24:25.203";
Date created = BaseIdentifiableObject.DATE_FORMAT.parse(BEFORE_DATE);
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byLastUpdated().after(created)
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_content_type() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byContentType().eq("image/png")
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_path() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byPath().like("files/sdk_resources")
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_state() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.bySyncState().eq(State.TO_POST)
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void filter_by_content_length() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources().blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources()
.byContentLength().eq(1024L)
.blockingGet();
assertThat(fileResources.size()).isEqualTo(1);
}
@Test
public void add_fileResources_to_the_repository() throws D2Error, IOException {
cleanFileResources();
List<FileResource> fileResources1 = d2.fileResourceModule().fileResources().blockingGet();
assertThat(fileResources1.size()).isEqualTo(0);
File file = getFile();
assertThat(file.exists()).isTrue();
String fileResourceUid = d2.fileResourceModule().fileResources().blockingAdd(file);
List<FileResource> fileResources2 = d2.fileResourceModule().fileResources().blockingGet();
assertThat(fileResources2.size()).isEqualTo(1);
FileResource fileResource = d2.fileResourceModule().fileResources().uid(fileResourceUid).blockingGet();
assertThat(fileResource.uid()).isEqualTo(fileResourceUid);
File savedFile = new File(fileResource.path());
assertThat(savedFile.exists()).isTrue();
}
private File getFile() {
InputStream inputStream = new RandomGeneratedInputStream(1024);
Context context = InstrumentationRegistry.getInstrumentation().getContext();
File destinationFile = new File(FileResourceDirectoryHelper.getFileResourceDirectory(context), "file1.png");
return FileResourceUtil.writeInputStream(inputStream, destinationFile, 1024);
}
private void cleanFileResources() throws IOException {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
FileUtils.cleanDirectory(FileResourceDirectoryHelper.getFileResourceDirectory(context));
new TableWiper(databaseAdapter).wipeTable(FileResourceTableInfo.TABLE_INFO);
}
} | dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/testapp/fileresource/FileResourceCollectionRepositoryMockIntegrationShould.java | Java | bsd-3-clause | 8,166 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Limitless - Responsive Web Application Kit by Eugene Kopyov</title>
<!-- Global stylesheets -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
<link href="assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
<link href="assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="assets/css/core.css" rel="stylesheet" type="text/css">
<link href="assets/css/components.css" rel="stylesheet" type="text/css">
<link href="assets/css/colors.css" rel="stylesheet" type="text/css">
<!-- /global stylesheets -->
<!-- Core JS files -->
<script type="text/javascript" src="assets/js/plugins/loaders/pace.min.js"></script>
<script type="text/javascript" src="assets/js/core/libraries/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/core/libraries/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/plugins/loaders/blockui.min.js"></script>
<!-- /core JS files -->
<!-- Theme JS files -->
<script type="text/javascript" src="assets/js/plugins/visualization/d3/d3.min.js"></script>
<script type="text/javascript" src="assets/js/plugins/visualization/dimple/dimple.min.js"></script>
<script type="text/javascript" src="assets/js/core/app.js"></script>
<script type="text/javascript" src="assets/js/charts/dimple/area/area_horizontal.js"></script>
<script type="text/javascript" src="assets/js/charts/dimple/area/area_horizontal_stacked.js"></script>
<script type="text/javascript" src="assets/js/charts/dimple/area/area_horizontal_stacked_normalized.js"></script>
<script type="text/javascript" src="assets/js/charts/dimple/area/area_horizontal_grouped.js"></script>
<script type="text/javascript" src="assets/js/charts/dimple/area/area_horizontal_stacked_grouped.js"></script>
<!-- /theme JS files -->
</head>
<body>
<!-- Main navbar -->
<div class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="index.html"><img src="assets/images/logo_light.png" alt=""></a>
<ul class="nav navbar-nav pull-right visible-xs-block">
<li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
<li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
</div>
<div class="navbar-collapse collapse" id="navbar-mobile">
<ul class="nav navbar-nav">
<li>
<a class="sidebar-control sidebar-main-toggle hidden-xs">
<i class="icon-paragraph-justify3"></i>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-git-compare"></i>
<span class="visible-xs-inline-block position-right">Git updates</span>
<span class="badge bg-warning-400">9</span>
</a>
<div class="dropdown-menu dropdown-content">
<div class="dropdown-content-heading">
Git updates
<ul class="icons-list">
<li><a href="#"><i class="icon-sync"></i></a></li>
</ul>
</div>
<ul class="media-list dropdown-content-body width-350">
<li class="media">
<div class="media-left">
<a href="#" class="btn border-primary text-primary btn-flat btn-rounded btn-icon btn-sm"><i class="icon-git-pull-request"></i></a>
</div>
<div class="media-body">
Drop the IE <a href="#">specific hacks</a> for temporal inputs
<div class="media-annotation">4 minutes ago</div>
</div>
</li>
<li class="media">
<div class="media-left">
<a href="#" class="btn border-warning text-warning btn-flat btn-rounded btn-icon btn-sm"><i class="icon-git-commit"></i></a>
</div>
<div class="media-body">
Add full font overrides for popovers and tooltips
<div class="media-annotation">36 minutes ago</div>
</div>
</li>
<li class="media">
<div class="media-left">
<a href="#" class="btn border-info text-info btn-flat btn-rounded btn-icon btn-sm"><i class="icon-git-branch"></i></a>
</div>
<div class="media-body">
<a href="#">Chris Arney</a> created a new <span class="text-semibold">Design</span> branch
<div class="media-annotation">2 hours ago</div>
</div>
</li>
<li class="media">
<div class="media-left">
<a href="#" class="btn border-success text-success btn-flat btn-rounded btn-icon btn-sm"><i class="icon-git-merge"></i></a>
</div>
<div class="media-body">
<a href="#">Eugene Kopyov</a> merged <span class="text-semibold">Master</span> and <span class="text-semibold">Dev</span> branches
<div class="media-annotation">Dec 18, 18:36</div>
</div>
</li>
<li class="media">
<div class="media-left">
<a href="#" class="btn border-primary text-primary btn-flat btn-rounded btn-icon btn-sm"><i class="icon-git-pull-request"></i></a>
</div>
<div class="media-body">
Have Carousel ignore keyboard events
<div class="media-annotation">Dec 12, 05:46</div>
</div>
</li>
</ul>
<div class="dropdown-content-footer">
<a href="#" data-popup="tooltip" title="All activity"><i class="icon-menu display-block"></i></a>
</div>
</div>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-people"></i>
<span class="visible-xs-inline-block position-right">Users</span>
</a>
<div class="dropdown-menu dropdown-content">
<div class="dropdown-content-heading">
Users online
<ul class="icons-list">
<li><a href="#"><i class="icon-gear"></i></a></li>
</ul>
</div>
<ul class="media-list dropdown-content-body width-300">
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading text-semibold">Jordana Ansley</a>
<span class="display-block text-muted text-size-small">Lead web developer</span>
</div>
<div class="media-right media-middle"><span class="status-mark border-success"></span></div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading text-semibold">Will Brason</a>
<span class="display-block text-muted text-size-small">Marketing manager</span>
</div>
<div class="media-right media-middle"><span class="status-mark border-danger"></span></div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading text-semibold">Hanna Walden</a>
<span class="display-block text-muted text-size-small">Project manager</span>
</div>
<div class="media-right media-middle"><span class="status-mark border-success"></span></div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading text-semibold">Dori Laperriere</a>
<span class="display-block text-muted text-size-small">Business developer</span>
</div>
<div class="media-right media-middle"><span class="status-mark border-warning-300"></span></div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading text-semibold">Vanessa Aurelius</a>
<span class="display-block text-muted text-size-small">UX expert</span>
</div>
<div class="media-right media-middle"><span class="status-mark border-grey-400"></span></div>
</li>
</ul>
<div class="dropdown-content-footer">
<a href="#" data-popup="tooltip" title="All users"><i class="icon-menu display-block"></i></a>
</div>
</div>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-bubbles4"></i>
<span class="visible-xs-inline-block position-right">Messages</span>
<span class="badge bg-warning-400">2</span>
</a>
<div class="dropdown-menu dropdown-content width-350">
<div class="dropdown-content-heading">
Messages
<ul class="icons-list">
<li><a href="#"><i class="icon-compose"></i></a></li>
</ul>
</div>
<ul class="media-list dropdown-content-body">
<li class="media">
<div class="media-left">
<img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt="">
<span class="badge bg-danger-400 media-badge">5</span>
</div>
<div class="media-body">
<a href="#" class="media-heading">
<span class="text-semibold">James Alexander</span>
<span class="media-annotation pull-right">04:58</span>
</a>
<span class="text-muted">who knows, maybe that would be the best thing for me...</span>
</div>
</li>
<li class="media">
<div class="media-left">
<img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt="">
<span class="badge bg-danger-400 media-badge">4</span>
</div>
<div class="media-body">
<a href="#" class="media-heading">
<span class="text-semibold">Margo Baker</span>
<span class="media-annotation pull-right">12:16</span>
</a>
<span class="text-muted">That was something he was unable to do because...</span>
</div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading">
<span class="text-semibold">Jeremy Victorino</span>
<span class="media-annotation pull-right">22:48</span>
</a>
<span class="text-muted">But that would be extremely strained and suspicious...</span>
</div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading">
<span class="text-semibold">Beatrix Diaz</span>
<span class="media-annotation pull-right">Tue</span>
</a>
<span class="text-muted">What a strenuous career it is that I've chosen...</span>
</div>
</li>
<li class="media">
<div class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></div>
<div class="media-body">
<a href="#" class="media-heading">
<span class="text-semibold">Richard Vango</span>
<span class="media-annotation pull-right">Mon</span>
</a>
<span class="text-muted">Other travelling salesmen live a life of luxury...</span>
</div>
</li>
</ul>
<div class="dropdown-content-footer">
<a href="#" data-popup="tooltip" title="All messages"><i class="icon-menu display-block"></i></a>
</div>
</div>
</li>
<li class="dropdown dropdown-user">
<a class="dropdown-toggle" data-toggle="dropdown">
<img src="assets/images/placeholder.jpg" alt="">
<span>Victoria</span>
<i class="caret"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#"><i class="icon-user-plus"></i> My profile</a></li>
<li><a href="#"><i class="icon-coins"></i> My balance</a></li>
<li><a href="#"><span class="badge badge-warning pull-right">58</span> <i class="icon-comment-discussion"></i> Messages</a></li>
<li class="divider"></li>
<li><a href="#"><i class="icon-cog5"></i> Account settings</a></li>
<li><a href="#"><i class="icon-switch2"></i> Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
<!-- /main navbar -->
<!-- Page container -->
<div class="page-container">
<!-- Page content -->
<div class="page-content">
<!-- Main sidebar -->
<div class="sidebar sidebar-main">
<div class="sidebar-content">
<!-- User menu -->
<div class="sidebar-user">
<div class="category-content">
<div class="media">
<a href="#" class="media-left"><img src="assets/images/placeholder.jpg" class="img-circle img-sm" alt=""></a>
<div class="media-body">
<span class="media-heading text-semibold">Victoria Baker</span>
<div class="text-size-mini text-muted">
<i class="icon-pin text-size-small"></i> Santa Ana, CA
</div>
</div>
<div class="media-right media-middle">
<ul class="icons-list">
<li>
<a href="#"><i class="icon-cog3"></i></a>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- /user menu -->
<!-- Main navigation -->
<div class="sidebar-category sidebar-category-visible">
<div class="category-content no-padding">
<ul class="navigation navigation-main navigation-accordion">
<!-- Main -->
<li class="navigation-header"><span>Main</span> <i class="icon-menu" title="Main pages"></i></li>
<li><a href="index.html"><i class="icon-home4"></i> <span>Dashboard</span></a></li>
<li>
<a href="#"><i class="icon-stack2"></i> <span>Page layouts</span></a>
<ul>
<li><a href="layout_navbar_fixed.html">Fixed navbar</a></li>
<li><a href="layout_navbar_sidebar_fixed.html">Fixed navbar & sidebar</a></li>
<li><a href="layout_sidebar_fixed_native.html">Fixed sidebar native scroll</a></li>
<li><a href="layout_navbar_hideable.html">Hideable navbar</a></li>
<li><a href="layout_navbar_hideable_sidebar.html">Hideable & fixed sidebar</a></li>
<li><a href="layout_footer_fixed.html">Fixed footer</a></li>
<li class="navigation-divider"></li>
<li><a href="boxed_default.html">Boxed with default sidebar</a></li>
<li><a href="boxed_mini.html">Boxed with mini sidebar</a></li>
<li><a href="boxed_full.html">Boxed full width</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-copy"></i> <span>Layouts</span></a>
<ul>
<li><a href="index.html" id="layout1">Layout 1 <span class="label bg-warning-400">Current</span></a></li>
<li><a href="../../layout_2/LTR/index.html" id="layout2">Layout 2</a></li>
<li><a href="../../layout_3/LTR/index.html" id="layout3">Layout 3</a></li>
<li><a href="../../layout_4/LTR/index.html" id="layout4">Layout 4</a></li>
<li class="disabled"><a href="../../layout_5/LTR/index.html" id="layout5">Layout 5 <span class="label">Coming soon</span></a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-droplet2"></i> <span>Color system</span></a>
<ul>
<li><a href="colors_primary.html">Primary palette</a></li>
<li><a href="colors_danger.html">Danger palette</a></li>
<li><a href="colors_success.html">Success palette</a></li>
<li><a href="colors_warning.html">Warning palette</a></li>
<li><a href="colors_info.html">Info palette</a></li>
<li class="navigation-divider"></li>
<li><a href="colors_pink.html">Pink palette</a></li>
<li><a href="colors_violet.html">Violet palette</a></li>
<li><a href="colors_purple.html">Purple palette</a></li>
<li><a href="colors_indigo.html">Indigo palette</a></li>
<li><a href="colors_blue.html">Blue palette</a></li>
<li><a href="colors_teal.html">Teal palette</a></li>
<li><a href="colors_green.html">Green palette</a></li>
<li><a href="colors_orange.html">Orange palette</a></li>
<li><a href="colors_brown.html">Brown palette</a></li>
<li><a href="colors_grey.html">Grey palette</a></li>
<li><a href="colors_slate.html">Slate palette</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-stack"></i> <span>Starter kit</span></a>
<ul>
<li><a href="starters/horizontal_nav.html">Horizontal navigation</a></li>
<li><a href="starters/1_col.html">1 column</a></li>
<li><a href="starters/2_col.html">2 columns</a></li>
<li>
<a href="#">3 columns</a>
<ul>
<li><a href="starters/3_col_dual.html">Dual sidebars</a></li>
<li><a href="starters/3_col_double.html">Double sidebars</a></li>
</ul>
</li>
<li><a href="starters/4_col.html">4 columns</a></li>
<li>
<a href="#">Detached layout</a>
<ul>
<li><a href="starters/detached_left.html">Left sidebar</a></li>
<li><a href="starters/detached_right.html">Right sidebar</a></li>
<li><a href="starters/detached_sticky.html">Sticky sidebar</a></li>
</ul>
</li>
<li><a href="starters/layout_boxed.html">Boxed layout</a></li>
<li class="navigation-divider"></li>
<li><a href="starters/layout_navbar_fixed_main.html">Fixed main navbar</a></li>
<li><a href="starters/layout_navbar_fixed_secondary.html">Fixed secondary navbar</a></li>
<li><a href="starters/layout_navbar_fixed_both.html">Both navbars fixed</a></li>
<li><a href="starters/layout_fixed.html">Fixed layout</a></li>
</ul>
</li>
<li><a href="changelog.html"><i class="icon-list-unordered"></i> <span>Changelog <span class="label bg-blue-400">1.2.1</span></span></a></li>
<li><a href="../RTL/index.html"><i class="icon-width"></i> <span>RTL version</span></a></li>
<!-- /main -->
<!-- Forms -->
<li class="navigation-header"><span>Forms</span> <i class="icon-menu" title="Forms"></i></li>
<li>
<a href="#"><i class="icon-pencil3"></i> <span>Form components</span></a>
<ul>
<li><a href="form_inputs_basic.html">Basic inputs</a></li>
<li><a href="form_checkboxes_radios.html">Checkboxes & radios</a></li>
<li><a href="form_input_groups.html">Input groups</a></li>
<li><a href="form_controls_extended.html">Extended controls</a></li>
<li>
<a href="#">Selects</a>
<ul>
<li><a href="form_select2.html">Select2 selects</a></li>
<li><a href="form_multiselect.html">Bootstrap multiselect</a></li>
<li><a href="form_select_box_it.html">SelectBoxIt selects</a></li>
<li><a href="form_bootstrap_select.html">Bootstrap selects</a></li>
</ul>
</li>
<li><a href="form_tag_inputs.html">Tag inputs</a></li>
<li><a href="form_dual_listboxes.html">Dual Listboxes</a></li>
<li><a href="form_editable.html">Editable forms</a></li>
<li><a href="form_validation.html">Validation</a></li>
<li><a href="form_inputs_grid.html">Inputs grid</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-footprint"></i> <span>Wizards</span></a>
<ul>
<li><a href="wizard_steps.html">Steps wizard</a></li>
<li><a href="wizard_form.html">Form wizard</a></li>
<li><a href="wizard_stepy.html">Stepy wizard</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-spell-check"></i> <span>Editors</span></a>
<ul>
<li><a href="editor_summernote.html">Summernote editor</a></li>
<li><a href="editor_ckeditor.html">CKEditor</a></li>
<li><a href="editor_wysihtml5.html">WYSIHTML5 editor</a></li>
<li><a href="editor_code.html">Code editor</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-select2"></i> <span>Pickers</span></a>
<ul>
<li><a href="picker_date.html">Date & time pickers</a></li>
<li><a href="picker_color.html">Color pickers</a></li>
<li><a href="picker_location.html">Location pickers</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-insert-template"></i> <span>Form layouts</span></a>
<ul>
<li><a href="form_layout_vertical.html">Vertical form</a></li>
<li><a href="form_layout_horizontal.html">Horizontal form</a></li>
</ul>
</li>
<!-- /forms -->
<!-- Appearance -->
<li class="navigation-header"><span>Appearance</span> <i class="icon-menu" title="Appearance"></i></li>
<li>
<a href="#"><i class="icon-grid"></i> <span>Components</span></a>
<ul>
<li><a href="components_modals.html">Modals</a></li>
<li><a href="components_dropdowns.html">Dropdown menus</a></li>
<li><a href="components_tabs.html">Tabs component</a></li>
<li><a href="components_pills.html">Pills component</a></li>
<li><a href="components_navs.html">Accordion and navs</a></li>
<li><a href="components_buttons.html">Buttons</a></li>
<li><a href="components_notifications_pnotify.html">PNotify notifications</a></li>
<li><a href="components_notifications_others.html">Other notifications</a></li>
<li><a href="components_popups.html">Tooltips and popovers</a></li>
<li><a href="components_alerts.html">Alerts</a></li>
<li><a href="components_pagination.html">Pagination</a></li>
<li><a href="components_labels.html">Labels and badges</a></li>
<li><a href="components_loaders.html">Loaders and bars</a></li>
<li><a href="components_thumbnails.html">Thumbnails</a></li>
<li><a href="components_page_header.html">Page header</a></li>
<li><a href="components_breadcrumbs.html">Breadcrumbs</a></li>
<li><a href="components_media.html">Media objects</a></li>
<li><a href="components_affix.html">Affix and Scrollspy</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-puzzle2"></i> <span>Content appearance</span></a>
<ul>
<li><a href="appearance_content_panels.html">Content panels</a></li>
<li><a href="appearance_panel_heading.html">Panel heading elements</a></li>
<li><a href="appearance_draggable_panels.html">Draggable panels</a></li>
<li><a href="appearance_text_styling.html">Text styling</a></li>
<li><a href="appearance_typography.html">Typography</a></li>
<li><a href="appearance_helpers.html">Helper classes</a></li>
<li><a href="appearance_syntax_highlighter.html">Syntax highlighter</a></li>
<li><a href="appearance_content_grid.html">Grid system</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-gift"></i> <span>Extra components</span></a>
<ul>
<li><a href="extra_sliders_noui.html">NoUI sliders</a></li>
<li><a href="extra_sliders_ion.html">Ion range sliders</a></li>
<li><a href="extra_session_timeout.html">Session timeout</a></li>
<li><a href="extra_idle_timeout.html">Idle timeout</a></li>
<li><a href="extra_trees.html">Dynamic tree views</a></li>
<li><a href="extra_context_menu.html">Context menu</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-spinner2 spinner"></i> <span>Animations</span></a>
<ul>
<li><a href="animations_css3.html">CSS3 animations</a></li>
<li>
<a href="#">Velocity animations</a>
<ul>
<li><a href="animations_velocity_basic.html">Basic usage</a></li>
<li><a href="animations_velocity_ui.html">UI pack effects</a></li>
<li><a href="animations_velocity_examples.html">Advanced examples</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#"><i class="icon-thumbs-up2"></i> <span>Icons</span></a>
<ul>
<li><a href="icons_glyphicons.html">Glyphicons</a></li>
<li><a href="icons_icomoon.html">Icomoon</a></li>
<li><a href="icons_fontawesome.html">Font awesome</a></li>
</ul>
</li>
<!-- /appearance -->
<!-- Layout -->
<li class="navigation-header"><span>Layout</span> <i class="icon-menu" title="Layout options"></i></li>
<li>
<a href="#"><i class="icon-indent-decrease2"></i> <span>Sidebars</span></a>
<ul>
<li><a href="sidebar_default_collapse.html">Default collapsible</a></li>
<li><a href="sidebar_default_hide.html">Default hideable</a></li>
<li><a href="sidebar_mini_collapse.html">Mini collapsible</a></li>
<li><a href="sidebar_mini_hide.html">Mini hideable</a></li>
<li>
<a href="#">Dual sidebar</a>
<ul>
<li><a href="sidebar_dual.html">Dual sidebar</a></li>
<li><a href="sidebar_dual_double_collapse.html">Dual double collapse</a></li>
<li><a href="sidebar_dual_double_hide.html">Dual double hide</a></li>
<li><a href="sidebar_dual_swap.html">Swap sidebars</a></li>
</ul>
</li>
<li>
<a href="#">Double sidebar</a>
<ul>
<li><a href="sidebar_double_collapse.html">Collapse main sidebar</a></li>
<li><a href="sidebar_double_hide.html">Hide main sidebar</a></li>
<li><a href="sidebar_double_fix_default.html">Fix default width</a></li>
<li><a href="sidebar_double_fix_mini.html">Fix mini width</a></li>
<li><a href="sidebar_double_visible.html">Opposite sidebar visible</a></li>
</ul>
</li>
<li>
<a href="#">Detached sidebar</a>
<ul>
<li><a href="sidebar_detached_left.html">Left position</a></li>
<li><a href="sidebar_detached_right.html">Right position</a></li>
<li><a href="sidebar_detached_sticky_custom.html">Sticky (custom scroll)</a></li>
<li><a href="sidebar_detached_sticky_native.html">Sticky (native scroll)</a></li>
<li><a href="sidebar_detached_separate.html">Separate categories</a></li>
</ul>
</li>
<li><a href="sidebar_hidden.html">Hidden sidebar</a></li>
<li><a href="sidebar_light.html">Light sidebar</a></li>
<li><a href="sidebar_components.html">Sidebar components</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-sort"></i> <span>Vertical navigation</span></a>
<ul>
<li><a href="navigation_vertical_collapsible.html">Collapsible menu</a></li>
<li><a href="navigation_vertical_accordion.html">Accordion menu</a></li>
<li><a href="navigation_vertical_sizing.html">Navigation sizing</a></li>
<li><a href="navigation_vertical_bordered.html">Bordered navigation</a></li>
<li><a href="navigation_vertical_right_icons.html">Right icons</a></li>
<li><a href="navigation_vertical_labels_badges.html">Labels and badges</a></li>
<li><a href="navigation_vertical_disabled.html">Disabled navigation links</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-transmission"></i> <span>Horizontal navigation</span></a>
<ul>
<li><a href="navigation_horizontal_click.html">Submenu on click</a></li>
<li><a href="navigation_horizontal_hover.html">Submenu on hover</a></li>
<li><a href="navigation_horizontal_elements.html">With custom elements</a></li>
<li><a href="navigation_horizontal_tabs.html">Tabbed navigation</a></li>
<li><a href="navigation_horizontal_disabled.html">Disabled navigation links</a></li>
<li><a href="navigation_horizontal_mega.html">Horizontal mega menu</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-menu3"></i> <span>Navbars</span></a>
<ul>
<li><a href="navbar_single.html">Single navbar</a></li>
<li>
<a href="#">Multiple navbars</a>
<ul>
<li><a href="navbar_multiple_navbar_navbar.html">Navbar + navbar</a></li>
<li><a href="navbar_multiple_navbar_header.html">Navbar + header</a></li>
<li><a href="navbar_multiple_header_navbar.html">Header + navbar</a></li>
<li><a href="navbar_multiple_top_bottom.html">Top + bottom</a></li>
</ul>
</li>
<li><a href="navbar_colors.html">Color options</a></li>
<li><a href="navbar_sizes.html">Sizing options</a></li>
<li><a href="navbar_hideable.html">Hide on scroll</a></li>
<li><a href="navbar_components.html">Navbar components</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-tree5"></i> <span>Menu levels</span></a>
<ul>
<li><a href="#"><i class="icon-IE"></i> Second level</a></li>
<li>
<a href="#"><i class="icon-firefox"></i> Second level with child</a>
<ul>
<li><a href="#"><i class="icon-android"></i> Third level</a></li>
<li>
<a href="#"><i class="icon-apple2"></i> Third level with child</a>
<ul>
<li><a href="#"><i class="icon-html5"></i> Fourth level</a></li>
<li><a href="#"><i class="icon-css3"></i> Fourth level</a></li>
</ul>
</li>
<li><a href="#"><i class="icon-windows"></i> Third level</a></li>
</ul>
</li>
<li><a href="#"><i class="icon-chrome"></i> Second level</a></li>
</ul>
</li>
<!-- /layout -->
<!-- Data visualization -->
<li class="navigation-header"><span>Data visualization</span> <i class="icon-menu" title="Data visualization"></i></li>
<li>
<a href="#"><i class="icon-graph"></i> <span>Echarts library</span></a>
<ul>
<li><a href="echarts_lines_areas.html">Lines and areas</a></li>
<li><a href="echarts_columns_waterfalls.html">Columns and waterfalls</a></li>
<li><a href="echarts_bars_tornados.html">Bars and tornados</a></li>
<li><a href="echarts_scatter.html">Scatter charts</a></li>
<li><a href="echarts_pies_donuts.html">Pies and donuts</a></li>
<li><a href="echarts_funnels_chords.html">Funnels and chords</a></li>
<li><a href="echarts_candlesticks_others.html">Candlesticks and others</a></li>
<li><a href="echarts_combinations.html">Chart combinations</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-statistics"></i> <span>D3 library</span></a>
<ul>
<li><a href="d3_lines_basic.html">Simple lines</a></li>
<li><a href="d3_lines_advanced.html">Advanced lines</a></li>
<li><a href="d3_bars_basic.html">Simple bars</a></li>
<li><a href="d3_bars_advanced.html">Advanced bars</a></li>
<li><a href="d3_pies.html">Pie charts</a></li>
<li><a href="d3_circle_diagrams.html">Circle diagrams</a></li>
<li><a href="d3_tree.html">Tree layout</a></li>
<li><a href="d3_other.html">Other charts</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-stats-dots"></i> <span>Dimple library</span></a>
<ul>
<li>
<a href="#">Line charts</a>
<ul>
<li><a href="dimple_lines_horizontal.html">Horizontal orientation</a></li>
<li><a href="dimple_lines_vertical.html">Vertical orientation</a></li>
</ul>
</li>
<li>
<a href="#">Bar charts</a>
<ul>
<li><a href="dimple_bars_horizontal.html">Horizontal orientation</a></li>
<li><a href="dimple_bars_vertical.html">Vertical orientation</a></li>
</ul>
</li>
<li>
<a href="#">Area charts</a>
<ul>
<li class="active"><a href="dimple_area_horizontal.html">Horizontal orientation</a></li>
<li><a href="dimple_area_vertical.html">Vertical orientation</a></li>
</ul>
</li>
<li>
<a href="#">Step charts</a>
<ul>
<li><a href="dimple_step_horizontal.html">Horizontal orientation</a></li>
<li><a href="dimple_step_vertical.html">Vertical orientation</a></li>
</ul>
</li>
<li><a href="dimple_pies.html">Pie charts</a></li>
<li><a href="dimple_rings.html">Ring charts</a></li>
<li><a href="dimple_scatter.html">Scatter charts</a></li>
<li><a href="dimple_bubble.html">Bubble charts</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-stats-bars"></i> <span>C3 library</span></a>
<ul>
<li><a href="c3_lines_areas.html">Lines and areas</a></li>
<li><a href="c3_bars_pies.html">Bars and pies</a></li>
<li><a href="c3_advanced.html">Advanced examples</a></li>
<li><a href="c3_axis.html">Chart axis</a></li>
<li><a href="c3_grid.html">Grid options</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-google"></i> <span>Google visualization</span></a>
<ul>
<li><a href="google_lines.html">Line charts</a></li>
<li><a href="google_bars.html">Bar charts</a></li>
<li><a href="google_pies.html">Pie charts</a></li>
<li><a href="google_scatter_bubble.html">Bubble & scatter charts</a></li>
<li><a href="google_other.html">Other charts</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-map5"></i> <span>Maps integration</span></a>
<ul>
<li>
<a href="#">Google maps</a>
<ul>
<li><a href="maps_google_basic.html">Basics</a></li>
<li><a href="maps_google_controls.html">Controls</a></li>
<li><a href="maps_google_markers.html">Markers</a></li>
<li><a href="maps_google_drawings.html">Map drawings</a></li>
<li><a href="maps_google_layers.html">Layers</a></li>
</ul>
</li>
<li><a href="maps_vector.html">Vector maps</a></li>
</ul>
</li>
<!-- /data visualization -->
<!-- Extensions -->
<li class="navigation-header"><span>Extensions</span> <i class="icon-menu" title="Extensions"></i></li>
<li>
<a href="#"><i class="icon-puzzle4"></i> <span>Extensions</span></a>
<ul>
<li><a href="extension_image_cropper.html">Image cropper</a></li>
<li><a href="extension_blockui.html">Block UI</a></li>
<li><a href="extension_dnd.html">Drag and drop</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-popout"></i> <span>JQuery UI</span></a>
<ul>
<li><a href="jqueryui_interactions.html">Interactions</a></li>
<li><a href="jqueryui_forms.html">Forms</a></li>
<li><a href="jqueryui_components.html">Components</a></li>
<li><a href="jqueryui_sliders.html">Sliders</a></li>
<li><a href="jqueryui_navigation.html">Navigation</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-upload"></i> <span>File uploaders</span></a>
<ul>
<li><a href="uploader_plupload.html">Plupload</a></li>
<li><a href="uploader_bootstrap.html">Bootstrap file uploader</a></li>
<li><a href="uploader_dropzone.html">Dropzone</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-calendar3"></i> <span>Event calendars</span></a>
<ul>
<li><a href="extension_fullcalendar_views.html">Basic views</a></li>
<li><a href="extension_fullcalendar_styling.html">Event styling</a></li>
<li><a href="extension_fullcalendar_formats.html">Language and time</a></li>
<li><a href="extension_fullcalendar_advanced.html">Advanced usage</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-sphere"></i> <span>Internationalization</span></a>
<ul>
<li><a href="internationalization_switch_direct.html">Direct translation</a></li>
<li><a href="internationalization_switch_query.html">Querystring parameter</a></li>
<li><a href="internationalization_on_init.html">Set language on init</a></li>
<li><a href="internationalization_after_init.html">Set language after init</a></li>
<li><a href="internationalization_fallback.html">Language fallback</a></li>
<li><a href="internationalization_callbacks.html">Callbacks</a></li>
</ul>
</li>
<!-- /extensions -->
<!-- Tables -->
<li class="navigation-header"><span>Tables</span> <i class="icon-menu" title="Tables"></i></li>
<li>
<a href="#"><i class="icon-table2"></i> <span>Basic tables</span></a>
<ul>
<li><a href="table_basic.html">Basic examples</a></li>
<li><a href="table_sizing.html">Table sizing</a></li>
<li><a href="table_borders.html">Table borders</a></li>
<li><a href="table_styling.html">Table styling</a></li>
<li><a href="table_elements.html">Table elements</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-grid7"></i> <span>Data tables</span></a>
<ul>
<li><a href="datatable_basic.html">Basic initialization</a></li>
<li><a href="datatable_styling.html">Basic styling</a></li>
<li><a href="datatable_advanced.html">Advanced examples</a></li>
<li><a href="datatable_sorting.html">Sorting options</a></li>
<li><a href="datatable_api.html">Using API</a></li>
<li><a href="datatable_data_sources.html">Data sources</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-alignment-unalign"></i> <span>Data tables extensions</span></a>
<ul>
<li><a href="datatable_extension_reorder.html">Columns reorder</a></li>
<li><a href="datatable_extension_row_reorder.html">Row reorder</a></li>
<li><a href="datatable_extension_fixed_columns.html">Fixed columns</a></li>
<li><a href="datatable_extension_fixed_header.html">Fixed header</a></li>
<li><a href="datatable_extension_autofill.html">Auto fill</a></li>
<li><a href="datatable_extension_key_table.html">Key table</a></li>
<li><a href="datatable_extension_scroller.html">Scroller</a></li>
<li><a href="datatable_extension_select.html">Select</a></li>
<li>
<a href="#">Buttons</a>
<ul>
<li><a href="datatable_extension_buttons_init.html">Initialization</a></li>
<li><a href="datatable_extension_buttons_flash.html">Flash buttons</a></li>
<li><a href="datatable_extension_buttons_print.html">Print buttons</a></li>
<li><a href="datatable_extension_buttons_html5.html">HTML5 buttons</a></li>
</ul>
</li>
<li><a href="datatable_extension_colvis.html">Columns visibility</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-file-spreadsheet"></i> <span>Handsontable</span></a>
<ul>
<li><a href="handsontable_basic.html">Basic configuration</a></li>
<li><a href="handsontable_advanced.html">Advanced setup</a></li>
<li><a href="handsontable_cols.html">Column features</a></li>
<li><a href="handsontable_cells.html">Cell features</a></li>
<li><a href="handsontable_types.html">Basic cell types</a></li>
<li><a href="handsontable_custom_checks.html">Custom & checkboxes</a></li>
<li><a href="handsontable_ac_password.html">Autocomplete & password</a></li>
<li><a href="handsontable_search.html">Search</a></li>
<li><a href="handsontable_context.html">Context menu</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-versions"></i> <span>Responsive options</span></a>
<ul>
<li><a href="table_responsive.html">Responsive basic tables</a></li>
<li><a href="datatable_responsive.html">Responsive data tables</a></li>
</ul>
</li>
<!-- /tables -->
<!-- Page kits -->
<li class="navigation-header"><span>Page kits</span> <i class="icon-menu" title="Page kits"></i></li>
<li>
<a href="#"><i class="icon-task"></i> <span>Task manager</span></a>
<ul>
<li><a href="task_manager_grid.html">Task grid</a></li>
<li><a href="task_manager_list.html">Task list</a></li>
<li><a href="task_manager_detailed.html">Task detailed</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-cash3"></i> <span>Invoicing</span></a>
<ul>
<li><a href="invoice_template.html">Invoice template</a></li>
<li><a href="invoice_grid.html">Invoice grid</a></li>
<li><a href="invoice_archive.html">Invoice archive</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-people"></i> <span>User pages</span></a>
<ul>
<li><a href="user_pages_cards.html">User cards</a></li>
<li><a href="user_pages_list.html">User list</a></li>
<li><a href="user_pages_profile.html">Simple profile</a></li>
<li><a href="user_pages_profile_cover.html">Profile with cover</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-user-plus"></i> <span>Login & registration</span></a>
<ul>
<li><a href="login_simple.html">Simple login</a></li>
<li><a href="login_advanced.html">More login info</a></li>
<li><a href="login_registration.html">Simple registration</a></li>
<li><a href="login_registration_advanced.html">More registration info</a></li>
<li><a href="login_unlock.html">Unlock user</a></li>
<li><a href="login_password_recover.html">Reset password</a></li>
<li><a href="login_hide_navbar.html">Hide navbar</a></li>
<li><a href="login_transparent.html">Transparent box</a></li>
<li><a href="login_background.html">Background option</a></li>
<li><a href="login_validation.html">With validation</a></li>
<li><a href="login_tabbed.html">Tabbed form</a></li>
<li><a href="login_modals.html">Inside modals</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-magazine"></i> <span>Timelines</span></a>
<ul>
<li><a href="timelines_left.html">Left timeline</a></li>
<li><a href="timelines_right.html">Right timeline</a></li>
<li><a href="timelines_center.html">Centered timeline</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-lifebuoy"></i> <span>Support</span></a>
<ul>
<li><a href="support_conversation_layouts.html">Conversation layouts</a></li>
<li><a href="support_conversation_options.html">Conversation options</a></li>
<li><a href="support_knowledgebase.html">Knowledgebase</a></li>
<li><a href="support_faq.html">FAQ page</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-search4"></i> <span>Search</span></a>
<ul>
<li><a href="search_basic.html">Basic search results</a></li>
<li><a href="search_users.html">User search results</a></li>
<li><a href="search_images.html">Image search results</a></li>
<li><a href="search_videos.html">Video search results</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-images2"></i> <span>Gallery</span></a>
<ul>
<li><a href="gallery_grid.html">Media grid</a></li>
<li><a href="gallery_titles.html">Media with titles</a></li>
<li><a href="gallery_description.html">Media with description</a></li>
<li><a href="gallery_library.html">Media library</a></li>
</ul>
</li>
<li>
<a href="#"><i class="icon-warning"></i> <span>Error pages</span></a>
<ul>
<li><a href="error_403.html">Error 403</a></li>
<li><a href="error_404.html">Error 404</a></li>
<li><a href="error_405.html">Error 405</a></li>
<li><a href="error_500.html">Error 500</a></li>
<li><a href="error_503.html">Error 503</a></li>
<li><a href="error_offline.html">Offline page</a></li>
</ul>
</li>
<!-- /page kits -->
</ul>
</div>
</div>
<!-- /main navigation -->
</div>
</div>
<!-- /main sidebar -->
<!-- Main content -->
<div class="content-wrapper">
<!-- Page header -->
<div class="page-header">
<div class="page-header-content">
<div class="page-title">
<h4><i class="icon-arrow-left52 position-left"></i> <span class="text-semibold">Dimple</span> - Horizontal Areas</h4>
</div>
<div class="heading-elements">
<div class="heading-btn-group">
<a href="#" class="btn btn-link btn-float has-text"><i class="icon-bars-alt text-primary"></i><span>Statistics</span></a>
<a href="#" class="btn btn-link btn-float has-text"><i class="icon-calculator text-primary"></i> <span>Invoices</span></a>
<a href="#" class="btn btn-link btn-float has-text"><i class="icon-calendar5 text-primary"></i> <span>Schedule</span></a>
</div>
</div>
</div>
<div class="breadcrumb-line">
<ul class="breadcrumb">
<li><a href="index.html"><i class="icon-home2 position-left"></i> Home</a></li>
<li><a href="dimple_area_horizontal.html">Dimple</a></li>
<li class="active">Horizontal areas</li>
</ul>
<ul class="breadcrumb-elements">
<li><a href="#"><i class="icon-comment-discussion position-left"></i> Support</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-gear position-left"></i>
Settings
<span class="caret"></span>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#"><i class="icon-user-lock"></i> Account security</a></li>
<li><a href="#"><i class="icon-statistics"></i> Analytics</a></li>
<li><a href="#"><i class="icon-accessibility"></i> Accessibility</a></li>
<li class="divider"></li>
<li><a href="#"><i class="icon-gear"></i> All settings</a></li>
</ul>
</li>
</ul>
</div>
</div>
<!-- /page header -->
<!-- Content area -->
<div class="content">
<!-- Basic area chart -->
<div class="panel panel-flat">
<div class="panel-heading">
<h6 class="panel-title text-semibold">Standard area chart</h6>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="chart-container">
<div class="chart" id="dimple-area-horizontal"></div>
</div>
</div>
</div>
<!-- /basic area chart -->
<!-- Stacked area chart -->
<div class="panel panel-flat">
<div class="panel-heading">
<h6 class="panel-title text-semibold">Stacked area chart</h6>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="chart-container">
<div class="chart" id="dimple-area-horizontal-stacked"></div>
</div>
</div>
</div>
<!-- /stacked area chart -->
<!-- Normalized stacked area chart -->
<div class="panel panel-flat">
<div class="panel-heading">
<h6 class="panel-title text-semibold">Normalized stacked area chart</h6>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="chart-container">
<div class="chart" id="dimple-area-horizontal-stacked-normalized"></div>
</div>
</div>
</div>
<!-- /normalized stacked area chart -->
<!-- Grouped area chart -->
<div class="panel panel-flat">
<div class="panel-heading">
<h6 class="panel-title text-semibold">Grouped area chart</h6>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="chart-container">
<div class="chart" id="dimple-area-horizontal-grouped"></div>
</div>
</div>
</div>
<!-- /grouped area chart -->
<!-- Grouped stacked area chart -->
<div class="panel panel-flat">
<div class="panel-heading">
<h6 class="panel-title text-semibold">Grouped stacked area chart</h6>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="chart-container">
<div class="chart" id="dimple-area-horizontal-stacked-grouped"></div>
</div>
</div>
</div>
<!-- /grouped stacked area chart -->
<!-- Footer -->
<div class="footer text-muted">
© 2015. <a href="#">Limitless Web App Kit</a> by <a href="http://themeforest.net/user/Kopyov" target="_blank">Eugene Kopyov</a>
</div>
<!-- /footer -->
</div>
<!-- /content area -->
</div>
<!-- /main content -->
</div>
<!-- /page content -->
</div>
<!-- /page container -->
</body>
</html>
| luizaranda/sistema | public/sistema/limitless/dimple_area_horizontal.html | HTML | bsd-3-clause | 52,076 |
#include "stdafx.h"
#include "ThreadManager.h"
#include "Ini.h"
#include "SceneThread.h"
#include "SceneManager.h"
#include "Config.h"
ThreadManager* g_pThreadManager = NULL ;
ThreadManager::ThreadManager()
{
__ENTER_FUNCTION
m_pThreadPool = new ThreadPool ;
Assert( m_pThreadPool ) ;
m_pServerThread = new ServerThread ;
Assert( m_pServerThread ) ;
m_nThreads = 0 ;
__LEAVE_FUNCTION
}
ThreadManager::~ThreadManager()
{
__ENTER_FUNCTION
SAFE_DELETE( m_pThreadPool) ;
SAFE_DELETE( m_pServerThread ) ;
__LEAVE_FUNCTION
}
BOOL ThreadManager::Init( UINT MaxSceneCount )
{
__ENTER_FUNCTION
BOOL ret = FALSE ;
//根据配置文件读取需要使用的场景,为每个场景分配一个线程;
//读取场景数量
UINT count = MaxSceneCount ;
Assert( MAX_SCENE >= count ) ;
UINT uMaxThreadCount = 0 ;
UINT i ;
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
if ( ( ID_t )uMaxThreadCount < g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex )
{
uMaxThreadCount = g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ;
}
}
SceneThread* pSceneThread = NULL ;
for ( i = 0; i <= uMaxThreadCount; i++ )
{
pSceneThread = new SceneThread ;
Assert( pSceneThread ) ;
ret = m_pThreadPool->AddThread( i, pSceneThread ) ;
Assert( ret ) ;
m_nThreads ++ ;
}
/** //my debug output
for ( i = 0 ; i <= uMaxThreadCount ; i++ )
{
Thread** m_pThread = m_pThreadPool->GetThread() ;
SceneThread* pSceneThread1 = (SceneThread*)( m_pThread[ i ] ) ;
LERR( "FILE: %s, LINE: %d, pSceneThread1: %d, index: %d", __FILE__, __LINE__, pSceneThread1, i ) ;
}
**/
MySleep( 3600 ) ;
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
SceneThread* pSceneThread = ( SceneThread* )( m_pThreadPool->GetThreadByIndex( g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ) ) ;
if ( NULL == pSceneThread )
{
AssertEx( FALSE, "没有创建所需的线程" ) ;
}
else
{
Scene* pScene = g_pSceneManager->GetScene( SceneID ) ;
pSceneThread->AddScene( pScene ) ;
}
}
if ( m_pServerThread->IsActive() )
{
m_nThreads ++ ;
}
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Start()
{
__ENTER_FUNCTION
BOOL ret ;
m_pServerThread->start() ;
MySleep( 500 ) ;
ret = m_pThreadPool->Start() ;
return ret ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Stop()
{
__ENTER_FUNCTION
if ( m_pServerThread )
{
m_pServerThread->stop() ;
}
return m_pThreadPool->Stop() ;
__LEAVE_FUNCTION
return FALSE ;
}
| viticm/web-pap | server/Server/Main/ThreadManager.cpp | C++ | bsd-3-clause | 4,176 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class ArrayOfExtendedEventPair
{
public ExtendedEventPair[] ExtendedEventPair;
public ExtendedEventPair[] getExtendedEventPair()
{
return this.ExtendedEventPair;
}
public ExtendedEventPair getExtendedEventPair(int i)
{
return this.ExtendedEventPair[i];
}
public void setExtendedEventPair(ExtendedEventPair[] ExtendedEventPair)
{
this.ExtendedEventPair=ExtendedEventPair;
}
} | mikem2005/vijava | src/com/vmware/vim25/ArrayOfExtendedEventPair.java | Java | bsd-3-clause | 2,131 |
## things I need to do
- flesh out a "save" methodology (including remote storage -- e.g. AWS S3)
- allow for PUT requests | henderjon/filemarshal | TODO.md | Markdown | bsd-3-clause | 127 |
//
// Copyright (c) 2014-2016 Brian W. Wolter, All rights reserved.
// Ego - an embedded Go parser / compiler
//
// 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 names of Brian W. Wolter nor the names of the 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.
//
// --
//
// This scanner incorporates routines from the Go package text/scanner:
// http://golang.org/src/pkg/text/scanner/scanner.go
//
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// http://golang.org/LICENSE
//
package ego
import (
"fmt"
"math"
"strings"
"strconv"
"unicode"
"unicode/utf8"
)
/**
* A text span
*/
type span struct {
text string
offset int
length int
}
/**
* Span (unquoted) excerpt
*/
func (s span) excerpt() string {
max := float64(len(s.text))
return s.text[int(math.Max(0, math.Min(max, float64(s.offset)))):int(math.Min(max, float64(s.offset+s.length)))]
}
/**
* Span (quoted) excerpt
*/
func (s span) String() string {
return strconv.Quote(s.excerpt())
}
/**
* Create a new span that encompasses all the provided spans. The underlying text is taken from the first span.
*/
func encompass(a ...span) span {
var t string
min, max := 0, 0
for i, e := range a {
if i == 0 {
min, max = e.offset, e.offset + e.length
t = e.text
}else{
if e.offset < min {
min = e.offset
}
if e.offset + e.length > max {
max = e.offset + e.length
}
}
}
return span{t, min, max - min}
}
/**
* Numeric type
*/
type numericType int
const (
numericInteger numericType = iota
numericFloat
)
/**
* Token type
*/
type tokenType int
/**
* Token types
*/
const (
tokenError tokenType = iota
tokenEOF
tokenVerbatim
tokenMeta
tokenBlock
tokenClose
tokenAtem
tokenString
tokenNumber
tokenIdentifier
tokenIf
tokenElse
tokenFor
tokenBreak
tokenContinue
tokenTrue
tokenFalse
tokenNil
tokenRange
tokenLParen = '('
tokenRParen = ')'
tokenLBracket = '['
tokenRBracket = ']'
tokenDot = '.'
tokenComma = ','
tokenSemi = ';'
tokenColon = ':'
tokenAdd = '+'
tokenSub = '-'
tokenMul = '*'
tokenDiv = '/'
tokenMod = '%'
tokenAssign = '='
tokenLess = '<'
tokenGreater = '>'
tokenBang = '!'
tokenAmp = '&'
tokenPipe = '|'
tokenPrefixAdd = 1 << 16
tokenInc = tokenPrefixAdd | '+'
tokenPrefixSub = 1 << 17
tokenDec = tokenPrefixSub | '-'
tokenPrefixAmp = 1 << 18
tokenLogicalAnd = tokenPrefixAmp | '&'
tokenPrefixPipe = 1 << 19
tokenLogicalOr = tokenPrefixPipe | '|'
tokenSuffixEqual = 1 << 20
tokenEqual = tokenSuffixEqual | '='
tokenAddEqual = tokenSuffixEqual | '+'
tokenSubEqual = tokenSuffixEqual | '-'
tokenMulEqual = tokenSuffixEqual | '*'
tokenDivEqual = tokenSuffixEqual | '/'
tokenLessEqual = tokenSuffixEqual | '<'
tokenGreaterEqual = tokenSuffixEqual | '>'
tokenNotEqual = tokenSuffixEqual | '!'
tokenBitwiseAndEqual = tokenSuffixEqual | '&'
tokenBitwiseOrEqual = tokenSuffixEqual | '|'
tokenAssignSpecial = tokenSuffixEqual | ':'
)
/**
* Token type string
*/
func (t tokenType) String() string {
switch t {
case tokenError:
return "error"
case tokenEOF:
return "EOF"
case tokenVerbatim:
return "verbatim"
case tokenMeta:
return "@"
case tokenBlock:
return "{..."
case tokenClose:
return "...}"
case tokenAtem:
return "#"
case tokenString:
return "string"
case tokenNumber:
return "number"
case tokenIdentifier:
return "ident"
case tokenIf:
return "if"
case tokenElse:
return "else"
case tokenFor:
return "for"
case tokenBreak:
return "break"
case tokenContinue:
return "continue"
case tokenTrue:
return "true"
case tokenFalse:
return "false"
case tokenNil:
return "nil"
case tokenRange:
return "range"
case tokenInc:
return "++"
case tokenDec:
return "--"
case tokenLogicalAnd:
return "&&"
case tokenLogicalOr:
return "||"
case tokenEqual:
return "=="
case tokenAddEqual:
return "+="
case tokenSubEqual:
return "+="
case tokenMulEqual:
return "*="
case tokenDivEqual:
return "/="
case tokenLessEqual:
return "<="
case tokenGreaterEqual:
return ">="
case tokenNotEqual:
return "!="
case tokenAssignSpecial:
return ":="
case tokenBitwiseAndEqual:
return "&="
case tokenBitwiseOrEqual:
return "|="
default:
if t < 128 {
return fmt.Sprintf("'%v'", string(t))
}else{
return fmt.Sprintf("%U", t)
}
}
}
/**
* Token stuff
*/
const (
meta = '@'
eof = -1
)
/**
* A token
*/
type token struct {
span span
which tokenType
value interface{}
}
/**
* Stringer
*/
func (t token) String() string {
switch t.which {
case tokenError:
return fmt.Sprintf("<%v %v %v>", t.which, t.span, t.value)
default:
return fmt.Sprintf("<%v %v>", t.which, t.span)
}
}
/**
* A scanner action
*/
type scannerAction func(*scanner) scannerAction
/**
* A scanner error
*/
type scannerError struct {
message string
span span
cause error
}
/**
* Error
*/
func (s *scannerError) Error() string {
if s.cause != nil {
return fmt.Sprintf("%s: %v\n%v", s.message, s.cause, excerptCallout.FormatExcerpt(s.span))
}else{
return fmt.Sprintf("%s\n%v", s.message, excerptCallout.FormatExcerpt(s.span))
}
}
const (
mtypeExpr = iota
mtypeControl = iota
)
/**
* A scanner
*/
type scanner struct {
text string
index int
width int // current rune width
start int // token start position
depth int // meta depth
tokens chan token
state scannerAction
paren int
mtype int
}
/**
* Create a scanner
*/
func newScanner(text string) *scanner {
t := make(chan token, 64 /* several tokens may be produced in one iteration */)
return &scanner{text, 0, 0, 0, 0, t, startAction, 0, 0}
}
/**
* Scan and produce a token
*/
func (s *scanner) scan() token {
for {
select {
case t := <- s.tokens:
return t
default:
if s.state == nil {
return token{span{s.text, len(s.text), 0}, tokenEOF, nil}
}else{
s.state = s.state(s)
}
}
}
}
/**
* Create an error
*/
func (s *scanner) errorf(where span, cause error, format string, args ...interface{}) *scannerError {
return &scannerError{fmt.Sprintf(format, args...), where, cause}
}
/**
* Emit a token
*/
func (s *scanner) emit(t token) {
s.tokens <- t
s.start = t.span.offset + t.span.length
}
/**
* Emit an error and return a nil action
*/
func (s *scanner) error(err *scannerError) scannerAction {
s.tokens <- token{err.span, tokenError, err}
return nil
}
/**
* Obtain the next rune from input without consuming it
*/
func (s *scanner) peek() rune {
r := s.next()
s.backup()
return r
}
/**
* Consume the next rune from input
*/
func (s *scanner) next() rune {
if s.index >= len(s.text) {
s.width = 0
return eof
}
r, w := utf8.DecodeRuneInString(s.text[s.index:])
s.index += w
s.width = w
return r
}
/**
* Match ahead
*/
func (s *scanner) match(text string) bool {
return s.matchAt(s.index, text)
}
/**
* Match ahead
*/
func (s *scanner) matchAt(index int, text string) bool {
i := index
if i < 0 {
return false
}
for n := 0; n < len(text); {
if i >= len(s.text) {
return false
}
r, w := utf8.DecodeRuneInString(s.text[i:])
i += w
c, z := utf8.DecodeRuneInString(text[n:])
n += z
if r != c {
return false
}
}
return true
}
/**
* Find the next occurance of any character in the specified string
*/
func (s *scanner) findFrom(index int, any string, invert bool) int {
i := index
if !invert {
return strings.IndexAny(s.text[i:], any)
}else{
for {
if i >= len(s.text) {
return -1
}
r, w := utf8.DecodeRuneInString(s.text[i:])
if !strings.ContainsRune(any, r) {
return i
}else{
i += w
}
}
}
}
/**
* Shuffle the token start to the current index
*/
func (s *scanner) ignore() {
s.start = s.index
}
/**
* Move directly to an index
*/
func (s *scanner) move(index int) {
s.start, s.index = index, index
}
/**
* Unconsume the previous rune from input (this can be called only once
* per invocation of next())
*/
func (s *scanner) backup() {
s.index -= s.width
}
/**
* Skip past a rune that was previously peeked
*/
func (s *scanner) skip() {
s.index += s.width
}
/**
* Skip past a rune that was previously peeked and ignore it
*/
func (s *scanner) skipAndIgnore() {
s.skip()
s.ignore()
}
/**
* Start action
*/
func startAction(s *scanner) scannerAction {
for {
if s.index < len(s.text) {
r := s.text[s.index]
switch {
case r == meta:
if s.index > s.start {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenVerbatim, s.text[s.start:s.index]})
}
return preludeAction
case r == '}' && s.depth > 0:
if s.index > s.start {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenVerbatim, s.text[s.start:s.index]})
}
return closeAction
}
}
if r := s.next(); r == eof {
break
}else if r == '\\' {
var t span
switch r := s.next(); {
case r == eof:
break
case r == '\\':
t = span{s.text, s.start, s.index - s.start - 1} // verbatim up to first '\', ignore second (literal '\')
s.emit(token{t, tokenVerbatim, t.excerpt()})
s.ignore()
case r == '@' || r == '{' || r == '}':
if s.index - 2 > s.start {
t = span{s.text, s.start, s.index - s.start - 2} // verbatim up to '\', exclusive (we know the widths of runes '\' and r)
s.emit(token{t, tokenVerbatim, t.excerpt()})
}
t = span{s.text, s.index - 1, 1} // emit r, continue (literal r)
s.emit(token{t, tokenVerbatim, t.excerpt()})
s.ignore()
}
}
}
// emit the last verbatim block, if we have one
if s.index > s.start {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenVerbatim, s.text[s.start:s.index]})
}
// emit end of input
s.emit(token{span{s.text, len(s.text), 0}, tokenEOF, nil})
// we're done
return nil
}
/**
* Prelude action. This introduces a meta expression or control structure.
*/
func preludeAction(s *scanner) scannerAction {
s.emit(token{span{s.text, s.index, 1}, tokenMeta, "@"})
s.next() // skip the '@' delimiter
// if the meta begins with an open parenthesis it is an expression, otherwise
// it is a control structure (if, for, etc)
if s.next() == '(' {
s.mtype = mtypeExpr
}else{
s.mtype = mtypeControl
}
s.backup()
return metaAction
}
/**
* Meta action.
*/
func metaAction(s *scanner) scannerAction {
for {
switch r := s.next(); {
case r == eof:
return s.error(s.errorf(span{s.text, s.index, 1}, nil, "Unexpected end-of-input"))
case unicode.IsSpace(r):
s.ignore()
case r == '{': // open verbatim
s.backup()
return blockAction
case r == '"':
// consume the open '"'
return stringAction
case r >= '0' && r <= '9':
s.backup()
return numberAction
case r == '_' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z'):
s.backup()
return identifierAction
case r == '(':
s.paren++
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
return metaAction
case r == ')':
s.paren--
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
if s.paren == 0 && s.mtype == mtypeExpr {
return startAction
}else{
return metaAction
}
case r == '[' || r == ']' || r == '.' || r == ',' || r == ';':
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
return metaAction
case r == '&':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else if n == '&' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenPrefixAmp | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
case r == '|':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else if n == '|' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenPrefixPipe | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
case r == '+':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else if n == '+' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenPrefixAdd | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
case r == '-':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else if n == '-' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenPrefixSub | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
case r == ':':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
case r == '=' || r == '!' || r == '<' || r == '>' || r == ':' || r == '*' || r == '/':
if n := s.next(); n == '=' {
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(tokenSuffixEqual | r), string(r)})
}else{
s.backup()
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenType(r), string(r)})
}
return metaAction
default:
return s.error(s.errorf(span{s.text, s.index, 1}, nil, "Syntax error in meta"))
}
}
return startAction
}
/**
* Block { ... }
*/
func blockAction(s *scanner) scannerAction {
s.depth++ // increment the meta depth
s.emit(token{span{s.text, s.index, 1}, tokenBlock, nil})
s.next() // skip the '{' delimiter
return startAction
}
/**
* Close a block. This closes a meta expression or control structure. As a special case, the
* dangling 'else' following what is otherwise a closed structure begins a new block.
*/
func closeAction(s *scanner) scannerAction {
s.emit(token{span{s.text, s.index, 1}, tokenClose, nil})
s.next() // skip the '}' delimiter
s.depth-- // decrement the meta depth
f := s.findFrom(s.index, " \n\r\t\v", true)
if s.matchAt(f, "else") {
s.move(f)
return identifierAction
}else if s.matchAt(f, "\\else") {
// move past the \ escape, which should be ignored in this specific case
s.move(f+1)
}
return startAction
}
/**
* Quoted string
*/
func stringAction(s *scanner) scannerAction {
if v, err := s.scanString('"', '\\'); err != nil {
s.error(s.errorf(span{s.text, s.index, 1}, err, "Invalid string"))
}else{
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenString, v})
}
return metaAction
}
/**
* Number string
*/
func numberAction(s *scanner) scannerAction {
if v, _, err := s.scanNumber(); err != nil {
s.error(s.errorf(span{s.text, s.index, 1}, err, "Invalid number"))
}else{
s.emit(token{span{s.text, s.start, s.index - s.start}, tokenNumber, v})
}
return metaAction
}
/**
* Identifier
*/
func identifierAction(s *scanner) scannerAction {
v, err := s.scanIdentifier()
if err != nil {
s.error(s.errorf(span{s.text, s.index, 1}, err, "Invalid identifier"))
}
t := span{s.text, s.start, s.index - s.start}
switch v {
case "if":
s.emit(token{t, tokenIf, v})
case "else":
s.emit(token{t, tokenElse, v})
case "for":
s.emit(token{t, tokenFor, v})
case "break":
s.emit(token{t, tokenBreak, v})
case "continue":
s.emit(token{t, tokenContinue, v})
case "true":
s.emit(token{t, tokenTrue, v})
case "false":
s.emit(token{t, tokenFalse, v})
case "nil":
s.emit(token{t, tokenNil, nil})
case "range":
s.emit(token{t, tokenRange, v})
default:
s.emit(token{t, tokenIdentifier, v})
}
return metaAction
}
/***
*** SCANNING PRIMITIVES
***/
/**
* Scan a delimited token with escape sequences. The opening delimiter is
* expected to have already been consumed.
*/
func (s *scanner) scanString(quote, escape rune) (string, error) {
var unquoted string
for {
switch r := s.next(); {
case r == eof:
return "", s.errorf(span{s.text, s.start, s.index - s.start}, nil, "Unexpected end-of-input")
case r == escape:
if e, err := s.scanEscape(quote, escape); err != nil {
return "", s.errorf(span{s.text, s.start, s.index - s.start}, err, "Invalid escape sequence")
}else{
unquoted += string(e)
}
case r == quote:
return unquoted, nil
default:
unquoted += string(r)
}
}
return "", s.errorf(span{s.text, s.start, s.index - s.start}, nil, "Unexpected end-of-input")
}
/**
* Scan an identifier
*/
func (s *scanner) scanIdentifier() (string, error) {
start := s.index
for r := s.next(); r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r); {
r = s.next()
}
s.backup() // unget the last character
return s.text[start:s.index], nil
}
/**
* Scan a digit value
*/
func digitValue(ch rune) int {
switch {
case '0' <= ch && ch <= '9':
return int(ch - '0')
case 'a' <= ch && ch <= 'f':
return int(ch - 'a' + 10)
case 'A' <= ch && ch <= 'F':
return int(ch - 'A' + 10)
}
return 16 // too big
}
/**
* Decimla digit?
*/
func isDecimal(ch rune) bool {
return '0' <= ch && ch <= '9'
}
/**
* Scan digits
*/
func (s *scanner) scanDigits(base, n int) (string, error) {
start := s.index
for r := s.next(); n > 0 && digitValue(r) < base; {
r = s.next(); n--
}
if n > 0 {
return "", s.errorf(span{s.text, start, s.index - start}, nil, "Not enough digits")
}else{
return s.text[start:s.index-1], nil
}
}
/**
* Scan digits
*/
func (s *scanner) scanDecimal(base, n int) (int64, error) {
if d, err := s.scanDigits(base, n); err != nil {
return 0, err
}else{
return strconv.ParseInt(d, base, 64)
}
}
/**
* Scan digits as a rune
*/
func (s *scanner) scanRune(base, n int) (rune, error) {
if d, err := s.scanDecimal(base, n); err != nil {
return 0, err
}else{
return rune(d), nil
}
}
/**
* Scan an escape
*/
func (s *scanner) scanEscape(quote, esc rune) (rune, error) {
start := s.index
r := s.next()
switch r {
case 'a':
return '\a', nil
case 'b':
return '\b', nil
case 'f':
return '\f', nil
case 'n':
return '\n', nil
case 'r':
return '\r', nil
case 't':
return '\t', nil
case 'v':
return '\v', nil
case esc, quote:
return r, nil
case '0', '1', '2', '3', '4', '5', '6', '7':
return s.scanRune(8, 3)
case 'x':
return s.scanRune(16, 2)
case 'u':
return s.scanRune(16, 4)
case 'U':
return s.scanRune(16, 8)
default:
return 0, s.errorf(span{s.text, start, s.index - start}, nil, "Invalid escape sequence")
}
}
/**
* Scan a number mantissa
*/
func (s *scanner) scanMantissa(ch rune) rune {
for isDecimal(ch) {
ch = s.next()
}
return ch
}
/**
* Scan a number fraction
*/
func (s *scanner) scanFraction(ch rune) rune {
if ch == '.' {
ch = s.scanMantissa(s.next())
}
return ch
}
/**
* Scan a number exponent
*/
func (s *scanner) scanExponent(ch rune) rune {
if ch == 'e' || ch == 'E' {
ch = s.next()
if ch == '-' || ch == '+' {
ch = s.next()
}
ch = s.scanMantissa(ch)
}
return ch
}
/**
* Scan a number
*/
func (s *scanner) scanNumber() (float64, numericType, error) {
start := s.index
ch := s.next()
if ch == '0' {
// int or float
ch = s.next()
if ch == 'x' || ch == 'X' {
// hexadecimal int
ch = s.next()
hasMantissa := false
for digitValue(ch) < 16 {
ch = s.next()
hasMantissa = true
}
s.backup() // unscan the stop rune
if !hasMantissa {
return 0, 0, s.errorf(span{s.text, start, s.index - start}, nil, "Illegal hexadecimal number")
}
if v, err := strconv.ParseInt(s.text[start+2:s.index], 16, 64); err != nil {
return 0, 0, s.errorf(span{s.text, start, s.index - start}, err, "Could not parse number")
}else{
return float64(v), numericInteger, nil
}
} else {
// octal int or float
has8or9 := false
for isDecimal(ch) {
if ch > '7' { has8or9 = true }
ch = s.next()
}
s.backup() // unscan the stop rune
// octal int
if has8or9 {
s.errorf(span{s.text, start, s.index - start}, nil, "Illegal octal number")
}
t := s.text[start+1:s.index]
if t == "" { // no more text, this is a zero
return 0, numericInteger, nil
}else if v, err := strconv.ParseInt(t, 8, 64); err != nil {
return 0, 0, s.errorf(span{s.text, start, s.index - start}, err, "Could not parse number")
}else{
return float64(v), numericInteger, nil
}
}
}
// decimal int or float
ch = s.scanMantissa(ch)
// float
if ch == '.' || ch == 'e' || ch == 'E' {
// float
ch = s.scanFraction(ch)
ch = s.scanExponent(ch)
// unscan the non-numeric rune
s.backup()
if v, err := strconv.ParseFloat(s.text[start:s.index], 64); err != nil {
return 0, 0, s.errorf(span{s.text, start, s.index - start}, err, "Could not parse number")
}else{
return v, numericInteger, nil
}
}else{
// unscan the non-numeric rune
s.backup()
}
// integer
if v, err := strconv.ParseInt(s.text[start:s.index], 10, 64); err != nil {
return 0, 0, s.errorf(span{s.text, start, s.index - start}, err, "Could not parse number")
}else{
return float64(v), numericInteger, nil
}
}
/*
func (s *scanner) scanChar() {
if s.scanString('\'') != 1 {
s.error("illegal char literal")
}
}
func (s *scanner) scanComment(ch rune) rune {
// ch == '/' || ch == '*'
if ch == '/' {
// line comment
ch = s.next() // read character after "//"
for ch != '\n' && ch >= 0 {
ch = s.next()
}
return ch
}
// general comment
ch = s.next() // read character after "/*"
for {
if ch < 0 {
s.error("comment not terminated")
break
}
ch0 := ch
ch = s.next()
if ch0 == '*' && ch == '/' {
ch = s.next()
break
}
}
return ch
}
*/
| bww/Ego | scanner.go | GO | bsd-3-clause | 25,845 |
//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
#ifndef CHCHRONO_H
#define CHCHRONO_H
//////////////////////////////////////////////////
//
// ChChrono.h
//
// Generic header for Chrono API/SDK,
//
// HEADER file for CHRONO,
// Multibody dynamics engine
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
//
// Following is documentation for 1st page of SDK help, aimed at the Doxygen
// tool which builds the html/pdf/help by automatically scanning these
// headers.
//
/*! \mainpage Chrono Engine API/SDK documentation
*
* <div align="center"><img src="logo_chronoengine_middle.png" ></div>
*
* \section intro Introduction
*
* Welcome to the Chrono::Engine API/SDK documentation.
* Here you'll find any information you'll need to develop applications with
* the Chrono Engine.
*
* The Chrono::Engine is a C++ library of tools for physics simulation (multibody
* dynamics, kinematics, etc.). This documentation is an important part of it.
* If you have any questions or suggestions, just send a email to the author
* of the engine, Alessandro Tasora (tasora (at) deltaknowledge.com).
*
*
* \section links Links
*
* <A HREF="namespaces.html">Namespaces</A>: An interesting place to start reading
* the documentation.<BR>
* <A HREF="annotated.html">Class list</A>: List of all classes with descriptions.<BR>
* <A HREF="functions.html">Class members</A>: Nice place to find forgotten features.<BR>
*
* Everything in the engine is
* placed into the namespace 'chrono'. All Chrono classes and functions should be
* accessed with th e:: syntax, as: chrono::[class or functions here] . Of course, in
* sake of a more compact syntax, you could avoid all the chrono::... typing by adding at the
* beginning of your source code the following statement:
*
* \code
* using namespace chrono;
* \endcode
*
* There are also other namespaces.
* You can find a list of all namespaces with descriptions at the
* <A HREF="namespaces.html"> namespaces page</A>.
* This is also a good place to start reading the documentation.
* If you don't want to write the namespace names all the time, just use all namespaces,
* like in this example:
* \code
* using namespace collision;
* using namespace pneumatics;
* using namespace geometry;
* \endcode
*
* There is a lot more the engine can do, but we hope this gave a short
* overview over the basic features of the engine. For some examples, please take
* a look into the 'demos' directory of the SDK, and read the tutorials.
*/
namespace chrono
{
} // END_OF_NAMESPACE____
#endif // END of header
| scpeters/chrono | src/core/ChChrono.h | C | bsd-3-clause | 3,018 |
/**
* @docs https://docs.mollie.com/reference/v2/refunds-api/cancel-refund
*/
import createMollieClient from '@mollie/api-client';
const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' });
(async () => {
try {
const status: boolean = await mollieClient.paymentRefunds.cancel('re_4qqhO89gsT', { paymentId: 'tr_WDqYK6vllg' });
console.log(status);
} catch (error) {
console.warn(error);
}
})();
| mollie/mollie-api-node | examples/refunds/cancel.ts | TypeScript | bsd-3-clause | 450 |
#include <stdlib.h>
#include "FCam/Lens.h"
#include "FCam/Frame.h"
#include "Debug.h"
namespace FCam {
Lens::FocusAction::FocusAction(Lens *l) :
lens(l) {
focus = 0.0f;
speed = lens->maxFocusSpeed();
latency = lens->focusLatency();
time = 0;
}
Lens::FocusAction::FocusAction(Lens *l, int t, float f) :
focus(f), lens(l) {
speed = lens->maxFocusSpeed();
latency = lens->focusLatency();
time = t;
}
Lens::FocusAction::FocusAction(Lens *l, int t, float f, float s) :
focus(f), speed(s), lens(l) {
latency = lens->focusLatency();
time = t;
}
void Lens::FocusAction::doAction() {
lens->setFocus(focus, speed);
}
Lens::FocusSteppingAction::FocusSteppingAction(Lens *l) :
lens(l) {
step = 0.0f;
speed = lens->maxFocusSpeed();
latency = lens->focusLatency();
time = 0;
repeat = 1;
}
Lens::FocusSteppingAction::FocusSteppingAction(Lens *l, int r, int t, float f) :
step(f), repeat(r), lens(l) {
speed = lens->maxFocusSpeed();
latency = lens->focusLatency();
time = t;
}
Lens::FocusSteppingAction::FocusSteppingAction(Lens *l, int r, int t, float f, float s) :
step(f), speed(s), repeat(r), lens(l) {
latency = lens->focusLatency();
time = t;
}
void Lens::FocusSteppingAction::doAction() {
if (repeat > 0 && !lens->focusChanging()) {
float current = lens->getFocus();
lens->setFocus(step + current, speed);
repeat--;
}
}
Lens::ZoomAction::ZoomAction(Lens *l) :
lens(l) {
zoom = 0.0f;
speed = lens->maxZoomSpeed();
latency = lens->zoomLatency();
time = 0;
}
Lens::ZoomAction::ZoomAction(Lens *l, int t, float f) :
zoom(f), lens(l) {
speed = lens->maxZoomSpeed();
latency = lens->zoomLatency();
time = t;
}
Lens::ZoomAction::ZoomAction(Lens *l, int t, float f, float s) :
zoom(f), speed(s), lens(l) {
latency = lens->zoomLatency();
time = t;
}
void Lens::ZoomAction::doAction() {
lens->setZoom(zoom, speed);
}
Lens::ApertureAction::ApertureAction(Lens *l) :
lens(l) {
aperture = 0.0f;
speed = lens->maxApertureSpeed();
latency = lens->apertureLatency();
time = 0;
}
Lens::ApertureAction::ApertureAction(Lens *l, int t, float f) :
aperture(f), lens(l) {
speed = lens->maxApertureSpeed();
latency = lens->apertureLatency();
time = t;
}
Lens::ApertureAction::ApertureAction(Lens *l, int t, float f, float s) :
aperture(f), speed(s), lens(l) {
latency = lens->apertureLatency();
time = t;
}
void Lens::ApertureAction::doAction() {
lens->setAperture(aperture, speed);
}
Lens::Tags::Tags(Frame f) {
initialFocus = f["lens.initialFocus"];
finalFocus = f["lens.finalFocus"];
focus = f["lens.focus"];
focusSpeed = f["lens.focusSpeed"];
zoom = f["lens.zoom"];
initialZoom = f["lens.initialZoom"];
finalZoom = f["lens.finalZoom"];
aperture = f["lens.aperture"];
initialAperture = f["lens.initialAperture"];
finalAperture = f["lens.finalAperture"];
apertureSpeed = f["lens.apertureSpeed"];
}
}
| mattrubin/CameraAssist | external/FCam/Lens.cpp | C++ | bsd-3-clause | 3,547 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\PostSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="post-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'content') ?>
<?= $form->field($model, 'category_id') ?>
<?= $form->field($model, 'status') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| monroesummer/myblog.loc | modules/admin/views/post/_search.php | PHP | bsd-3-clause | 755 |
#ifndef _CURSES_H
#define _CURSES_H
#include <ansi.h>
/* Lots of junk here, not packaged right. */
extern char termcap[];
extern char tc[];
extern char *ttytype;
extern char *arp;
extern char *cp;
extern char *cl;
extern char *cm;
extern char *so;
extern char *se;
extern char /* nscrn[ROWS][COLS], cscrn[ROWS][COLS], */ row, col, mode;
extern char str[];
_PROTOTYPE( void addstr, (char *_s) );
_PROTOTYPE( void clear, (void) );
_PROTOTYPE( void clrtobot, (void) );
_PROTOTYPE( void clrtoeol, (void) );
_PROTOTYPE( void endwin, (void) );
_PROTOTYPE( void fatal, (char *_s) );
_PROTOTYPE( char inch, (void) );
_PROTOTYPE( void initscr, (void) );
_PROTOTYPE( void move, (int _y, int _x) );
/* WRONG, next is varargs. */
_PROTOTYPE( void printw, (char *_fmt, char *_a1, char *_a2, char *_a3,
char *_a4, char *_a5) );
_PROTOTYPE( void outc, (int _c) );
_PROTOTYPE( void refresh, (void) );
_PROTOTYPE( void standend, (void) );
_PROTOTYPE( void standout, (void) );
_PROTOTYPE( void touchwin, (void) );
#endif /* _CURSES_H */
| macminix/MacMinix | include/curses.h | C | bsd-3-clause | 1,093 |
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import GeoLabel (toString, fromString')
import GeoLabel.Strings (format, parse)
import GeoLabel.Strings.Wordlist (wordlist)
import GeoLabel.Geometry.QuadTree (Subface(A,B,C,D))
import GeoLabel.Geometry.Point (lengthOf, (<->))
import GeoLabel.Geometry.Conversion (cartesian)
import GeoLabel.Geometry.Polar (Polar(..))
import GeoLabel.Geodesic.Earth (earthRadius)
import GeoLabel.Unit.Location (Location(..), idOf, fromId)
import Numeric.Units.Dimensional ((*~), one)
import Numeric.Units.Dimensional.SIUnits (meter)
import System.Exit (exitFailure)
import Test.QuickCheck (quickCheckResult, Result(..), forAll, vector, vectorOf, elements, choose)
import Data.Maybe (fromJust)
import GeoLabel.Real (R)
import Data.Number.BigFloat (BigFloat, Prec50, Epsilon)
import System.Random (Random, randomR, random)
instance Epsilon e => Random (BigFloat e) where
randomR (a,b) g = (c,g')
where
(d,g') = randomR (realToFrac a :: Double, realToFrac b) g
c = realToFrac d
random g = (realToFrac (d :: Double), g')
where (d,g') = random g
main :: IO ()
main = do
print "testing location -> bits -> location"
try $ quickCheckResult idTest
print "testing location -> String -> location"
try $ quickCheckResult locTest
print "testing coordinate -> String -> coordinate"
try $ quickCheckResult coordTest
try :: (IO Result) -> IO ()
try test = do
result <- test
case result of
Failure{..} -> exitFailure
_ -> return ()
idTest = forAll (choose (0,19)) $ \face ->
forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces ->
let loc = Location face subfaces in
loc == (fromJust . fromId . idOf $ loc)
locTest = forAll (choose (0,19)) $ \face ->
forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces ->
let loc = Location face subfaces in
loc == (fromJust . parse . format $ loc)
coordTest = forAll (choose (0.0, pi)) $ \lat ->
forAll (choose (0.0, pi)) $ \lon ->
acceptableError (lat, lon) (fromString' . toString $ (lat, lon))
acceptableError :: (R, R) -> (R, R) -> Bool
acceptableError (a1, b1) (a2, b2) = difference <= 0.2 *~ meter
where
point1 = cartesian (Polar earthRadius (a1 *~ one) (b1 *~ one))
point2 = cartesian (Polar earthRadius (a2 *~ one) (b2 *~ one))
difference = lengthOf (point1 <-> point2)
-- Infinite loop?
-- 1.1477102348032477
-- 2.5287052457281303
-- toString (1.1477102348032477, 2.5287052457281303)
-- It's resulting in a lot of kicks
-- It's landing really far away
-- V3 -1615695.0421316223 m 3918971.9410642236 m 582344.6221676043 m
--0.5342809894312989
--2.434338807577105
-- V3 2089283.5979154985 m 1236191.1378369904 m -2840087.204665418 m | wyager/GeoLabel | src/GeoLabel/Test.hs | Haskell | bsd-3-clause | 2,776 |
/* Catalog */
#select_city_chosen {
width: 100% !important;
}
#companyform_categories_chosen {
width: 100% !important;
}
.has-error > .chosen-container {
border: 1px solid #a94442 !important;
border-radius: 5px;
}
| baranov-nt/ektscp | frontend/modules/bussness/assets/css/bussness.css | CSS | bsd-3-clause | 232 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/generic/listctrl.cpp
// Purpose: generic implementation of wxListCtrl
// Author: Robert Roebling
// Vadim Zeitlin (virtual list control support)
// Copyright: (c) 1998 Robert Roebling
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// TODO
//
// 1. we need to implement searching/sorting for virtual controls somehow
// 2. when changing selection the lines are refreshed twice
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_LISTCTRL
#include "wx/listctrl.h"
#ifndef WX_PRECOMP
#include "wx/scrolwin.h"
#include "wx/timer.h"
#include "wx/settings.h"
#include "wx/dynarray.h"
#include "wx/dcclient.h"
#include "wx/dcscreen.h"
#include "wx/math.h"
#include "wx/settings.h"
#include "wx/sizer.h"
#endif
#include "wx/imaglist.h"
#include "wx/renderer.h"
#include "wx/generic/private/listctrl.h"
#include "wx/generic/private/widthcalc.h"
#ifdef __WXMAC__
#include "wx/osx/private.h"
#endif
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
#include "wx/msw/wrapwin.h"
#endif
// NOTE: If using the wxListBox visual attributes works everywhere then this can
// be removed, as well as the #else case below.
#define _USE_VISATTR 0
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
static const int SCROLL_UNIT_X = 15;
// the spacing between the lines (in report mode)
static const int LINE_SPACING = 0;
// extra margins around the text label
#ifdef __WXGTK__
static const int EXTRA_WIDTH = 6;
#else
static const int EXTRA_WIDTH = 4;
#endif
#ifdef __WXGTK__
static const int EXTRA_HEIGHT = 6;
#else
static const int EXTRA_HEIGHT = 4;
#endif
// margin between the window and the items
static const int EXTRA_BORDER_X = 2;
static const int EXTRA_BORDER_Y = 2;
#ifdef __WXGTK__
// This probably needs to be done
// on all platforms as the icons
// otherwise nearly touch the border
static const int ICON_OFFSET_X = 2;
#else
static const int ICON_OFFSET_X = 0;
#endif
// offset for the header window
static const int HEADER_OFFSET_X = 0;
static const int HEADER_OFFSET_Y = 0;
// margin between rows of icons in [small] icon view
static const int MARGIN_BETWEEN_ROWS = 6;
// when autosizing the columns, add some slack
static const int AUTOSIZE_COL_MARGIN = 10;
// default width for the header columns
static const int WIDTH_COL_DEFAULT = 80;
// the space between the image and the text in the report mode
static const int IMAGE_MARGIN_IN_REPORT_MODE = 5;
// the space between the image and the text in the report mode in header
static const int HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2;
// space after a checkbox
static const int MARGIN_AROUND_CHECKBOX = 5;
// ----------------------------------------------------------------------------
// arrays/list implementations
// ----------------------------------------------------------------------------
#include "wx/listimpl.cpp"
WX_DEFINE_LIST(wxListItemDataList)
#include "wx/listimpl.cpp"
WX_DEFINE_LIST(wxListHeaderDataList)
// ----------------------------------------------------------------------------
// wxListItemData
// ----------------------------------------------------------------------------
wxListItemData::~wxListItemData()
{
// in the virtual list control the attributes are managed by the main
// program, so don't delete them
if ( !m_owner->IsVirtual() )
delete m_attr;
delete m_rect;
}
void wxListItemData::Init()
{
m_image = -1;
m_data = 0;
m_attr = NULL;
}
wxListItemData::wxListItemData(wxListMainWindow *owner)
{
Init();
m_owner = owner;
if ( owner->InReportView() )
m_rect = NULL;
else
m_rect = new wxRect;
}
// Check if the item is visible
bool wxGenericListCtrl::IsVisible(long item) const
{
wxRect itemRect;
GetItemRect( item, itemRect );
const wxRect clientRect = GetClientRect();
bool visible = clientRect.Intersects( itemRect );
if ( visible && m_headerWin )
{
wxRect headerRect = m_headerWin->GetClientRect();
// take into account the +1 added in GetSubItemRect()
headerRect.height++;
visible = itemRect.GetBottom() > headerRect.GetBottom();
}
return visible;
}
void wxListItemData::SetItem( const wxListItem &info )
{
if ( info.m_mask & wxLIST_MASK_TEXT )
SetText(info.m_text);
if ( info.m_mask & wxLIST_MASK_IMAGE )
m_image = info.m_image;
if ( info.m_mask & wxLIST_MASK_DATA )
m_data = info.m_data;
if ( info.HasAttributes() )
{
if ( m_attr )
m_attr->AssignFrom(*info.GetAttributes());
else
m_attr = new wxItemAttr(*info.GetAttributes());
}
if ( m_rect )
{
m_rect->x =
m_rect->y =
m_rect->height = 0;
m_rect->width = info.m_width;
}
}
void wxListItemData::SetPosition( int x, int y )
{
wxCHECK_RET( m_rect, wxT("unexpected SetPosition() call") );
m_rect->x = x;
m_rect->y = y;
}
void wxListItemData::SetSize( int width, int height )
{
wxCHECK_RET( m_rect, wxT("unexpected SetSize() call") );
if ( width != -1 )
m_rect->width = width;
if ( height != -1 )
m_rect->height = height;
}
bool wxListItemData::IsHit( int x, int y ) const
{
wxCHECK_MSG( m_rect, false, wxT("can't be called in this mode") );
return wxRect(GetX(), GetY(), GetWidth(), GetHeight()).Contains(x, y);
}
int wxListItemData::GetX() const
{
wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
return m_rect->x;
}
int wxListItemData::GetY() const
{
wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
return m_rect->y;
}
int wxListItemData::GetWidth() const
{
wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
return m_rect->width;
}
int wxListItemData::GetHeight() const
{
wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
return m_rect->height;
}
void wxListItemData::GetItem( wxListItem &info ) const
{
long mask = info.m_mask;
if ( !mask )
// by default, get everything for backwards compatibility
mask = -1;
if ( mask & wxLIST_MASK_TEXT )
info.m_text = m_text;
if ( mask & wxLIST_MASK_IMAGE )
info.m_image = m_image;
if ( mask & wxLIST_MASK_DATA )
info.m_data = m_data;
if ( m_attr )
{
if ( m_attr->HasTextColour() )
info.SetTextColour(m_attr->GetTextColour());
if ( m_attr->HasBackgroundColour() )
info.SetBackgroundColour(m_attr->GetBackgroundColour());
if ( m_attr->HasFont() )
info.SetFont(m_attr->GetFont());
}
}
//-----------------------------------------------------------------------------
// wxListHeaderData
//-----------------------------------------------------------------------------
void wxListHeaderData::Init()
{
m_mask = 0;
m_image = -1;
m_format = 0;
m_width = 0;
m_xpos = 0;
m_ypos = 0;
m_height = 0;
m_state = 0;
}
wxListHeaderData::wxListHeaderData()
{
Init();
}
wxListHeaderData::wxListHeaderData( const wxListItem &item )
{
Init();
SetItem( item );
}
void wxListHeaderData::SetItem( const wxListItem &item )
{
m_mask = item.m_mask;
if ( m_mask & wxLIST_MASK_TEXT )
m_text = item.m_text;
if ( m_mask & wxLIST_MASK_IMAGE )
m_image = item.m_image;
if ( m_mask & wxLIST_MASK_FORMAT )
m_format = item.m_format;
if ( m_mask & wxLIST_MASK_WIDTH )
SetWidth(item.m_width);
if ( m_mask & wxLIST_MASK_STATE )
SetState(item.m_state);
}
void wxListHeaderData::SetPosition( int x, int y )
{
m_xpos = x;
m_ypos = y;
}
void wxListHeaderData::SetHeight( int h )
{
m_height = h;
}
void wxListHeaderData::SetWidth( int w )
{
m_width = w < 0 ? WIDTH_COL_DEFAULT : w;
}
void wxListHeaderData::SetState( int flag )
{
m_state = flag;
}
void wxListHeaderData::SetFormat( int format )
{
m_format = format;
}
bool wxListHeaderData::HasImage() const
{
return m_image != -1;
}
bool wxListHeaderData::IsHit( int x, int y ) const
{
return ((x >= m_xpos) && (x <= m_xpos+m_width) && (y >= m_ypos) && (y <= m_ypos+m_height));
}
void wxListHeaderData::GetItem( wxListItem& item )
{
long mask = item.m_mask;
if ( !mask )
{
// by default, get everything for backwards compatibility
mask = -1;
}
if ( mask & wxLIST_MASK_STATE )
item.m_state = m_state;
if ( mask & wxLIST_MASK_TEXT )
item.m_text = m_text;
if ( mask & wxLIST_MASK_IMAGE )
item.m_image = m_image;
if ( mask & wxLIST_MASK_WIDTH )
item.m_width = m_width;
if ( mask & wxLIST_MASK_FORMAT )
item.m_format = m_format;
}
int wxListHeaderData::GetImage() const
{
return m_image;
}
int wxListHeaderData::GetWidth() const
{
return m_width;
}
int wxListHeaderData::GetFormat() const
{
return m_format;
}
int wxListHeaderData::GetState() const
{
return m_state;
}
//-----------------------------------------------------------------------------
// wxListLineData
//-----------------------------------------------------------------------------
inline int wxListLineData::GetMode() const
{
return m_owner->GetListCtrl()->GetWindowStyleFlag() & wxLC_MASK_TYPE;
}
inline bool wxListLineData::InReportView() const
{
return m_owner->HasFlag(wxLC_REPORT);
}
inline bool wxListLineData::IsVirtual() const
{
return m_owner->IsVirtual();
}
wxListLineData::wxListLineData( wxListMainWindow *owner )
{
m_owner = owner;
if ( InReportView() )
m_gi = NULL;
else // !report
m_gi = new GeometryInfo;
m_highlighted = false;
m_checked = false;
InitItems( GetMode() == wxLC_REPORT ? m_owner->GetColumnCount() : 1 );
}
void wxListLineData::CalculateSize( wxDC *dc, int spacing )
{
wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
wxCHECK_RET( node, wxT("no subitems at all??") );
wxListItemData *item = node->GetData();
wxString s;
wxCoord lw, lh;
switch ( GetMode() )
{
case wxLC_ICON:
case wxLC_SMALL_ICON:
m_gi->m_rectAll.width = spacing;
s = item->GetText();
if ( s.empty() )
{
lh =
m_gi->m_rectLabel.width =
m_gi->m_rectLabel.height = 0;
}
else // has label
{
dc->GetTextExtent( s, &lw, &lh );
lw += EXTRA_WIDTH;
lh += EXTRA_HEIGHT;
m_gi->m_rectAll.height = spacing + lh;
if (lw > spacing)
m_gi->m_rectAll.width = lw;
m_gi->m_rectLabel.width = lw;
m_gi->m_rectLabel.height = lh;
}
if (item->HasImage())
{
int w, h;
m_owner->GetImageSize( item->GetImage(), w, h );
m_gi->m_rectIcon.width = w + 8;
m_gi->m_rectIcon.height = h + 8;
if ( m_gi->m_rectIcon.width > m_gi->m_rectAll.width )
m_gi->m_rectAll.width = m_gi->m_rectIcon.width;
if ( m_gi->m_rectIcon.height + lh > m_gi->m_rectAll.height - 4 )
m_gi->m_rectAll.height = m_gi->m_rectIcon.height + lh + 4;
}
if ( item->HasText() )
{
m_gi->m_rectHighlight.width = m_gi->m_rectLabel.width;
m_gi->m_rectHighlight.height = m_gi->m_rectLabel.height;
}
else // no text, highlight the icon
{
m_gi->m_rectHighlight.width = m_gi->m_rectIcon.width;
m_gi->m_rectHighlight.height = m_gi->m_rectIcon.height;
}
break;
case wxLC_LIST:
s = item->GetTextForMeasuring();
dc->GetTextExtent( s, &lw, &lh );
lw += EXTRA_WIDTH;
lh += EXTRA_HEIGHT;
m_gi->m_rectLabel.width = lw;
m_gi->m_rectLabel.height = lh;
m_gi->m_rectAll.width = lw;
m_gi->m_rectAll.height = lh;
if (item->HasImage())
{
int w, h;
m_owner->GetImageSize( item->GetImage(), w, h );
m_gi->m_rectIcon.width = w;
m_gi->m_rectIcon.height = h;
m_gi->m_rectAll.width += 4 + w;
if (h > m_gi->m_rectAll.height)
m_gi->m_rectAll.height = h;
}
m_gi->m_rectHighlight.width = m_gi->m_rectAll.width;
m_gi->m_rectHighlight.height = m_gi->m_rectAll.height;
break;
case wxLC_REPORT:
wxFAIL_MSG( wxT("unexpected call to SetSize") );
break;
default:
wxFAIL_MSG( wxT("unknown mode") );
break;
}
}
void wxListLineData::SetPosition( int x, int y, int spacing )
{
wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
wxCHECK_RET( node, wxT("no subitems at all??") );
wxListItemData *item = node->GetData();
switch ( GetMode() )
{
case wxLC_ICON:
case wxLC_SMALL_ICON:
m_gi->m_rectAll.x = x;
m_gi->m_rectAll.y = y;
if ( item->HasImage() )
{
m_gi->m_rectIcon.x = m_gi->m_rectAll.x + 4 +
(m_gi->m_rectAll.width - m_gi->m_rectIcon.width) / 2;
m_gi->m_rectIcon.y = m_gi->m_rectAll.y + 4;
}
if ( item->HasText() )
{
if (m_gi->m_rectAll.width > spacing)
m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2);
else
m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2) + (spacing / 2) - (m_gi->m_rectLabel.width / 2);
m_gi->m_rectLabel.y = m_gi->m_rectAll.y + m_gi->m_rectAll.height + 2 - m_gi->m_rectLabel.height;
m_gi->m_rectHighlight.x = m_gi->m_rectLabel.x - 2;
m_gi->m_rectHighlight.y = m_gi->m_rectLabel.y - 2;
}
else // no text, highlight the icon
{
m_gi->m_rectHighlight.x = m_gi->m_rectIcon.x - 4;
m_gi->m_rectHighlight.y = m_gi->m_rectIcon.y - 4;
}
break;
case wxLC_LIST:
m_gi->m_rectAll.x = x;
m_gi->m_rectAll.y = y;
m_gi->m_rectHighlight.x = m_gi->m_rectAll.x;
m_gi->m_rectHighlight.y = m_gi->m_rectAll.y;
m_gi->m_rectLabel.y = m_gi->m_rectAll.y + 2;
if (item->HasImage())
{
m_gi->m_rectIcon.x = m_gi->m_rectAll.x + 2;
m_gi->m_rectIcon.y = m_gi->m_rectAll.y + 2;
m_gi->m_rectLabel.x = m_gi->m_rectAll.x + 4 + (EXTRA_WIDTH/2) + m_gi->m_rectIcon.width;
}
else
{
m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2);
}
break;
case wxLC_REPORT:
wxFAIL_MSG( wxT("unexpected call to SetPosition") );
break;
default:
wxFAIL_MSG( wxT("unknown mode") );
break;
}
}
void wxListLineData::InitItems( int num )
{
for (int i = 0; i < num; i++)
m_items.Append( new wxListItemData(m_owner) );
}
void wxListLineData::SetItem( int index, const wxListItem &info )
{
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
wxCHECK_RET( node, wxT("invalid column index in SetItem") );
wxListItemData *item = node->GetData();
item->SetItem( info );
}
void wxListLineData::GetItem( int index, wxListItem &info ) const
{
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
if (node)
{
wxListItemData *item = node->GetData();
item->GetItem( info );
}
}
wxString wxListLineData::GetText(int index) const
{
wxString s;
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
if (node)
{
wxListItemData *item = node->GetData();
s = item->GetText();
}
return s;
}
void wxListLineData::SetText( int index, const wxString& s )
{
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
if (node)
{
wxListItemData *item = node->GetData();
item->SetText( s );
}
}
void wxListLineData::SetImage( int index, int image )
{
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
wxCHECK_RET( node, wxT("invalid column index in SetImage()") );
wxListItemData *item = node->GetData();
item->SetImage(image);
}
int wxListLineData::GetImage( int index ) const
{
wxListItemDataList::compatibility_iterator node = m_items.Item( index );
wxCHECK_MSG( node, -1, wxT("invalid column index in GetImage()") );
wxListItemData *item = node->GetData();
return item->GetImage();
}
wxItemAttr *wxListLineData::GetAttr() const
{
wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
wxCHECK_MSG( node, NULL, wxT("invalid column index in GetAttr()") );
wxListItemData *item = node->GetData();
return item->GetAttr();
}
void wxListLineData::SetAttr(wxItemAttr *attr)
{
wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
wxCHECK_RET( node, wxT("invalid column index in SetAttr()") );
wxListItemData *item = node->GetData();
item->SetAttr(attr);
}
void wxListLineData::ApplyAttributes(wxDC *dc,
const wxRect& rectHL,
bool highlighted,
bool current)
{
const wxItemAttr * const attr = GetAttr();
wxWindow * const listctrl = m_owner->GetParent();
const bool hasFocus = listctrl->HasFocus();
// fg colour
// don't use foreground colour for drawing highlighted items - this might
// make them completely invisible (and there is no way to do bit
// arithmetics on wxColour, unfortunately)
wxColour colText;
if ( highlighted )
{
#ifdef __WXMAC__
if ( hasFocus )
colText = *wxWHITE;
else
colText = *wxBLACK;
#else
if ( hasFocus )
colText = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
else
colText = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT);
#endif
}
else if ( attr && attr->HasTextColour() )
colText = attr->GetTextColour();
else
colText = listctrl->GetForegroundColour();
dc->SetTextForeground(colText);
// font
wxFont font;
if ( attr && attr->HasFont() )
font = attr->GetFont();
else
font = listctrl->GetFont();
dc->SetFont(font);
// background
if ( highlighted )
{
// Use the renderer method to ensure that the selected items use the
// native look.
int flags = wxCONTROL_SELECTED;
if ( hasFocus )
flags |= wxCONTROL_FOCUSED;
if (current)
flags |= wxCONTROL_CURRENT;
wxRendererNative::Get().
DrawItemSelectionRect( m_owner, *dc, rectHL, flags );
}
else if ( attr && attr->HasBackgroundColour() )
{
// Draw the background using the items custom background colour.
dc->SetBrush(attr->GetBackgroundColour());
dc->SetPen(*wxTRANSPARENT_PEN);
dc->DrawRectangle(rectHL);
}
// just for debugging to better see where the items are
#if 0
dc->SetPen(*wxRED_PEN);
dc->SetBrush(*wxTRANSPARENT_BRUSH);
dc->DrawRectangle( m_gi->m_rectAll );
dc->SetPen(*wxGREEN_PEN);
dc->DrawRectangle( m_gi->m_rectIcon );
#endif
}
void wxListLineData::Draw(wxDC *dc, bool current)
{
wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
wxCHECK_RET( node, wxT("no subitems at all??") );
ApplyAttributes(dc, m_gi->m_rectHighlight, IsHighlighted(), current);
wxListItemData *item = node->GetData();
if (item->HasImage())
{
// centre the image inside our rectangle, this looks nicer when items
// ae aligned in a row
const wxRect& rectIcon = m_gi->m_rectIcon;
m_owner->DrawImage(item->GetImage(), dc, rectIcon.x, rectIcon.y);
}
if (item->HasText())
{
const wxRect& rectLabel = m_gi->m_rectLabel;
wxDCClipper clipper(*dc, rectLabel);
dc->DrawText(item->GetText(), rectLabel.x, rectLabel.y);
}
}
void wxListLineData::DrawInReportMode( wxDC *dc,
const wxRect& rect,
const wxRect& rectHL,
bool highlighted,
bool current )
{
// TODO: later we should support setting different attributes for
// different columns - to do it, just add "col" argument to
// GetAttr() and move these lines into the loop below
// Note: GetSubItemRect() needs to be modified if the layout here changes.
ApplyAttributes(dc, rectHL, highlighted, current);
wxCoord x = rect.x + HEADER_OFFSET_X + ICON_OFFSET_X,
yMid = rect.y + rect.height/2;
if ( m_owner->HasCheckBoxes() )
{
wxSize cbSize = wxRendererNative::Get().GetCheckBoxSize(m_owner);
int yOffset = (rect.height - cbSize.GetHeight()) / 2;
wxRect rr(wxPoint(x, rect.y + yOffset), cbSize);
rr.x += MARGIN_AROUND_CHECKBOX;
int flags = 0;
if (m_checked)
flags |= wxCONTROL_CHECKED;
wxRendererNative::Get().DrawCheckBox(m_owner, *dc, rr, flags);
x += cbSize.GetWidth() + (2 * MARGIN_AROUND_CHECKBOX);
}
size_t col = 0;
for ( wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
node;
node = node->GetNext(), col++ )
{
wxListItemData *item = node->GetData();
int width = m_owner->GetColumnWidth(col);
if (col == 0 && m_owner->HasCheckBoxes())
width -= x;
int xOld = x;
x += width;
width -= 8;
const int wText = width;
wxDCClipper clipper(*dc, xOld, rect.y, wText, rect.height);
if ( item->HasImage() )
{
int ix, iy;
m_owner->GetImageSize( item->GetImage(), ix, iy );
m_owner->DrawImage( item->GetImage(), dc, xOld, yMid - iy/2 );
ix += IMAGE_MARGIN_IN_REPORT_MODE;
xOld += ix;
width -= ix;
}
if ( item->HasText() )
DrawTextFormatted(dc, item->GetText(), col, xOld, yMid, width);
}
}
void wxListLineData::DrawTextFormatted(wxDC *dc,
const wxString& textOrig,
int col,
int x,
int yMid,
int width)
{
// we don't support displaying multiple lines currently (and neither does
// wxMSW FWIW) so just merge all the lines
wxString text(textOrig);
text.Replace(wxT("\n"), wxT(" "));
wxCoord w, h;
dc->GetTextExtent(text, &w, &h);
const wxCoord y = yMid - (h + 1)/2;
wxDCClipper clipper(*dc, x, y, width, h);
// determine if the string can fit inside the current width
if (w <= width)
{
// it can, draw it using the items alignment
wxListItem item;
m_owner->GetColumn(col, item);
switch ( item.GetAlign() )
{
case wxLIST_FORMAT_LEFT:
// nothing to do
break;
case wxLIST_FORMAT_RIGHT:
x += width - w;
break;
case wxLIST_FORMAT_CENTER:
x += (width - w) / 2;
break;
default:
wxFAIL_MSG( wxT("unknown list item format") );
break;
}
dc->DrawText(text, x, y);
}
else // otherwise, truncate and add an ellipsis if possible
{
// determine the base width
wxString ellipsis(wxT("..."));
wxCoord base_w;
dc->GetTextExtent(ellipsis, &base_w, &h);
// continue until we have enough space or only one character left
wxCoord w_c, h_c;
size_t len = text.length();
wxString drawntext = text.Left(len);
while (len > 1)
{
dc->GetTextExtent(drawntext.Last(), &w_c, &h_c);
drawntext.RemoveLast();
len--;
w -= w_c;
if (w + base_w <= width)
break;
}
// if still not enough space, remove ellipsis characters
while (ellipsis.length() > 0 && w + base_w > width)
{
ellipsis = ellipsis.Left(ellipsis.length() - 1);
dc->GetTextExtent(ellipsis, &base_w, &h);
}
// now draw the text
dc->DrawText(drawntext, x, y);
dc->DrawText(ellipsis, x + w, y);
}
}
bool wxListLineData::Highlight( bool on )
{
wxCHECK_MSG( !IsVirtual(), false, wxT("unexpected call to Highlight") );
if ( on == m_highlighted )
return false;
m_highlighted = on;
m_owner->UpdateSelectionCount(on);
return true;
}
void wxListLineData::ReverseHighlight( void )
{
Highlight(!IsHighlighted());
}
//-----------------------------------------------------------------------------
// wxListHeaderWindow
//-----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(wxListHeaderWindow,wxWindow)
EVT_PAINT (wxListHeaderWindow::OnPaint)
EVT_MOUSE_EVENTS (wxListHeaderWindow::OnMouse)
wxEND_EVENT_TABLE()
void wxListHeaderWindow::Init()
{
m_currentCursor = NULL;
m_isDragging = false;
m_dirty = false;
m_sendSetColumnWidth = false;
}
wxListHeaderWindow::wxListHeaderWindow()
{
Init();
m_owner = NULL;
m_resizeCursor = NULL;
}
bool wxListHeaderWindow::Create( wxWindow *win,
wxWindowID id,
wxListMainWindow *owner,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString &name )
{
if ( !wxWindow::Create(win, id, pos, size, style, name) )
return false;
Init();
m_owner = owner;
m_resizeCursor = new wxCursor( wxCURSOR_SIZEWE );
#if _USE_VISATTR
wxVisualAttributes attr = wxPanel::GetClassDefaultAttributes();
SetOwnForegroundColour( attr.colFg );
SetOwnBackgroundColour( attr.colBg );
if (!m_hasFont)
SetOwnFont( attr.font );
#else
SetOwnForegroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
SetOwnBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
if (!m_hasFont)
SetOwnFont( wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT ));
#endif
return true;
}
wxListHeaderWindow::~wxListHeaderWindow()
{
delete m_resizeCursor;
}
#ifdef __WXUNIVERSAL__
#include "wx/univ/renderer.h"
#include "wx/univ/theme.h"
#endif
// shift the DC origin to match the position of the main window horz
// scrollbar: this allows us to always use logical coords
void wxListHeaderWindow::AdjustDC(wxDC& dc)
{
wxGenericListCtrl *parent = m_owner->GetListCtrl();
int xpix;
parent->GetScrollPixelsPerUnit( &xpix, NULL );
int view_start;
parent->GetViewStart( &view_start, NULL );
int org_x = 0;
int org_y = 0;
dc.GetDeviceOrigin( &org_x, &org_y );
// account for the horz scrollbar offset
#if defined(__WXGTK__) && !defined(__WXGTK3__)
if (GetLayoutDirection() == wxLayout_RightToLeft)
{
// Maybe we just have to check for m_signX
// in the DC, but I leave the #ifdef __WXGTK__
// for now
dc.SetDeviceOrigin( org_x + (view_start * xpix), org_y );
}
else
#endif
dc.SetDeviceOrigin( org_x - (view_start * xpix), org_y );
}
void wxListHeaderWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
{
wxGenericListCtrl *parent = m_owner->GetListCtrl();
wxPaintDC dc( this );
AdjustDC( dc );
dc.SetFont( GetFont() );
// width and height of the entire header window
int w, h;
GetClientSize( &w, &h );
parent->CalcUnscrolledPosition(w, 0, &w, NULL);
dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
dc.SetTextForeground(GetForegroundColour());
int x = HEADER_OFFSET_X;
int numColumns = m_owner->GetColumnCount();
wxListItem item;
for ( int i = 0; i < numColumns && x < w; i++ )
{
m_owner->GetColumn( i, item );
int wCol = item.m_width;
int cw = wCol;
int ch = h;
int flags = 0;
if (!m_parent->IsEnabled())
flags |= wxCONTROL_DISABLED;
// NB: The code below is not really Mac-specific, but since we are close
// to 2.8 release and I don't have time to test on other platforms, I
// defined this only for wxMac. If this behaviour is desired on
// other platforms, please go ahead and revise or remove the #ifdef.
#ifdef __WXMAC__
if ( !m_owner->IsVirtual() && (item.m_mask & wxLIST_MASK_STATE) &&
(item.m_state & wxLIST_STATE_SELECTED) )
flags |= wxCONTROL_SELECTED;
#endif
if (i == 0)
flags |= wxCONTROL_SPECIAL; // mark as first column
wxRendererNative::Get().DrawHeaderButton
(
this,
dc,
wxRect(x, HEADER_OFFSET_Y, cw, ch),
flags
);
// see if we have enough space for the column label
// for this we need the width of the text
wxCoord wLabel;
wxCoord hLabel;
dc.GetTextExtent(item.GetText(), &wLabel, &hLabel);
wLabel += 2 * EXTRA_WIDTH;
// and the width of the icon, if any
int ix = 0, iy = 0; // init them just to suppress the compiler warnings
const int image = item.m_image;
wxImageList *imageList;
if ( image != -1 )
{
imageList = m_owner->GetSmallImageList();
if ( imageList )
{
imageList->GetSize(image, ix, iy);
wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE;
}
}
else
{
imageList = NULL;
}
// ignore alignment if there is not enough space anyhow
int xAligned;
switch ( wLabel < cw ? item.GetAlign() : wxLIST_FORMAT_LEFT )
{
default:
wxFAIL_MSG( wxT("unknown list item format") );
wxFALLTHROUGH;
case wxLIST_FORMAT_LEFT:
xAligned = x;
break;
case wxLIST_FORMAT_RIGHT:
xAligned = x + cw - wLabel;
break;
case wxLIST_FORMAT_CENTER:
xAligned = x + (cw - wLabel) / 2;
break;
}
// draw the text and image clipping them so that they
// don't overwrite the column boundary
wxDCClipper clipper(dc, x, HEADER_OFFSET_Y, cw, h);
// if we have an image, draw it on the right of the label
if ( imageList )
{
imageList->Draw
(
image,
dc,
xAligned + wLabel - ix - HEADER_IMAGE_MARGIN_IN_REPORT_MODE,
HEADER_OFFSET_Y + (h - iy)/2,
wxIMAGELIST_DRAW_TRANSPARENT
);
}
dc.DrawText( item.GetText(),
xAligned + EXTRA_WIDTH, (h - hLabel) / 2 );
x += wCol;
}
// Fill in what's missing to the right of the columns, otherwise we will
// leave an unpainted area when columns are removed (and it looks better)
if ( x < w )
{
wxRendererNative::Get().DrawHeaderButton
(
this,
dc,
wxRect(x, HEADER_OFFSET_Y, w - x, h),
wxCONTROL_DIRTY // mark as last column
);
}
}
void wxListHeaderWindow::OnInternalIdle()
{
wxWindow::OnInternalIdle();
if (m_sendSetColumnWidth)
{
m_owner->SetColumnWidth( m_colToSend, m_widthToSend );
m_sendSetColumnWidth = false;
}
}
void wxListHeaderWindow::DrawCurrent()
{
m_sendSetColumnWidth = true;
m_colToSend = m_column;
m_widthToSend = m_currentX - m_minX;
}
void wxListHeaderWindow::OnMouse( wxMouseEvent &event )
{
wxGenericListCtrl *parent = m_owner->GetListCtrl();
// we want to work with logical coords
int x;
parent->CalcUnscrolledPosition(event.GetX(), 0, &x, NULL);
if (m_isDragging)
{
SendListEvent(wxEVT_LIST_COL_DRAGGING, event.GetPosition());
// we don't draw the line beyond our window, but we allow dragging it
// there
int w = 0;
GetClientSize( &w, NULL );
parent->CalcUnscrolledPosition(w, 0, &w, NULL);
w -= 6;
// erase the line if it was drawn
if ( m_currentX < w )
DrawCurrent();
if (event.ButtonUp())
{
ReleaseMouse();
m_isDragging = false;
m_dirty = true;
m_owner->SetColumnWidth( m_column, m_currentX - m_minX );
SendListEvent(wxEVT_LIST_COL_END_DRAG, event.GetPosition());
}
else
{
if (x > m_minX + 7)
m_currentX = x;
else
m_currentX = m_minX + 7;
// draw in the new location
if ( m_currentX < w )
DrawCurrent();
}
}
else // not dragging
{
m_minX = 0;
bool hit_border = false;
// end of the current column
int xpos = 0;
// find the column where this event occurred
int col,
countCol = m_owner->GetColumnCount();
for (col = 0; col < countCol; col++)
{
xpos += m_owner->GetColumnWidth( col );
m_column = col;
if ( abs(x-xpos) < 3 )
{
// near the column border
hit_border = true;
break;
}
if ( x < xpos )
{
// inside the column
break;
}
m_minX = xpos;
}
if ( col == countCol )
m_column = -1;
if (event.LeftDown() || event.RightUp())
{
if (hit_border && event.LeftDown())
{
if ( SendListEvent(wxEVT_LIST_COL_BEGIN_DRAG,
event.GetPosition()) )
{
m_isDragging = true;
m_currentX = x;
CaptureMouse();
DrawCurrent();
}
//else: column resizing was vetoed by the user code
}
else // click on a column
{
// record the selected state of the columns
if (event.LeftDown())
{
for (int i=0; i < m_owner->GetColumnCount(); i++)
{
wxListItem colItem;
m_owner->GetColumn(i, colItem);
long state = colItem.GetState();
if (i == m_column)
colItem.SetState(state | wxLIST_STATE_SELECTED);
else
colItem.SetState(state & ~wxLIST_STATE_SELECTED);
m_owner->SetColumn(i, colItem);
}
}
SendListEvent( event.LeftDown()
? wxEVT_LIST_COL_CLICK
: wxEVT_LIST_COL_RIGHT_CLICK,
event.GetPosition());
}
}
else if ( event.LeftDClick() && hit_border )
{
// Autosize the column when the divider is clicked: if there are
// any items, fit the columns to its contents, otherwise just fit
// it to its label width.
parent->SetColumnWidth(m_column,
parent->IsEmpty() ? wxLIST_AUTOSIZE_USEHEADER
: wxLIST_AUTOSIZE);
}
else if (event.Moving())
{
bool setCursor;
if (hit_border)
{
setCursor = m_currentCursor == wxSTANDARD_CURSOR;
m_currentCursor = m_resizeCursor;
}
else
{
setCursor = m_currentCursor != wxSTANDARD_CURSOR;
m_currentCursor = wxSTANDARD_CURSOR;
}
if ( setCursor )
SetCursor(*m_currentCursor);
}
}
}
bool wxListHeaderWindow::SendListEvent(wxEventType type, const wxPoint& pos)
{
wxWindow *parent = GetParent();
wxListEvent le( type, parent->GetId() );
le.SetEventObject( parent );
le.m_pointDrag = pos;
le.m_col = m_column;
return !parent->GetEventHandler()->ProcessEvent( le ) || le.IsAllowed();
}
//-----------------------------------------------------------------------------
// wxListRenameTimer (internal)
//-----------------------------------------------------------------------------
wxListRenameTimer::wxListRenameTimer( wxListMainWindow *owner )
{
m_owner = owner;
}
void wxListRenameTimer::Notify()
{
m_owner->OnRenameTimer();
}
//-----------------------------------------------------------------------------
// wxListFindTimer (internal)
//-----------------------------------------------------------------------------
void wxListFindTimer::Notify()
{
m_owner->OnFindTimer();
}
//-----------------------------------------------------------------------------
// wxListTextCtrlWrapper (internal)
//-----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(wxListTextCtrlWrapper, wxEvtHandler)
EVT_CHAR (wxListTextCtrlWrapper::OnChar)
EVT_KEY_UP (wxListTextCtrlWrapper::OnKeyUp)
EVT_KILL_FOCUS (wxListTextCtrlWrapper::OnKillFocus)
wxEND_EVENT_TABLE()
wxListTextCtrlWrapper::wxListTextCtrlWrapper(wxListMainWindow *owner,
wxTextCtrl *text,
size_t itemEdit)
: m_startValue(owner->GetItemText(itemEdit)),
m_itemEdited(itemEdit)
{
m_owner = owner;
m_text = text;
m_aboutToFinish = false;
wxGenericListCtrl *parent = m_owner->GetListCtrl();
wxRect rectLabel = owner->GetLineLabelRect(itemEdit);
parent->CalcScrolledPosition(rectLabel.x, rectLabel.y,
&rectLabel.x, &rectLabel.y);
m_text->Create(owner, wxID_ANY, m_startValue,
wxPoint(rectLabel.x-4,rectLabel.y-4),
wxSize(rectLabel.width+11,rectLabel.height+8));
m_text->SetFocus();
m_text->PushEventHandler(this);
}
void wxListTextCtrlWrapper::EndEdit(EndReason reason)
{
if( m_aboutToFinish )
{
// We already called Finish which cannot be called
// more than once.
return;
}
m_aboutToFinish = true;
switch ( reason )
{
case End_Accept:
// Notify the owner about the changes
AcceptChanges();
// Even if vetoed, close the control (consistent with MSW)
Finish( true );
break;
case End_Discard:
m_owner->OnRenameCancelled(m_itemEdited);
Finish( true );
break;
case End_Destroy:
// Don't generate any notifications for the control being destroyed
// and don't set focus to it neither.
Finish(false);
break;
}
}
void wxListTextCtrlWrapper::Finish( bool setfocus )
{
m_text->RemoveEventHandler(this);
m_owner->ResetTextControl( m_text );
wxPendingDelete.Append( this );
if (setfocus)
m_owner->SetFocus();
}
bool wxListTextCtrlWrapper::AcceptChanges()
{
const wxString value = m_text->GetValue();
// notice that we should always call OnRenameAccept() to generate the "end
// label editing" event, even if the user hasn't really changed anything
if ( !m_owner->OnRenameAccept(m_itemEdited, value) )
{
// vetoed by the user
return false;
}
// accepted, do rename the item (unless nothing changed)
if ( value != m_startValue )
m_owner->SetItemText(m_itemEdited, value);
return true;
}
void wxListTextCtrlWrapper::OnChar( wxKeyEvent &event )
{
if ( !CheckForEndEditKey(event) )
event.Skip();
}
bool wxListTextCtrlWrapper::CheckForEndEditKey(const wxKeyEvent& event)
{
switch ( event.m_keyCode )
{
case WXK_RETURN:
EndEdit( End_Accept );
break;
case WXK_ESCAPE:
EndEdit( End_Discard );
break;
default:
return false;
}
return true;
}
void wxListTextCtrlWrapper::OnKeyUp( wxKeyEvent &event )
{
if (m_aboutToFinish)
{
// auto-grow the textctrl:
wxSize parentSize = m_owner->GetSize();
wxPoint myPos = m_text->GetPosition();
wxSize mySize = m_text->GetSize();
int sx, sy;
m_text->GetTextExtent(m_text->GetValue() + wxT("MM"), &sx, &sy);
if (myPos.x + sx > parentSize.x)
sx = parentSize.x - myPos.x;
if (mySize.x > sx)
sx = mySize.x;
m_text->SetSize(sx, wxDefaultCoord);
}
event.Skip();
}
void wxListTextCtrlWrapper::OnKillFocus( wxFocusEvent &event )
{
if ( !m_aboutToFinish )
{
m_aboutToFinish = true;
if ( !AcceptChanges() )
m_owner->OnRenameCancelled( m_itemEdited );
Finish( false );
}
// We must let the native text control handle focus
event.Skip();
}
//-----------------------------------------------------------------------------
// wxListMainWindow
//-----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(wxListMainWindow, wxWindow)
EVT_PAINT (wxListMainWindow::OnPaint)
EVT_MOUSE_EVENTS (wxListMainWindow::OnMouse)
EVT_CHAR_HOOK (wxListMainWindow::OnCharHook)
EVT_CHAR (wxListMainWindow::OnChar)
EVT_KEY_DOWN (wxListMainWindow::OnKeyDown)
EVT_KEY_UP (wxListMainWindow::OnKeyUp)
EVT_SET_FOCUS (wxListMainWindow::OnSetFocus)
EVT_KILL_FOCUS (wxListMainWindow::OnKillFocus)
EVT_SCROLLWIN (wxListMainWindow::OnScroll)
EVT_CHILD_FOCUS (wxListMainWindow::OnChildFocus)
wxEND_EVENT_TABLE()
void wxListMainWindow::Init()
{
m_dirty = true;
m_selCount =
m_countVirt = 0;
m_lineFrom =
m_lineTo = (size_t)-1;
m_linesPerPage = 0;
m_headerWidth =
m_lineHeight = 0;
m_small_image_list = NULL;
m_normal_image_list = NULL;
m_small_spacing = 30;
m_normal_spacing = 40;
m_hasFocus = false;
m_dragCount = 0;
m_isCreated = false;
m_lastOnSame = false;
m_renameTimer = new wxListRenameTimer( this );
m_findTimer = NULL;
m_findBell = 0; // default is to not ring bell at all
m_textctrlWrapper = NULL;
m_current =
m_lineLastClicked =
m_lineSelectSingleOnUp =
m_lineBeforeLastClicked =
m_anchor = (size_t)-1;
m_hasCheckBoxes = false;
m_extendRulesAndAlternateColour = false;
}
wxListMainWindow::wxListMainWindow()
{
Init();
m_highlightBrush =
m_highlightUnfocusedBrush = NULL;
}
wxListMainWindow::wxListMainWindow( wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size )
: wxWindow( parent, id, pos, size,
wxWANTS_CHARS | wxBORDER_NONE )
{
Init();
m_highlightBrush = new wxBrush
(
wxSystemSettings::GetColour
(
wxSYS_COLOUR_HIGHLIGHT
),
wxBRUSHSTYLE_SOLID
);
m_highlightUnfocusedBrush = new wxBrush
(
wxSystemSettings::GetColour
(
wxSYS_COLOUR_BTNSHADOW
),
wxBRUSHSTYLE_SOLID
);
wxVisualAttributes attr = wxGenericListCtrl::GetClassDefaultAttributes();
SetOwnForegroundColour( attr.colFg );
SetOwnBackgroundColour( attr.colBg );
if (!m_hasFont)
SetOwnFont( attr.font );
}
wxListMainWindow::~wxListMainWindow()
{
if ( m_textctrlWrapper )
m_textctrlWrapper->EndEdit(wxListTextCtrlWrapper::End_Destroy);
DoDeleteAllItems();
WX_CLEAR_LIST(wxListHeaderDataList, m_columns);
WX_CLEAR_ARRAY(m_aColWidths);
delete m_highlightBrush;
delete m_highlightUnfocusedBrush;
delete m_renameTimer;
delete m_findTimer;
}
void wxListMainWindow::SetReportView(bool inReportView)
{
const size_t count = m_lines.size();
for ( size_t n = 0; n < count; n++ )
{
m_lines[n]->SetReportView(inReportView);
}
}
void wxListMainWindow::CacheLineData(size_t line)
{
wxGenericListCtrl *listctrl = GetListCtrl();
wxListLineData *ld = GetDummyLine();
size_t countCol = GetColumnCount();
for ( size_t col = 0; col < countCol; col++ )
{
ld->SetText(col, listctrl->OnGetItemText(line, col));
ld->SetImage(col, listctrl->OnGetItemColumnImage(line, col));
}
if ( HasCheckBoxes() )
{
ld->Check(listctrl->OnGetItemIsChecked(line));
}
ld->SetAttr(listctrl->OnGetItemAttr(line));
}
wxListLineData *wxListMainWindow::GetDummyLine() const
{
wxASSERT_MSG( !IsEmpty(), wxT("invalid line index") );
wxASSERT_MSG( IsVirtual(), wxT("GetDummyLine() shouldn't be called") );
wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
// we need to recreate the dummy line if the number of columns in the
// control changed as it would have the incorrect number of fields
// otherwise
if ( !m_lines.empty() &&
m_lines[0]->m_items.GetCount() != (size_t)GetColumnCount() )
{
self->m_lines.Clear();
}
if ( m_lines.empty() )
{
wxListLineData *line = new wxListLineData(self);
self->m_lines.push_back(line);
// don't waste extra memory -- there never going to be anything
// else/more in this array
wxShrinkToFit(self->m_lines);
}
return m_lines[0];
}
// ----------------------------------------------------------------------------
// line geometry (report mode only)
// ----------------------------------------------------------------------------
wxCoord wxListMainWindow::GetLineHeight() const
{
// we cache the line height as calling GetTextExtent() is slow
if ( !m_lineHeight )
{
wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
wxClientDC dc( self );
dc.SetFont( GetFont() );
wxCoord y;
dc.GetTextExtent(wxT("H"), NULL, &y);
if ( m_small_image_list && m_small_image_list->GetImageCount() )
{
int iw = 0, ih = 0;
m_small_image_list->GetSize(0, iw, ih);
y = wxMax(y, ih);
}
y += EXTRA_HEIGHT;
self->m_lineHeight = y + LINE_SPACING;
}
return m_lineHeight;
}
wxCoord wxListMainWindow::GetLineY(size_t line) const
{
wxASSERT_MSG( InReportView(), wxT("only works in report mode") );
return LINE_SPACING + line * GetLineHeight();
}
wxRect wxListMainWindow::GetLineRect(size_t line) const
{
if ( !InReportView() )
return GetLine(line)->m_gi->m_rectAll;
wxRect rect;
rect.x = HEADER_OFFSET_X;
rect.y = GetLineY(line);
rect.width = GetHeaderWidth();
rect.height = GetLineHeight();
return rect;
}
wxRect wxListMainWindow::GetLineLabelRect(size_t line) const
{
if ( !InReportView() )
return GetLine(line)->m_gi->m_rectLabel;
int image_x = 0;
wxListLineData *data = GetLine(line);
wxListItemDataList::compatibility_iterator node = data->m_items.GetFirst();
if (node)
{
wxListItemData *item = node->GetData();
if ( item->HasImage() )
{
int ix, iy;
GetImageSize( item->GetImage(), ix, iy );
image_x = 3 + ix + IMAGE_MARGIN_IN_REPORT_MODE;
}
}
wxRect rect;
rect.x = image_x + HEADER_OFFSET_X;
rect.y = GetLineY(line);
rect.width = GetColumnWidth(0) - image_x;
rect.height = GetLineHeight();
return rect;
}
wxRect wxListMainWindow::GetLineIconRect(size_t line) const
{
if ( !InReportView() )
return GetLine(line)->m_gi->m_rectIcon;
wxListLineData *ld = GetLine(line);
wxASSERT_MSG( ld->HasImage(), wxT("should have an image") );
wxRect rect;
rect.x = HEADER_OFFSET_X;
rect.y = GetLineY(line);
GetImageSize(ld->GetImage(), rect.width, rect.height);
return rect;
}
wxRect wxListMainWindow::GetLineHighlightRect(size_t line) const
{
return InReportView() ? GetLineRect(line)
: GetLine(line)->m_gi->m_rectHighlight;
}
long wxListMainWindow::HitTestLine(size_t line, int x, int y) const
{
wxASSERT_MSG( line < GetItemCount(), wxT("invalid line in HitTestLine") );
wxListLineData *ld = GetLine(line);
if ( ld->HasImage() && GetLineIconRect(line).Contains(x, y) )
return wxLIST_HITTEST_ONITEMICON;
// VS: Testing for "ld->HasText() || InReportView()" instead of
// "ld->HasText()" is needed to make empty lines in report view
// possible
if ( ld->HasText() || InReportView() )
{
wxRect rect = InReportView() ? GetLineRect(line)
: GetLineLabelRect(line);
if ( rect.Contains(x, y) )
return wxLIST_HITTEST_ONITEMLABEL;
}
return 0;
}
// ----------------------------------------------------------------------------
// highlight (selection) handling
// ----------------------------------------------------------------------------
bool wxListMainWindow::IsHighlighted(size_t line) const
{
if ( IsVirtual() )
{
return m_selStore.IsSelected(line);
}
else // !virtual
{
wxListLineData *ld = GetLine(line);
wxCHECK_MSG( ld, false, wxT("invalid index in IsHighlighted") );
return ld->IsHighlighted();
}
}
void wxListMainWindow::HighlightLines( size_t lineFrom,
size_t lineTo,
bool highlight,
SendEvent sendEvent )
{
// It is safe to swap the bounds here if they are not in order.
if ( lineFrom > lineTo )
wxSwap(lineFrom, lineTo);
if ( IsVirtual() )
{
wxArrayInt linesChanged;
if ( !m_selStore.SelectRange(lineFrom, lineTo, highlight,
&linesChanged) )
{
// meny items changed state, refresh everything
RefreshLines(lineFrom, lineTo);
}
else // only a few items changed state, refresh only them
{
size_t count = linesChanged.GetCount();
for ( size_t n = 0; n < count; n++ )
{
RefreshLine(linesChanged[n]);
}
}
}
else // iterate over all items in non report view
{
for ( size_t line = lineFrom; line <= lineTo; line++ )
{
if ( HighlightLine(line, highlight, sendEvent) )
RefreshLine(line);
}
}
}
bool wxListMainWindow::HighlightLine( size_t line, bool highlight, SendEvent sendEvent )
{
bool changed;
if ( IsVirtual() )
{
changed = m_selStore.SelectItem(line, highlight);
}
else // !virtual
{
wxListLineData *ld = GetLine(line);
wxCHECK_MSG( ld, false, wxT("invalid index in HighlightLine") );
changed = ld->Highlight(highlight);
}
if ( changed && sendEvent )
{
SendNotify( line, highlight ? wxEVT_LIST_ITEM_SELECTED
: wxEVT_LIST_ITEM_DESELECTED );
}
return changed;
}
void wxListMainWindow::RefreshLine( size_t line )
{
if ( InReportView() )
{
size_t visibleFrom, visibleTo;
GetVisibleLinesRange(&visibleFrom, &visibleTo);
if ( line < visibleFrom || line > visibleTo )
return;
}
wxRect rect = GetLineRect(line);
GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
RefreshRect( rect );
}
void wxListMainWindow::RefreshLines( size_t lineFrom, size_t lineTo )
{
// we suppose that they are ordered by caller
wxASSERT_MSG( lineFrom <= lineTo, wxT("indices in disorder") );
wxASSERT_MSG( lineTo < GetItemCount(), wxT("invalid line range") );
if ( InReportView() )
{
size_t visibleFrom, visibleTo;
GetVisibleLinesRange(&visibleFrom, &visibleTo);
if ( lineFrom > visibleTo || lineTo < visibleFrom )
{
// None of these lines are currently visible at all, don't bother
// doing anything.
return;
}
if ( lineFrom < visibleFrom )
lineFrom = visibleFrom;
if ( lineTo > visibleTo )
lineTo = visibleTo;
wxRect rect;
rect.x = 0;
rect.y = GetLineY(lineFrom);
rect.width = GetClientSize().x;
rect.height = GetLineY(lineTo) - rect.y + GetLineHeight();
GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
RefreshRect( rect );
}
else // !report
{
// TODO: this should be optimized...
for ( size_t line = lineFrom; line <= lineTo; line++ )
{
RefreshLine(line);
}
}
}
void wxListMainWindow::RefreshAfter( size_t lineFrom )
{
if ( InReportView() )
{
size_t visibleFrom, visibleTo;
GetVisibleLinesRange(&visibleFrom, &visibleTo);
if ( lineFrom < visibleFrom )
lineFrom = visibleFrom;
else if ( lineFrom > visibleTo )
return;
wxRect rect;
rect.x = 0;
rect.y = GetLineY(lineFrom);
GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
wxSize size = GetClientSize();
rect.width = size.x;
// refresh till the bottom of the window
rect.height = size.y - rect.y;
RefreshRect( rect );
}
else // !report
{
// TODO: how to do it more efficiently?
m_dirty = true;
}
}
void wxListMainWindow::RefreshSelected()
{
if ( IsEmpty() )
return;
size_t from, to;
if ( InReportView() )
{
GetVisibleLinesRange(&from, &to);
}
else // !virtual
{
from = 0;
to = GetItemCount() - 1;
}
if ( HasCurrent() && m_current >= from && m_current <= to )
RefreshLine(m_current);
for ( size_t line = from; line <= to; line++ )
{
// NB: the test works as expected even if m_current == -1
if ( line != m_current && IsHighlighted(line) )
RefreshLine(line);
}
}
void wxListMainWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
{
// Note: a wxPaintDC must be constructed even if no drawing is
// done (a Windows requirement).
wxPaintDC dc( this );
if ( IsEmpty() )
{
// nothing to draw or not the moment to draw it
return;
}
if ( m_dirty )
RecalculatePositions( false );
GetListCtrl()->PrepareDC( dc );
int dev_x, dev_y;
GetListCtrl()->CalcScrolledPosition( 0, 0, &dev_x, &dev_y );
dc.SetFont( GetFont() );
if ( InReportView() )
{
int lineHeight = GetLineHeight();
size_t visibleFrom, visibleTo;
const size_t linesPerPage = (unsigned int) m_linesPerPage;
GetVisibleLinesRange(&visibleFrom, &visibleTo);
// We may need to iterate beyond visibleTo if we want to draw striped
// background across the entire window.
size_t visibleEnd;
wxColour colAlt;
if ( m_extendRulesAndAlternateColour )
{
colAlt = GetListCtrl()->GetAlternateRowColour();
visibleEnd = wxMax(linesPerPage, visibleTo);
}
else
{
visibleEnd = visibleTo;
}
wxRect rectLine;
int xOrig = dc.LogicalToDeviceX( 0 );
int yOrig = dc.LogicalToDeviceY( 0 );
// tell the caller cache to cache the data
if ( IsVirtual() )
{
wxListEvent evCache(wxEVT_LIST_CACHE_HINT,
GetParent()->GetId());
evCache.SetEventObject( GetParent() );
evCache.m_oldItemIndex = visibleFrom;
evCache.m_item.m_itemId =
evCache.m_itemIndex = visibleTo;
GetParent()->GetEventHandler()->ProcessEvent( evCache );
}
for ( size_t line = visibleFrom; line <= visibleEnd; line++ )
{
rectLine = GetLineRect(line);
if ( !IsExposed(rectLine.x + xOrig, rectLine.y + yOrig,
rectLine.width, rectLine.height) )
{
// don't redraw unaffected lines to avoid flicker
continue;
}
if ( line > visibleTo )
{
// We only iterate beyond visibleTo when we have to draw the
// odd rows background, so do this if needed.
if ( line % 2 )
{
dc.SetBrush(colAlt);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.DrawRectangle(rectLine);
}
// But don't do anything else, as there is no valid item.
continue;
}
GetLine(line)->DrawInReportMode( &dc,
rectLine,
GetLineHighlightRect(line),
IsHighlighted(line),
line == m_current );
}
if ( HasFlag(wxLC_HRULES) )
{
wxPen pen(GetRuleColour(), 1, wxPENSTYLE_SOLID);
wxSize clientSize = GetClientSize();
size_t i = visibleFrom;
if (i == 0) i = 1; // Don't draw the first one
for ( ; i <= visibleEnd; i++ )
{
dc.SetPen(pen);
dc.SetBrush( *wxTRANSPARENT_BRUSH );
dc.DrawLine(0 - dev_x, i * lineHeight,
clientSize.x - dev_x, i * lineHeight);
}
// Draw last horizontal rule
if ( visibleEnd == GetItemCount() - 1 )
{
dc.SetPen( pen );
dc.SetBrush( *wxTRANSPARENT_BRUSH );
dc.DrawLine(0 - dev_x, (m_lineTo + 1) * lineHeight,
clientSize.x - dev_x , (m_lineTo + 1) * lineHeight );
}
}
// Draw vertical rules if required
if ( HasFlag(wxLC_VRULES) &&
(m_extendRulesAndAlternateColour || !IsEmpty()) )
{
wxPen pen(GetRuleColour(), 1, wxPENSTYLE_SOLID);
wxRect firstItemRect, lastItemRect;
GetItemRect(visibleFrom, firstItemRect);
GetItemRect(visibleTo, lastItemRect);
int x = firstItemRect.GetX();
dc.SetPen(pen);
dc.SetBrush(* wxTRANSPARENT_BRUSH);
int clientHeight, clientWidth;
GetSize( &clientWidth, &clientHeight );
for (int col = 0; col < GetColumnCount(); col++)
{
int colWidth = GetColumnWidth(col);
x += colWidth;
int x_pos = x - dev_x;
if (col < GetColumnCount()-1) x_pos -= 2;
int ruleHeight = m_extendRulesAndAlternateColour && visibleEnd > visibleTo
? clientHeight
: lastItemRect.GetBottom() + 1 - dev_y;
dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y,
x_pos, ruleHeight);
}
}
}
else // !report
{
size_t count = GetItemCount();
for ( size_t i = 0; i < count; i++ )
{
GetLine(i)->Draw( &dc, i == m_current );
}
}
// DrawFocusRect() is unusable under Mac, it draws outside of the highlight
// rectangle somehow and so leaves traces when the item is not selected any
// more, see #12229.
#ifndef __WXMAC__
if ( HasCurrent() )
{
int flags = 0;
if ( IsHighlighted(m_current) )
flags |= wxCONTROL_SELECTED;
wxRendererNative::Get().
DrawFocusRect(this, dc, GetLineHighlightRect(m_current), flags);
}
#endif // !__WXMAC__
}
void wxListMainWindow::HighlightAll( bool on )
{
if ( IsSingleSel() )
{
wxASSERT_MSG( !on, wxT("can't do this in a single selection control") );
// we just have one item to turn off
if ( HasCurrent() && IsHighlighted(m_current) )
{
HighlightLine(m_current, false);
RefreshLine(m_current);
}
}
else // multi selection
{
if ( !IsEmpty() )
HighlightLines(0, GetItemCount() - 1, on);
}
}
void wxListMainWindow::HighlightOnly( size_t line, size_t oldLine )
{
const unsigned selCount = GetSelectedItemCount();
if ( selCount == 1 && IsHighlighted(line) )
{
return; // Nothing changed.
}
if ( oldLine != (size_t)-1 )
{
IsHighlighted(oldLine) ? ReverseHighlight(oldLine)
: RefreshLine(oldLine); // refresh the old focus to remove it
}
if ( selCount > 1 ) // multiple-selection only
{
// Deselecting many items at once will generate wxEVT_XXX_DESELECTED event
// for each one of them. although this may be inefficient if the number of
// deselected items is too much, we keep doing this (for non-virtual list
// controls) for backward compatibility concerns. For virtual listctrl (in
// multi-selection mode), wxMSW sends only a notification to indicate that
// something has been deselected. Notice that to be fully compatible with
// wxMSW behaviour, _line_ shouldn't be deselected if it was selected.
const SendEvent sendEvent = IsVirtual() ? SendEvent_None : SendEvent_Normal;
size_t lineFrom = 0,
lineTo = GetItemCount() - 1;
if ( line > lineFrom && line < lineTo )
{
HighlightLines(lineFrom, line - 1, false, sendEvent);
HighlightLines(line + 1, lineTo, false, sendEvent);
}
else // _line_ is equal to lineFrom or lineTo
{
line == lineFrom ? ++lineFrom : --lineTo;
HighlightLines(lineFrom, lineTo, false, sendEvent);
}
// If we didn't send the event for individual items above, send it for all of them now.
if ( sendEvent == SendEvent_None )
SendNotify((size_t)-1, wxEVT_LIST_ITEM_DESELECTED);
}
// _line_ should be the only selected item.
HighlightLine(line);
// refresh the new focus to add it.
RefreshLine(line);
}
void wxListMainWindow::OnChildFocus(wxChildFocusEvent& WXUNUSED(event))
{
// Do nothing here. This prevents the default handler in wxScrolledWindow
// from needlessly scrolling the window when the edit control is
// dismissed. See ticket #9563.
}
void wxListMainWindow::SendNotify( size_t line,
wxEventType command,
const wxPoint& point )
{
wxListEvent le( command, GetParent()->GetId() );
le.SetEventObject( GetParent() );
le.m_item.m_itemId =
le.m_itemIndex = line;
// set only for events which have position
if ( point != wxDefaultPosition )
{
// the position should be relative to the parent window, not
// this one for compatibility with MSW and common sense: the
// user code doesn't know anything at all about this window,
// so why should it get positions relative to it?
le.m_pointDrag = GetPosition() + point;
}
// don't try to get the line info for virtual list controls: the main
// program has it anyhow and if we did it would result in accessing all
// the lines, even those which are not visible now and this is precisely
// what we're trying to avoid
if ( !IsVirtual() )
{
if ( line != (size_t)-1 )
{
GetLine(line)->GetItem( 0, le.m_item );
}
//else: this happens for wxEVT_LIST_ITEM_FOCUSED event
}
//else: there may be no more such item
GetParent()->GetEventHandler()->ProcessEvent( le );
}
bool wxListMainWindow::ChangeCurrentWithoutEvent(size_t current)
{
if ( current == m_current )
{
return false; // Nothing changed!
}
m_current = current;
// as the current item changed, we shouldn't start editing it when the
// "slow click" timer expires as the click happened on another item
if ( m_renameTimer->IsRunning() )
m_renameTimer->Stop();
return true;
}
void wxListMainWindow::ChangeCurrent(size_t current)
{
if ( ChangeCurrentWithoutEvent(current) )
SendNotify(current, wxEVT_LIST_ITEM_FOCUSED);
}
wxTextCtrl *wxListMainWindow::EditLabel(long item, wxClassInfo* textControlClass)
{
wxCHECK_MSG( (item >= 0) && ((size_t)item < GetItemCount()), NULL,
wxT("wrong index in wxGenericListCtrl::EditLabel()") );
wxASSERT_MSG( textControlClass->IsKindOf(wxCLASSINFO(wxTextCtrl)),
wxT("EditLabel() needs a text control") );
size_t itemEdit = (size_t)item;
wxListEvent le( wxEVT_LIST_BEGIN_LABEL_EDIT, GetParent()->GetId() );
le.SetEventObject( GetParent() );
le.m_item.m_itemId =
le.m_itemIndex = item;
wxListLineData *data = GetLine(itemEdit);
wxCHECK_MSG( data, NULL, wxT("invalid index in EditLabel()") );
data->GetItem( 0, le.m_item );
if ( GetParent()->GetEventHandler()->ProcessEvent( le ) && !le.IsAllowed() )
{
// vetoed by user code
return NULL;
}
if ( m_dirty )
{
// Ensure the display is updated before we start editing.
Update();
}
wxTextCtrl * const text = (wxTextCtrl *)textControlClass->CreateObject();
m_textctrlWrapper = new wxListTextCtrlWrapper(this, text, item);
return m_textctrlWrapper->GetText();
}
bool wxListMainWindow::EndEditLabel(bool cancel)
{
if (!m_textctrlWrapper)
{
return false;
}
m_textctrlWrapper->EndEdit(cancel ? wxListTextCtrlWrapper::End_Discard : wxListTextCtrlWrapper::End_Accept);
return true;
}
void wxListMainWindow::OnRenameTimer()
{
wxCHECK_RET( HasCurrent(), wxT("unexpected rename timer") );
EditLabel( m_current );
}
bool wxListMainWindow::OnRenameAccept(size_t itemEdit, const wxString& value)
{
wxListEvent le( wxEVT_LIST_END_LABEL_EDIT, GetParent()->GetId() );
le.SetEventObject( GetParent() );
le.m_item.m_itemId =
le.m_itemIndex = itemEdit;
wxListLineData *data = GetLine(itemEdit);
wxCHECK_MSG( data, false, wxT("invalid index in OnRenameAccept()") );
data->GetItem( 0, le.m_item );
le.m_item.m_text = value;
return !GetParent()->GetEventHandler()->ProcessEvent( le ) ||
le.IsAllowed();
}
void wxListMainWindow::OnRenameCancelled(size_t itemEdit)
{
// let owner know that the edit was cancelled
wxListEvent le( wxEVT_LIST_END_LABEL_EDIT, GetParent()->GetId() );
le.SetEditCanceled(true);
le.SetEventObject( GetParent() );
le.m_item.m_itemId =
le.m_itemIndex = itemEdit;
wxListLineData *data = GetLine(itemEdit);
wxCHECK_RET( data, wxT("invalid index in OnRenameCancelled()") );
data->GetItem( 0, le.m_item );
GetEventHandler()->ProcessEvent( le );
}
void wxListMainWindow::OnFindTimer()
{
m_findPrefix.clear();
if ( m_findBell )
m_findBell = 1;
}
void wxListMainWindow::EnableBellOnNoMatch( bool on )
{
m_findBell = on;
}
void wxListMainWindow::OnMouse( wxMouseEvent &event )
{
#ifdef __WXMAC__
// On wxMac we can't depend on the EVT_KILL_FOCUS event to properly
// shutdown the edit control when the mouse is clicked elsewhere on the
// listctrl because the order of events is different (or something like
// that), so explicitly end the edit if it is active.
if ( event.LeftDown() && m_textctrlWrapper )
m_textctrlWrapper->EndEdit(wxListTextCtrlWrapper::End_Accept);
#endif // __WXMAC__
if ( event.LeftDown() )
{
// Ensure we skip the event to let the system set focus to this window.
event.Skip();
}
// Pretend that the event happened in wxListCtrl itself.
wxMouseEvent me(event);
me.SetEventObject( GetParent() );
me.SetId(GetParent()->GetId());
if ( GetParent()->GetEventHandler()->ProcessEvent( me ))
return;
if (event.GetEventType() == wxEVT_MOUSEWHEEL)
{
// let the base class handle mouse wheel events.
event.Skip();
return;
}
if ( !HasCurrent() || IsEmpty() )
{
if (event.RightDown())
{
SendNotify( (size_t)-1, wxEVT_LIST_ITEM_RIGHT_CLICK, event.GetPosition() );
wxContextMenuEvent evtCtx(wxEVT_CONTEXT_MENU,
GetParent()->GetId(),
ClientToScreen(event.GetPosition()));
evtCtx.SetEventObject(GetParent());
GetParent()->GetEventHandler()->ProcessEvent(evtCtx);
}
if ( IsEmpty() )
return;
// Continue processing...
}
if (m_dirty)
return;
if ( !(event.Dragging() || event.ButtonDown() || event.LeftUp() ||
event.ButtonDClick()) )
return;
int x = event.GetX();
int y = event.GetY();
GetListCtrl()->CalcUnscrolledPosition( x, y, &x, &y );
// where did we hit it (if we did)?
long hitResult = 0;
size_t count = GetItemCount(),
current;
if ( InReportView() )
{
current = y / GetLineHeight();
if ( current < count )
hitResult = HitTestLine(current, x, y);
}
else // !report
{
// TODO: optimize it too! this is less simple than for report view but
// enumerating all items is still not a way to do it!!
for ( current = 0; current < count; current++ )
{
hitResult = HitTestLine(current, x, y);
if ( hitResult )
break;
}
}
// Update drag events counter first as we must do it even if the mouse is
// not on any item right now as we must keep count in case we started
// dragging from the empty control area but continued to do it over a valid
// item -- in this situation we must not start dragging this item.
if (event.Dragging())
m_dragCount++;
else
m_dragCount = 0;
// The only mouse events that can be generated without any valid item are
// wxEVT_LIST_ITEM_DESELECTED for virtual lists, and
// wxEVT_LIST_ITEM_RIGHT_CLICK as it can be useful to have a global
// popup menu for the list control itself which should be shown even when
// the user clicks outside of any item.
if ( !hitResult )
{
// outside of any item
if (event.RightDown())
{
wxContextMenuEvent evtCtx(
wxEVT_CONTEXT_MENU,
GetParent()->GetId(),
ClientToScreen(event.GetPosition()));
evtCtx.SetEventObject(GetParent());
GetParent()->GetEventHandler()->ProcessEvent(evtCtx);
}
else if (event.LeftDown())
{
// reset the selection and bail out
HighlightAll(false);
// generate a DESELECTED event for
// virtual multi-selection lists
if ( IsVirtual() && !IsSingleSel() )
SendNotify( m_lineLastClicked, wxEVT_LIST_ITEM_DESELECTED );
}
return;
}
if ( event.Dragging() )
{
if (m_dragCount == 1)
{
// we have to report the raw, physical coords as we want to be
// able to call HitTest(event.m_pointDrag) from the user code to
// get the item being dragged
m_dragStart = event.GetPosition();
}
if (m_dragCount != 3)
return;
int command = event.RightIsDown() ? wxEVT_LIST_BEGIN_RDRAG
: wxEVT_LIST_BEGIN_DRAG;
SendNotify( m_lineLastClicked, command, m_dragStart );
return;
}
bool forceClick = false;
if (event.ButtonDClick())
{
if ( m_renameTimer->IsRunning() )
m_renameTimer->Stop();
m_lastOnSame = false;
if ( current == m_lineLastClicked )
{
SendNotify( current, wxEVT_LIST_ITEM_ACTIVATED );
return;
}
else
{
// The first click was on another item, so don't interpret this as
// a double click, but as a simple click instead
forceClick = true;
}
}
if (event.LeftUp())
{
if (m_lineSelectSingleOnUp != (size_t)-1)
{
// select single line
HighlightOnly(m_lineSelectSingleOnUp);
}
if (m_lastOnSame)
{
if ((current == m_current) &&
(hitResult == wxLIST_HITTEST_ONITEMLABEL) &&
HasFlag(wxLC_EDIT_LABELS) )
{
if ( !InReportView() ||
GetLineLabelRect(current).Contains(x, y) )
{
int dclick = wxSystemSettings::GetMetric(wxSYS_DCLICK_MSEC);
m_renameTimer->Start(dclick > 0 ? dclick : 250, true);
}
}
m_lastOnSame = false;
}
if ( GetSelectedItemCount() == 1 || event.CmdDown() )
{
// In multiple selection mode, the anchor is set to the first selected
// item or can be changed to m_current if Ctrl key is down, as is the
// case under wxMSW.
m_anchor = m_current;
}
m_lineSelectSingleOnUp = (size_t)-1;
}
else
{
// This is necessary, because after a DnD operation in
// from and to ourself, the up event is swallowed by the
// DnD code. So on next non-up event (which means here and
// now) m_lineSelectSingleOnUp should be reset.
m_lineSelectSingleOnUp = (size_t)-1;
}
if (event.RightDown())
{
m_lineBeforeLastClicked = m_lineLastClicked;
m_lineLastClicked = current;
// If the item is already selected, do not update the selection.
// Multi-selections should not be cleared if a selected item is clicked.
if (!IsHighlighted(current))
{
ChangeCurrent(current);
HighlightOnly(m_current);
}
SendNotify( current, wxEVT_LIST_ITEM_RIGHT_CLICK, event.GetPosition() );
// Allow generation of context menu event
event.Skip();
}
else if (event.MiddleDown())
{
SendNotify( current, wxEVT_LIST_ITEM_MIDDLE_CLICK );
}
else if ( event.LeftDown() || forceClick )
{
m_lineBeforeLastClicked = m_lineLastClicked;
m_lineLastClicked = current;
size_t oldCurrent = m_current;
bool oldWasSelected = HasCurrent() && IsHighlighted(m_current);
bool cmdModifierDown = event.CmdDown();
if ( IsSingleSel() || !(cmdModifierDown || event.ShiftDown()) )
{
if (IsInsideCheckBox(current, x, y))
{
CheckItem(current, !IsItemChecked(current));
}
else if (IsSingleSel() || !IsHighlighted(current))
{
ChangeCurrent(current);
HighlightOnly(m_current, oldWasSelected ? oldCurrent : (size_t)-1);
}
else // multi sel & current is highlighted & no mod keys
{
m_lineSelectSingleOnUp = current;
ChangeCurrent(current); // change focus
}
}
else // multi sel & either ctrl or shift is down
{
if (cmdModifierDown)
{
ChangeCurrent(current);
ReverseHighlight(m_current);
}
else if (event.ShiftDown())
{
ChangeCurrent(current);
if ( oldCurrent == (size_t)-1 )
{
// Highlight m_current only if there is no previous selection.
HighlightLine(m_current);
}
else if ( oldCurrent != current && m_anchor != (size_t)-1 )
{
ExtendSelection(oldCurrent, current);
}
}
else // !ctrl, !shift
{
// test in the enclosing if should make it impossible
wxFAIL_MSG( wxT("how did we get here?") );
}
}
if (m_current != oldCurrent && oldCurrent != (size_t)-1)
RefreshLine( oldCurrent );
// Set the flag telling us whether the next click on this item should
// start editing its label. This should happen if we clicked on the
// current item and it was already selected, i.e. if this click was not
// done to select it.
//
// It should not happen if this was a double click (forceClick is true)
// nor if we hadn't had the focus before as then this click was used to
// give focus to the control.
m_lastOnSame = (m_current == oldCurrent) && oldWasSelected &&
!forceClick && HasFocus();
}
}
void wxListMainWindow::MoveToItem(size_t item)
{
if ( item == (size_t)-1 )
return;
wxRect rect = GetLineRect(item);
int client_w, client_h;
GetClientSize( &client_w, &client_h );
const int hLine = GetLineHeight();
int view_x = SCROLL_UNIT_X * GetListCtrl()->GetScrollPos( wxHORIZONTAL );
int view_y = hLine * GetListCtrl()->GetScrollPos( wxVERTICAL );
if ( InReportView() )
{
// the next we need the range of lines shown it might be different,
// so recalculate it
ResetVisibleLinesRange();
if (rect.y < view_y)
GetListCtrl()->Scroll( -1, rect.y / hLine );
if (rect.y + rect.height + 5 > view_y + client_h)
GetListCtrl()->Scroll( -1, (rect.y + rect.height - client_h + hLine) / hLine );
#if defined(__WXMAC__) || defined(__WXUNIVERSAL__)
// At least on Mac the visible lines value will get reset inside of
// Scroll *before* it actually scrolls the window because of the
// Update() that happens there, so it will still have the wrong value.
// So let's reset it again and wait for it to be recalculated in the
// next paint event. I would expect this problem to show up in wxGTK
// too but couldn't duplicate it there. Perhaps the order of events
// is different... --Robin
// Same in wxUniv/X11
ResetVisibleLinesRange();
#endif
}
else // !report
{
int sx = -1,
sy = -1;
if (rect.x-view_x < 5)
sx = (rect.x - 5) / SCROLL_UNIT_X;
if (rect.x + rect.width - 5 > view_x + client_w)
sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X) / SCROLL_UNIT_X;
if (rect.y-view_y < 5)
sy = (rect.y - 5) / hLine;
if (rect.y + rect.height - 5 > view_y + client_h)
sy = (rect.y + rect.height - client_h + hLine) / hLine;
GetListCtrl()->Scroll(sx, sy);
}
}
bool wxListMainWindow::ScrollList(int WXUNUSED(dx), int dy)
{
if ( !InReportView() )
{
// TODO: this should work in all views but is not implemented now
return false;
}
size_t top, bottom;
GetVisibleLinesRange(&top, &bottom);
if ( bottom == (size_t)-1 )
return 0;
ResetVisibleLinesRange();
int hLine = GetLineHeight();
GetListCtrl()->Scroll(-1, top + dy / hLine);
#if defined(__WXMAC__) || defined(__WXUNIVERSAL__)
// see comment in MoveToItem() for why we do this
ResetVisibleLinesRange();
#endif
return true;
}
// ----------------------------------------------------------------------------
// keyboard handling
// ----------------------------------------------------------------------------
// Helper function which handles items selection correctly and efficiently. and
// simply, mimic the wxMSW behaviour. And The benefit of this function is that it
// ensures that wxEVT_LIST_ITEM_{DE}SELECTED events are only generated for items
// freshly (de)selected (i.e. items that have really changed state). Useful for
// multi-selection mode when selecting using mouse or arrows with Shift key down.
void wxListMainWindow::ExtendSelection(size_t oldCurrent, size_t newCurrent)
{
// Refresh the old/new focus to remove/add it
RefreshLine(oldCurrent);
RefreshLine(newCurrent);
// Given a selection [anchor, old], to change/extend it to new (i.e. the
// selection becomes [anchor, new]) we discriminate three possible cases:
//
// Case 1) new < old <= anchor || anchor <= old < new
// i.e. oldCurrent between anchor and newCurrent, in which case we:
// - Highlight everything between anchor and newCurrent (inclusive).
//
// Case 2) old < new <= anchor || anchor <= new < old
// i.e. newCurrent between anchor and oldCurrent, in which case we:
// - Unhighlight everything between oldCurrent and newCurrent (exclusive).
//
// Case 3) old < anchor < new || new < anchor < old
// i.e. anchor between oldCurrent and newCurrent, in which case we
// - Highlight everything between anchor and newCurrent (inclusive).
// - Unhighlight everything between anchor (exclusive) and oldCurrent.
size_t lineFrom, lineTo;
if ( (newCurrent < oldCurrent && oldCurrent <= m_anchor) ||
(newCurrent > oldCurrent && oldCurrent >= m_anchor) )
{
lineFrom = m_anchor;
lineTo = newCurrent;
HighlightLines(lineFrom, lineTo);
}
else if ( (oldCurrent < newCurrent && newCurrent <= m_anchor) ||
(oldCurrent > newCurrent && newCurrent >= m_anchor) )
{
lineFrom = oldCurrent;
lineTo = newCurrent;
// Exclude newCurrent from being deselected
(lineTo < lineFrom) ? ++lineTo : --lineTo;
HighlightLines(lineFrom, lineTo, false);
// For virtual listctrl (in multi-selection mode), wxMSW sends only
// a notification to indicate that something has been deselected.
if ( IsVirtual() )
SendNotify((size_t)-1, wxEVT_LIST_ITEM_DESELECTED);
}
else if ( (oldCurrent < m_anchor && m_anchor < newCurrent) ||
(newCurrent < m_anchor && m_anchor < oldCurrent) )
{
lineFrom = m_anchor;
lineTo = oldCurrent;
// Exclude anchor from being deselected
(lineTo < lineFrom) ? --lineFrom : ++lineFrom;
HighlightLines(lineFrom, lineTo, false);
// See above.
if ( IsVirtual() )
SendNotify((size_t)-1, wxEVT_LIST_ITEM_DESELECTED);
lineFrom = m_anchor;
lineTo = newCurrent;
HighlightLines(lineFrom, lineTo);
}
}
void wxListMainWindow::OnArrowChar(size_t newCurrent, const wxKeyEvent& event)
{
wxCHECK_RET( newCurrent < (size_t)GetItemCount(),
wxT("invalid item index in OnArrowChar()") );
size_t oldCurrent = m_current;
ChangeCurrent(newCurrent);
// in single selection we just ignore Shift as we can't select several
// items anyhow
if ( event.ShiftDown() && !IsSingleSel() )
{
ExtendSelection(oldCurrent, newCurrent);
}
else // !shift
{
// all previously selected items are unselected unless ctrl is held in
// a multi-selection control. in single selection mode we must always
// have a selected item.
if ( !event.ControlDown() || IsSingleSel() )
{
HighlightOnly(m_current, oldCurrent);
// Update anchor
m_anchor = m_current;
}
else
{
// refresh the old/new focus to remove/add it
RefreshLine(oldCurrent);
RefreshLine(m_current);
}
}
MoveToFocus();
}
void wxListMainWindow::OnKeyDown( wxKeyEvent &event )
{
wxWindow *parent = GetParent();
// propagate the key event upwards
wxKeyEvent ke(event);
ke.SetEventObject( parent );
ke.SetId(GetParent()->GetId());
if (parent->GetEventHandler()->ProcessEvent( ke ))
return;
// send a list event
wxListEvent le( wxEVT_LIST_KEY_DOWN, parent->GetId() );
const size_t current = ShouldSendEventForCurrent() ? m_current : (size_t)-1;
le.m_item.m_itemId =
le.m_itemIndex = current;
if ( current != (size_t)-1 )
GetLine(current)->GetItem( 0, le.m_item );
le.m_code = event.GetKeyCode();
le.SetEventObject( parent );
if (parent->GetEventHandler()->ProcessEvent( le ))
return;
event.Skip();
}
void wxListMainWindow::OnKeyUp( wxKeyEvent &event )
{
wxWindow *parent = GetParent();
// propagate the key event upwards
wxKeyEvent ke(event);
ke.SetEventObject( parent );
ke.SetId(GetParent()->GetId());
if (parent->GetEventHandler()->ProcessEvent( ke ))
return;
event.Skip();
}
void wxListMainWindow::OnCharHook( wxKeyEvent &event )
{
if ( m_textctrlWrapper )
{
// When an in-place editor is active we should ensure that it always
// gets the key events that are special to it.
if ( m_textctrlWrapper->CheckForEndEditKey(event) )
{
// Skip the call to wxEvent::Skip() below.
return;
}
}
event.Skip();
}
void wxListMainWindow::OnChar( wxKeyEvent &event )
{
wxWindow *parent = GetParent();
// propagate the char event upwards
wxKeyEvent ke(event);
ke.SetEventObject( parent );
ke.SetId(GetParent()->GetId());
if (parent->GetEventHandler()->ProcessEvent( ke ))
return;
if ( HandleAsNavigationKey(event) )
return;
// no item -> nothing to do
if (!HasCurrent())
{
event.Skip();
return;
}
// don't use m_linesPerPage directly as it might not be computed yet
const int pageSize = GetCountPerPage();
wxCHECK_RET( pageSize, wxT("should have non zero page size") );
if (GetLayoutDirection() == wxLayout_RightToLeft)
{
if (event.GetKeyCode() == WXK_RIGHT)
event.m_keyCode = WXK_LEFT;
else if (event.GetKeyCode() == WXK_LEFT)
event.m_keyCode = WXK_RIGHT;
}
int keyCode = event.GetKeyCode();
switch ( keyCode )
{
case WXK_UP:
if ( m_current > 0 )
OnArrowChar( m_current - 1, event );
break;
case WXK_DOWN:
if ( m_current < (size_t)GetItemCount() - 1 )
OnArrowChar( m_current + 1, event );
break;
case WXK_END:
if (!IsEmpty())
OnArrowChar( GetItemCount() - 1, event );
break;
case WXK_HOME:
if (!IsEmpty())
OnArrowChar( 0, event );
break;
case WXK_PAGEUP:
{
int steps = InReportView() ? pageSize - 1
: m_current % pageSize;
int index = m_current - steps;
if (index < 0)
index = 0;
OnArrowChar( index, event );
}
break;
case WXK_PAGEDOWN:
{
int steps = InReportView()
? pageSize - 1
: pageSize - (m_current % pageSize) - 1;
size_t index = m_current + steps;
size_t count = GetItemCount();
if ( index >= count )
index = count - 1;
OnArrowChar( index, event );
}
break;
case WXK_LEFT:
if ( !InReportView() )
{
int index = m_current - pageSize;
if (index < 0)
index = 0;
OnArrowChar( index, event );
}
break;
case WXK_RIGHT:
if ( !InReportView() )
{
size_t index = m_current + pageSize;
size_t count = GetItemCount();
if ( index >= count )
index = count - 1;
OnArrowChar( index, event );
}
break;
case WXK_SPACE:
if ( IsSingleSel() )
{
if ( event.ControlDown() )
{
ReverseHighlight(m_current);
}
else if ( ShouldSendEventForCurrent() ) // normal space press
{
SendNotify( m_current, wxEVT_LIST_ITEM_ACTIVATED );
}
}
else // multiple selection
{
ReverseHighlight(m_current);
}
break;
case WXK_RETURN:
case WXK_EXECUTE:
if ( event.HasModifiers() || !ShouldSendEventForCurrent() )
{
event.Skip();
break;
}
SendNotify( m_current, wxEVT_LIST_ITEM_ACTIVATED );
break;
default:
if ( !event.HasModifiers() &&
((keyCode >= '0' && keyCode <= '9') ||
(keyCode >= 'a' && keyCode <= 'z') ||
(keyCode >= 'A' && keyCode <= 'Z') ||
(keyCode == '_') ||
(keyCode == '+') ||
(keyCode == '*') ||
(keyCode == '-')))
{
// find the next item starting with the given prefix
wxChar ch = (wxChar)keyCode;
size_t item;
// if the same character is typed multiple times then go to the
// next entry starting with that character instead of searching
// for an item starting with multiple copies of this character,
// this is more useful and is how it works under Windows.
if ( m_findPrefix.length() == 1 && m_findPrefix[0] == ch )
{
item = PrefixFindItem(m_current, ch);
}
else
{
const wxString newPrefix(m_findPrefix + ch);
item = PrefixFindItem(m_current, newPrefix);
if ( item != (size_t)-1 )
m_findPrefix = newPrefix;
}
// also start the timer to reset the current prefix if the user
// doesn't press any more alnum keys soon -- we wouldn't want
// to use this prefix for a new item search
if ( !m_findTimer )
{
m_findTimer = new wxListFindTimer( this );
}
// Notice that we should start the timer even if we didn't find
// anything to make sure we reset the search state later.
m_findTimer->Start(wxListFindTimer::DELAY, wxTIMER_ONE_SHOT);
// restart timer even when there's no match so bell get's reset
if ( item != (size_t)-1 )
{
// Select the found item and go to it.
HighlightAll(false);
SetItemState(item,
wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED,
wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED);
EnsureVisible(item);
// Reset the bell flag if it had been temporarily disabled
// before.
if ( m_findBell )
m_findBell = 1;
}
else // No such item
{
// Signal it with a bell if enabled.
if ( m_findBell == 1 )
{
::wxBell();
// Disable it for the next unsuccessful match, we only
// beep once, this is usually enough and continuing to
// do it would be annoying.
m_findBell = -1;
}
}
}
else
{
event.Skip();
}
}
}
// ----------------------------------------------------------------------------
// focus handling
// ----------------------------------------------------------------------------
void wxListMainWindow::OnSetFocus( wxFocusEvent &WXUNUSED(event) )
{
if ( GetParent() )
{
wxFocusEvent event( wxEVT_SET_FOCUS, GetParent()->GetId() );
event.SetEventObject( GetParent() );
if ( GetParent()->GetEventHandler()->ProcessEvent( event) )
return;
}
// wxGTK sends us EVT_SET_FOCUS events even if we had never got
// EVT_KILL_FOCUS before which means that we finish by redrawing the items
// which are already drawn correctly resulting in horrible flicker - avoid
// it
if ( !m_hasFocus )
{
m_hasFocus = true;
UpdateCurrent();
RefreshSelected();
}
}
void wxListMainWindow::OnKillFocus( wxFocusEvent &WXUNUSED(event) )
{
if ( GetParent() )
{
wxFocusEvent event( wxEVT_KILL_FOCUS, GetParent()->GetId() );
event.SetEventObject( GetParent() );
if ( GetParent()->GetEventHandler()->ProcessEvent( event) )
return;
}
m_hasFocus = false;
RefreshSelected();
}
void wxListMainWindow::DrawImage( int index, wxDC *dc, int x, int y )
{
if ( HasFlag(wxLC_ICON) && (m_normal_image_list))
{
m_normal_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
}
else if ( HasFlag(wxLC_SMALL_ICON) && (m_small_image_list))
{
m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
}
else if ( HasFlag(wxLC_LIST) && (m_small_image_list))
{
m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
}
else if ( InReportView() && (m_small_image_list))
{
m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
}
}
void wxListMainWindow::GetImageSize( int index, int &width, int &height ) const
{
if ( HasFlag(wxLC_ICON) && m_normal_image_list )
{
m_normal_image_list->GetSize( index, width, height );
}
else if ( HasFlag(wxLC_SMALL_ICON) && m_small_image_list )
{
m_small_image_list->GetSize( index, width, height );
}
else if ( HasFlag(wxLC_LIST) && m_small_image_list )
{
m_small_image_list->GetSize( index, width, height );
}
else if ( InReportView() && m_small_image_list )
{
m_small_image_list->GetSize( index, width, height );
}
else
{
width =
height = 0;
}
}
void wxListMainWindow::SetImageList( wxImageList *imageList, int which )
{
m_dirty = true;
// calc the spacing from the icon size
int width = 0;
if ((imageList) && (imageList->GetImageCount()) )
{
int height;
imageList->GetSize(0, width, height);
}
if (which == wxIMAGE_LIST_NORMAL)
{
m_normal_image_list = imageList;
m_normal_spacing = width + 8;
}
if (which == wxIMAGE_LIST_SMALL)
{
m_small_image_list = imageList;
m_small_spacing = width + 14;
m_lineHeight = 0; // ensure that the line height will be recalc'd
}
}
void wxListMainWindow::SetItemSpacing( int spacing, bool isSmall )
{
m_dirty = true;
if (isSmall)
m_small_spacing = spacing;
else
m_normal_spacing = spacing;
}
int wxListMainWindow::GetItemSpacing( bool isSmall )
{
return isSmall ? m_small_spacing : m_normal_spacing;
}
// ----------------------------------------------------------------------------
// columns
// ----------------------------------------------------------------------------
int
wxListMainWindow::ComputeMinHeaderWidth(const wxListHeaderData* column) const
{
wxClientDC dc(const_cast<wxListMainWindow*>(this));
int width = dc.GetTextExtent(column->GetText()).x + AUTOSIZE_COL_MARGIN;
width += 2*EXTRA_WIDTH;
// check for column header's image availability
const int image = column->GetImage();
if ( image != -1 )
{
if ( m_small_image_list )
{
int ix = 0, iy = 0;
m_small_image_list->GetSize(image, ix, iy);
width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE;
}
}
return width;
}
void wxListMainWindow::SetColumn( int col, const wxListItem &item )
{
wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
wxCHECK_RET( node, wxT("invalid column index in SetColumn") );
wxListHeaderData *column = node->GetData();
column->SetItem( item );
if ( item.m_width == wxLIST_AUTOSIZE_USEHEADER )
column->SetWidth(ComputeMinHeaderWidth(column));
wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
if ( headerWin )
headerWin->m_dirty = true;
m_dirty = true;
// invalidate it as it has to be recalculated
m_headerWidth = 0;
}
class wxListCtrlMaxWidthCalculator : public wxMaxWidthCalculatorBase
{
public:
wxListCtrlMaxWidthCalculator(wxListMainWindow *listmain, unsigned int column)
: wxMaxWidthCalculatorBase(column),
m_listmain(listmain)
{
}
virtual void UpdateWithRow(int row) wxOVERRIDE
{
wxListLineData *line = m_listmain->GetLine( row );
wxListItemDataList::compatibility_iterator n = line->m_items.Item( GetColumn() );
wxCHECK_RET( n, wxS("no subitem?") );
wxListItemData* const itemData = n->GetData();
wxListItem item;
itemData->GetItem(item);
UpdateWithWidth(m_listmain->GetItemWidthWithImage(&item));
}
private:
wxListMainWindow* const m_listmain;
};
void wxListMainWindow::SetColumnWidth( int col, int width )
{
wxCHECK_RET( col >= 0 && col < GetColumnCount(),
wxT("invalid column index") );
wxCHECK_RET( InReportView(),
wxT("SetColumnWidth() can only be called in report mode.") );
m_dirty = true;
wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
if ( headerWin )
headerWin->m_dirty = true;
wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
wxCHECK_RET( node, wxT("no column?") );
wxListHeaderData *column = node->GetData();
if ( width == wxLIST_AUTOSIZE_USEHEADER || width == wxLIST_AUTOSIZE )
{
wxListCtrlMaxWidthCalculator calculator(this, col);
calculator.UpdateWithWidth(AUTOSIZE_COL_MARGIN);
if ( width == wxLIST_AUTOSIZE_USEHEADER )
calculator.UpdateWithWidth(ComputeMinHeaderWidth(column));
// if the cached column width isn't valid then recalculate it
wxColWidthInfo* const pWidthInfo = m_aColWidths.Item(col);
if ( pWidthInfo->bNeedsUpdate )
{
size_t first_visible, last_visible;
GetVisibleLinesRange(&first_visible, &last_visible);
calculator.ComputeBestColumnWidth(GetItemCount(),
first_visible, last_visible);
pWidthInfo->nMaxWidth = calculator.GetMaxWidth();
pWidthInfo->bNeedsUpdate = false;
}
else
{
calculator.UpdateWithWidth(pWidthInfo->nMaxWidth);
}
width = calculator.GetMaxWidth() + AUTOSIZE_COL_MARGIN;
if ( col == 0 && HasCheckBoxes() )
{
// also account for the space needed by the checkbox
width += wxRendererNative::Get().GetCheckBoxSize(this).x
+ 2*MARGIN_AROUND_CHECKBOX;
}
// expand the last column to fit the client size
// only for AUTOSIZE_USEHEADER to mimic MSW behaviour
if ( (width == wxLIST_AUTOSIZE_USEHEADER) && (col == GetColumnCount() - 1) )
{
int margin = GetClientSize().GetX();
for ( int i = 0; i < col && margin > 0; ++i )
margin -= m_columns.Item(i)->GetData()->GetWidth();
if ( margin > width )
width = margin;
}
}
column->SetWidth( width );
// invalidate it as it has to be recalculated
m_headerWidth = 0;
}
int wxListMainWindow::GetHeaderWidth() const
{
if ( !m_headerWidth )
{
wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
size_t count = GetColumnCount();
for ( size_t col = 0; col < count; col++ )
{
self->m_headerWidth += GetColumnWidth(col);
}
}
return m_headerWidth;
}
void wxListMainWindow::GetColumn( int col, wxListItem &item ) const
{
wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
wxCHECK_RET( node, wxT("invalid column index in GetColumn") );
wxListHeaderData *column = node->GetData();
column->GetItem( item );
}
int wxListMainWindow::GetColumnWidth( int col ) const
{
wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
wxCHECK_MSG( node, 0, wxT("invalid column index") );
wxListHeaderData *column = node->GetData();
return column->GetWidth();
}
// ----------------------------------------------------------------------------
// item state
// ----------------------------------------------------------------------------
void wxListMainWindow::SetItem( wxListItem &item )
{
long id = item.m_itemId;
wxCHECK_RET( id >= 0 && (size_t)id < GetItemCount(),
wxT("invalid item index in SetItem") );
if ( !IsVirtual() )
{
wxListLineData *line = GetLine((size_t)id);
line->SetItem( item.m_col, item );
// Set item state if user wants
if ( item.m_mask & wxLIST_MASK_STATE )
SetItemState( item.m_itemId, item.m_state, item.m_state );
if (InReportView())
{
// update the Max Width Cache if needed
int width = GetItemWidthWithImage(&item);
wxColWidthInfo* const pWidthInfo = m_aColWidths.Item(item.m_col);
if ( width > pWidthInfo->nMaxWidth )
{
pWidthInfo->nMaxWidth = width;
pWidthInfo->bNeedsUpdate = true;
}
}
}
// update the item on screen unless we're going to update everything soon
// anyhow
if ( !m_dirty )
{
wxRect rectItem;
GetItemRect(id, rectItem);
RefreshRect(rectItem);
}
}
void wxListMainWindow::SetItemStateAll(long state, long stateMask)
{
if ( IsEmpty() )
return;
// first deal with selection
if ( stateMask & wxLIST_STATE_SELECTED )
{
// set/clear select state
if ( IsVirtual() )
{
// optimized version for virtual listctrl.
m_selStore.SelectRange(0, GetItemCount() - 1, state == wxLIST_STATE_SELECTED);
Refresh();
}
else if ( state & wxLIST_STATE_SELECTED )
{
const long count = GetItemCount();
for( long i = 0; i < count; i++ )
{
SetItemState( i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
}
}
else
{
// clear for non virtual (somewhat optimized by using GetNextItem())
long i = -1;
while ( (i = GetNextItem(i, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)) != -1 )
{
SetItemState( i, 0, wxLIST_STATE_SELECTED );
}
}
}
if ( HasCurrent() && (state == 0) && (stateMask & wxLIST_STATE_FOCUSED) )
{
// unfocus all: only one item can be focussed, so clearing focus for
// all items is simply clearing focus of the focussed item.
SetItemState(m_current, state, stateMask);
}
//(setting focus to all items makes no sense, so it is not handled here.)
}
void wxListMainWindow::SetItemState( long litem, long state, long stateMask )
{
if ( litem == -1 )
{
SetItemStateAll(state, stateMask);
return;
}
wxCHECK_RET( litem >= 0 && (size_t)litem < GetItemCount(),
wxT("invalid list ctrl item index in SetItem") );
size_t oldCurrent = m_current;
size_t item = (size_t)litem; // safe because of the check above
// do we need to change the focus?
if ( stateMask & wxLIST_STATE_FOCUSED )
{
if ( state & wxLIST_STATE_FOCUSED )
{
// don't do anything if this item is already focused
if ( item != m_current )
{
ChangeCurrent(item);
if ( oldCurrent != (size_t)-1 )
{
if ( IsSingleSel() )
{
HighlightLine(oldCurrent, false);
}
RefreshLine(oldCurrent);
}
RefreshLine( m_current );
}
}
else // unfocus
{
// don't do anything if this item is not focused
if ( item == m_current )
{
ResetCurrent();
if ( IsSingleSel() )
{
// we must unselect the old current item as well or we
// might end up with more than one selected item in a
// single selection control
HighlightLine(oldCurrent, false);
}
RefreshLine( oldCurrent );
}
}
}
// do we need to change the selection state?
if ( stateMask & wxLIST_STATE_SELECTED )
{
bool on = (state & wxLIST_STATE_SELECTED) != 0;
if ( IsSingleSel() )
{
if ( on )
{
// selecting the item also makes it the focused one in the
// single sel mode
if ( m_current != item )
{
ChangeCurrent(item);
if ( oldCurrent != (size_t)-1 )
{
HighlightLine( oldCurrent, false );
RefreshLine( oldCurrent );
}
}
}
else // off
{
// only the current item may be selected anyhow
if ( item != m_current )
return;
}
}
if ( HighlightLine(item, on) )
{
RefreshLine(item);
}
}
}
int wxListMainWindow::GetItemState( long item, long stateMask ) const
{
wxCHECK_MSG( item >= 0 && (size_t)item < GetItemCount(), 0,
wxT("invalid list ctrl item index in GetItemState()") );
int ret = wxLIST_STATE_DONTCARE;
if ( stateMask & wxLIST_STATE_FOCUSED )
{
if ( (size_t)item == m_current )
ret |= wxLIST_STATE_FOCUSED;
}
if ( stateMask & wxLIST_STATE_SELECTED )
{
if ( IsHighlighted(item) )
ret |= wxLIST_STATE_SELECTED;
}
return ret;
}
void wxListMainWindow::GetItem( wxListItem &item ) const
{
wxCHECK_RET( item.m_itemId >= 0 && (size_t)item.m_itemId < GetItemCount(),
wxT("invalid item index in GetItem") );
wxListLineData *line = GetLine((size_t)item.m_itemId);
line->GetItem( item.m_col, item );
// Get item state if user wants it
if ( item.m_mask & wxLIST_MASK_STATE )
item.m_state = GetItemState( item.m_itemId, wxLIST_STATE_SELECTED |
wxLIST_STATE_FOCUSED );
}
// ----------------------------------------------------------------------------
// item count
// ----------------------------------------------------------------------------
size_t wxListMainWindow::GetItemCount() const
{
return IsVirtual() ? m_countVirt : m_lines.size();
}
void wxListMainWindow::SetItemCount(long count)
{
// Update the current item if it's not valid any longer (notice that this
// invalidates it completely if the control is becoming empty, which is the
// right thing to do).
if ( HasCurrent() && m_current >= (size_t)count )
ChangeCurrent(count - 1);
m_selStore.SetItemCount(count);
m_countVirt = count;
ResetVisibleLinesRange();
// scrollbars must be reset
m_dirty = true;
}
int wxListMainWindow::GetSelectedItemCount() const
{
// deal with the quick case first
if ( IsSingleSel() )
return HasCurrent() ? IsHighlighted(m_current) : false;
// virtual controls remmebers all its selections itself
if ( IsVirtual() )
return m_selStore.GetSelectedCount();
return m_selCount;
}
// ----------------------------------------------------------------------------
// item position/size
// ----------------------------------------------------------------------------
wxRect wxListMainWindow::GetViewRect() const
{
wxASSERT_MSG( !HasFlag(wxLC_LIST), "not implemented for list view" );
// we need to find the longest/tallest label
wxCoord xMax = 0, yMax = 0;
const int count = GetItemCount();
if ( count )
{
for ( int i = 0; i < count; i++ )
{
// we need logical, not physical, coordinates here, so use
// GetLineRect() instead of GetItemRect()
wxRect r = GetLineRect(i);
wxCoord x = r.GetRight(),
y = r.GetBottom();
if ( x > xMax )
xMax = x;
if ( y > yMax )
yMax = y;
}
}
// some fudge needed to make it look prettier
xMax += 2 * EXTRA_BORDER_X;
yMax += 2 * EXTRA_BORDER_Y;
// account for the scrollbars if necessary
const wxSize sizeAll = GetClientSize();
if ( xMax > sizeAll.x )
yMax += wxSystemSettings::GetMetric(wxSYS_HSCROLL_Y);
if ( yMax > sizeAll.y )
xMax += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
return wxRect(0, 0, xMax, yMax);
}
bool
wxListMainWindow::GetSubItemRect(long item, long subItem, wxRect& rect,
int code) const
{
wxCHECK_MSG( subItem == wxLIST_GETSUBITEMRECT_WHOLEITEM || InReportView(),
false,
wxT("GetSubItemRect only meaningful in report view") );
wxCHECK_MSG( item >= 0 && (size_t)item < GetItemCount(), false,
wxT("invalid item in GetSubItemRect") );
// ensure that we're laid out, otherwise we could return nonsense
if ( m_dirty )
{
wxConstCast(this, wxListMainWindow)->
RecalculatePositions(true /* no refresh */);
}
rect = GetLineRect((size_t)item);
// Adjust rect to specified column
if ( subItem != wxLIST_GETSUBITEMRECT_WHOLEITEM )
{
wxCHECK_MSG( subItem >= 0 && subItem < GetColumnCount(), false,
wxT("invalid subItem in GetSubItemRect") );
for (int i = 0; i < subItem; i++)
{
rect.x += GetColumnWidth(i);
}
rect.width = GetColumnWidth(subItem);
switch ( code )
{
case wxLIST_RECT_BOUNDS:
// Nothing to do.
break;
case wxLIST_RECT_ICON:
case wxLIST_RECT_LABEL:
// Note: this needs to be kept in sync with DrawInReportMode().
{
rect.x += ICON_OFFSET_X;
rect.width -= ICON_OFFSET_X;
wxListLineData* const line = GetLine(item);
if ( subItem == 0 && line->HasImage() )
{
int ix, iy;
GetImageSize(line->GetImage(), ix, iy);
const int iconWidth = ix + IMAGE_MARGIN_IN_REPORT_MODE;
if ( code == wxLIST_RECT_ICON )
{
rect.width = iconWidth;
}
else // wxLIST_RECT_LABEL
{
rect.x += iconWidth;
rect.width -= iconWidth;
}
}
else // No icon
{
if ( code == wxLIST_RECT_ICON )
rect = wxRect();
//else: label rect is the same as the full one
}
}
break;
default:
wxFAIL_MSG(wxS("Unknown rectangle requested"));
return false;
}
}
GetListCtrl()->CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y);
return true;
}
bool wxListMainWindow::GetItemPosition(long item, wxPoint& pos) const
{
wxRect rect;
GetItemRect(item, rect);
pos.x = rect.x;
pos.y = rect.y;
return true;
}
// ----------------------------------------------------------------------------
// checkboxes
// ----------------------------------------------------------------------------
bool wxListMainWindow::HasCheckBoxes() const
{
return m_hasCheckBoxes;
}
bool wxListMainWindow::EnableCheckBoxes(bool enable)
{
m_hasCheckBoxes = enable;
m_dirty = true;
m_headerWidth = 0;
Refresh();
return true;
}
void wxListMainWindow::CheckItem(long item, bool state)
{
wxListLineData *line = GetLine((size_t)item);
line->Check(state);
RefreshLine(item);
SendNotify(item, state ? wxEVT_LIST_ITEM_CHECKED
: wxEVT_LIST_ITEM_UNCHECKED);
}
bool wxListMainWindow::IsItemChecked(long item) const
{
wxListLineData *line = GetLine((size_t)item);
return line->IsChecked();
}
bool wxListMainWindow::IsInsideCheckBox(long item, int x, int y)
{
if ( HasCheckBoxes() )
{
wxRect lineRect = GetLineRect(item);
wxSize cbSize = wxRendererNative::Get().GetCheckBoxSize(this);
int yOffset = (lineRect.height - cbSize.GetHeight()) / 2;
wxRect rr(wxPoint(MARGIN_AROUND_CHECKBOX, lineRect.y + yOffset), cbSize);
return rr.Contains(wxPoint(x, y));
}
return false;
}
// ----------------------------------------------------------------------------
// geometry calculation
// ----------------------------------------------------------------------------
void wxListMainWindow::RecalculatePositions(bool noRefresh)
{
const int lineHeight = GetLineHeight();
wxClientDC dc( this );
dc.SetFont( GetFont() );
const size_t count = GetItemCount();
int iconSpacing;
if ( HasFlag(wxLC_ICON) && m_normal_image_list )
iconSpacing = m_normal_spacing;
else if ( HasFlag(wxLC_SMALL_ICON) && m_small_image_list )
iconSpacing = m_small_spacing;
else
iconSpacing = 0;
// Note that we do not call GetClientSize() here but
// GetSize() and subtract the border size for sunken
// borders manually. This is technically incorrect,
// but we need to know the client area's size WITHOUT
// scrollbars here. Since we don't know if there are
// any scrollbars, we use GetSize() instead. Another
// solution would be to call SetScrollbars() here to
// remove the scrollbars and call GetClientSize() then,
// but this might result in flicker and - worse - will
// reset the scrollbars to 0 which is not good at all
// if you resize a dialog/window, but don't want to
// reset the window scrolling. RR.
// Furthermore, we actually do NOT subtract the border
// width as 2 pixels is just the extra space which we
// need around the actual content in the window. Other-
// wise the text would e.g. touch the upper border. RR.
int clientWidth,
clientHeight;
GetSize( &clientWidth, &clientHeight );
if ( InReportView() )
{
// all lines have the same height and we scroll one line per step
int entireHeight = count * lineHeight + LINE_SPACING;
m_linesPerPage = clientHeight / lineHeight;
ResetVisibleLinesRange();
GetListCtrl()->SetScrollbars( SCROLL_UNIT_X, lineHeight,
GetHeaderWidth() / SCROLL_UNIT_X,
(entireHeight + lineHeight - 1) / lineHeight,
GetListCtrl()->GetScrollPos(wxHORIZONTAL),
GetListCtrl()->GetScrollPos(wxVERTICAL),
true );
}
else // !report
{
// we have 3 different layout strategies: either layout all items
// horizontally/vertically (wxLC_ALIGN_XXX styles explicitly given) or
// to arrange them in top to bottom, left to right (don't ask me why
// not the other way round...) order
if ( HasFlag(wxLC_ALIGN_LEFT | wxLC_ALIGN_TOP) )
{
int x = EXTRA_BORDER_X;
int y = EXTRA_BORDER_Y;
wxCoord widthMax = 0;
size_t i;
for ( i = 0; i < count; i++ )
{
wxListLineData *line = GetLine(i);
line->CalculateSize( &dc, iconSpacing );
line->SetPosition( x, y, iconSpacing );
wxSize sizeLine = GetLineSize(i);
if ( HasFlag(wxLC_ALIGN_TOP) )
{
if ( sizeLine.x > widthMax )
widthMax = sizeLine.x;
y += sizeLine.y;
}
else // wxLC_ALIGN_LEFT
{
x += sizeLine.x + MARGIN_BETWEEN_ROWS;
}
}
if ( HasFlag(wxLC_ALIGN_TOP) )
{
// traverse the items again and tweak their sizes so that they are
// all the same in a row
for ( i = 0; i < count; i++ )
{
wxListLineData *line = GetLine(i);
line->m_gi->ExtendWidth(widthMax);
}
}
GetListCtrl()->SetScrollbars
(
SCROLL_UNIT_X,
lineHeight,
(x + SCROLL_UNIT_X) / SCROLL_UNIT_X,
(y + lineHeight) / lineHeight,
GetListCtrl()->GetScrollPos( wxHORIZONTAL ),
GetListCtrl()->GetScrollPos( wxVERTICAL ),
true
);
}
else // "flowed" arrangement, the most complicated case
{
// at first we try without any scrollbars, if the items don't fit into
// the window, we recalculate after subtracting the space taken by the
// scrollbar
int entireWidth = 0;
for (int tries = 0; tries < 2; tries++)
{
entireWidth = 2 * EXTRA_BORDER_X;
if (tries == 1)
{
// Now we have decided that the items do not fit into the
// client area, so we need a scrollbar
entireWidth += SCROLL_UNIT_X;
}
int x = EXTRA_BORDER_X;
int y = EXTRA_BORDER_Y;
// Note that "row" here is vertical, i.e. what is called
// "column" in many other places in wxWidgets.
int maxWidthInThisRow = 0;
m_linesPerPage = 0;
int currentlyVisibleLines = 0;
for (size_t i = 0; i < count; i++)
{
currentlyVisibleLines++;
wxListLineData *line = GetLine( i );
line->CalculateSize( &dc, iconSpacing );
line->SetPosition( x, y, iconSpacing );
wxSize sizeLine = GetLineSize( i );
if ( maxWidthInThisRow < sizeLine.x )
maxWidthInThisRow = sizeLine.x;
y += sizeLine.y;
if (currentlyVisibleLines > m_linesPerPage)
m_linesPerPage = currentlyVisibleLines;
// Have we reached the end of the row either because no
// more items would fit or because there are simply no more
// items?
if ( y + sizeLine.y >= clientHeight
|| i == count - 1)
{
// Adjust all items in this row to have the same
// width to ensure that they all align horizontally in
// icon view.
if ( HasFlag(wxLC_ICON) || HasFlag(wxLC_SMALL_ICON) )
{
size_t firstRowLine = i - currentlyVisibleLines + 1;
for (size_t j = firstRowLine; j <= i; j++)
{
GetLine(j)->m_gi->ExtendWidth(maxWidthInThisRow);
}
}
currentlyVisibleLines = 0;
y = EXTRA_BORDER_Y;
maxWidthInThisRow += MARGIN_BETWEEN_ROWS;
x += maxWidthInThisRow;
entireWidth += maxWidthInThisRow;
maxWidthInThisRow = 0;
}
if ( (tries == 0) &&
(entireWidth + SCROLL_UNIT_X > clientWidth) )
{
clientHeight -= wxSystemSettings::
GetMetric(wxSYS_HSCROLL_Y);
m_linesPerPage = 0;
break;
}
if ( i == count - 1 )
tries = 1; // Everything fits, no second try required.
}
}
GetListCtrl()->SetScrollbars
(
SCROLL_UNIT_X,
lineHeight,
(entireWidth + SCROLL_UNIT_X) / SCROLL_UNIT_X,
0,
GetListCtrl()->GetScrollPos( wxHORIZONTAL ),
0,
true
);
}
}
if ( !noRefresh )
{
RefreshAll();
}
}
void wxListMainWindow::RefreshAll()
{
m_dirty = false;
Refresh();
wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
if ( headerWin && headerWin->m_dirty )
{
headerWin->m_dirty = false;
headerWin->Refresh();
}
}
void wxListMainWindow::UpdateCurrent()
{
if ( !HasCurrent() && !IsEmpty() )
{
// Initialise m_current to the first item without sending any
// wxEVT_LIST_ITEM_FOCUSED event (typicaly when the control gains focus)
// and this is to allow changing the focused item using the arrow keys.
// which is the behaviour found in the wxMSW port.
ChangeCurrentWithoutEvent(0);
}
}
long wxListMainWindow::GetNextItem( long item,
int WXUNUSED(geometry),
int state ) const
{
long ret = item,
max = GetItemCount();
wxCHECK_MSG( (ret == -1) || (ret < max), -1,
wxT("invalid listctrl index in GetNextItem()") );
// notice that we start with the next item (or the first one if item == -1)
// and this is intentional to allow writing a simple loop to iterate over
// all selected items
ret++;
if ( ret == max )
// this is not an error because the index was OK initially,
// just no such item
return -1;
if ( !state )
// any will do
return (size_t)ret;
size_t count = GetItemCount();
for ( size_t line = (size_t)ret; line < count; line++ )
{
if ( (state & wxLIST_STATE_FOCUSED) && (line == m_current) )
return line;
if ( (state & wxLIST_STATE_SELECTED) && IsHighlighted(line) )
return line;
}
return -1;
}
// ----------------------------------------------------------------------------
// deleting stuff
// ----------------------------------------------------------------------------
void wxListMainWindow::DeleteItem( long lindex )
{
size_t count = GetItemCount();
wxCHECK_RET( (lindex >= 0) && ((size_t)lindex < count),
wxT("invalid item index in DeleteItem") );
size_t index = (size_t)lindex;
// we don't need to adjust the index for the previous items
if ( HasCurrent() && m_current >= index )
{
// if the current item is being deleted, we want the next one to
// become selected - unless there is no next one - so don't adjust
// m_current in this case
if ( m_current != index || m_current == count - 1 )
m_current--;
}
if ( InReportView() )
{
// mark the Column Max Width cache as dirty if the items in the line
// we're deleting contain the Max Column Width
wxListLineData * const line = GetLine(index);
wxListItemDataList::compatibility_iterator n;
wxListItem item;
for (size_t i = 0; i < m_columns.GetCount(); i++)
{
n = line->m_items.Item( i );
wxListItemData* itemData;
itemData = n->GetData();
itemData->GetItem(item);
int itemWidth;
itemWidth = GetItemWidthWithImage(&item);
wxColWidthInfo *pWidthInfo = m_aColWidths.Item(i);
if ( itemWidth >= pWidthInfo->nMaxWidth )
pWidthInfo->bNeedsUpdate = true;
}
ResetVisibleLinesRange();
}
SendNotify( index, wxEVT_LIST_DELETE_ITEM, wxDefaultPosition );
if ( IsVirtual() )
{
m_countVirt--;
m_selStore.OnItemDelete(index);
}
else
{
delete m_lines[index];
m_lines.erase( m_lines.begin() + index );
}
// we need to refresh the (vert) scrollbar as the number of items changed
m_dirty = true;
RefreshAfter(index);
// This might be a wxGTK bug, but when deleting the last item in a control
// with many items, the vertical scroll position may change so that the new
// last item is not visible any longer, which is very annoying from the
// user point of view. Ensure that whatever happens, this item is visible.
if ( count > 1 && m_current != (size_t)-1 )
EnsureVisible(m_current);
}
void wxListMainWindow::DeleteColumn( int col )
{
wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
wxCHECK_RET( node, wxT("invalid column index in DeleteColumn()") );
m_dirty = true;
delete node->GetData();
m_columns.Erase( node );
if ( !IsVirtual() )
{
// update all the items
for ( size_t i = 0; i < m_lines.size(); i++ )
{
wxListLineData * const line = GetLine(i);
// In the following atypical but possible scenario it can be
// legal to call DeleteColumn() but the items may not have any
// values for it:
// 1. In report view, insert a second column.
// 2. Still in report view, add an item with 2 values.
// 3. Switch to an icon (or list) view.
// 4. Add an item -- necessarily with 1 value only.
// 5. Switch back to report view.
// 6. Call DeleteColumn().
// So we need to check for this as otherwise we would simply crash
// if this happens.
if ( line->m_items.GetCount() <= static_cast<unsigned>(col) )
continue;
wxListItemDataList::compatibility_iterator n = line->m_items.Item( col );
delete n->GetData();
line->m_items.Erase(n);
}
}
if ( InReportView() ) // we only cache max widths when in Report View
{
delete m_aColWidths.Item(col);
m_aColWidths.RemoveAt(col);
}
// invalidate it as it has to be recalculated
m_headerWidth = 0;
}
void wxListMainWindow::DoDeleteAllItems()
{
// We will need to update all columns if any items are inserted again.
if ( InReportView() )
{
for ( size_t i = 0; i < m_aColWidths.GetCount(); i++ )
m_aColWidths.Item(i)->bNeedsUpdate = true;
}
if ( IsEmpty() )
// nothing to do - in particular, don't send the event
return;
ResetCurrent();
// to make the deletion of all items faster, we don't send the
// notifications for each item deletion in this case but only one event
// for all of them: this is compatible with wxMSW and documented in
// DeleteAllItems() description
wxListEvent event( wxEVT_LIST_DELETE_ALL_ITEMS, GetParent()->GetId() );
event.SetEventObject( GetParent() );
GetParent()->GetEventHandler()->ProcessEvent( event );
if ( IsVirtual() )
{
m_countVirt = 0;
m_selStore.Clear();
}
else
{
m_selCount = 0;
}
if ( InReportView() )
ResetVisibleLinesRange();
m_lines.Clear();
}
void wxListMainWindow::DeleteAllItems()
{
DoDeleteAllItems();
RecalculatePositions();
}
void wxListMainWindow::DeleteEverything()
{
WX_CLEAR_LIST(wxListHeaderDataList, m_columns);
WX_CLEAR_ARRAY(m_aColWidths);
DeleteAllItems();
}
// ----------------------------------------------------------------------------
// scanning for an item
// ----------------------------------------------------------------------------
void wxListMainWindow::EnsureVisible( long index )
{
wxCHECK_RET( index >= 0 && (size_t)index < GetItemCount(),
wxT("invalid index in EnsureVisible") );
// We have to call this here because the label in question might just have
// been added and its position is not known yet
if ( m_dirty )
RecalculatePositions(true /* no refresh */);
MoveToItem((size_t)index);
}
long wxListMainWindow::FindItem(long start, const wxString& str, bool partial )
{
if (str.empty())
return wxNOT_FOUND;
long pos = start;
wxString str_upper = str.Upper();
if (pos < 0)
pos = 0;
size_t count = GetItemCount();
for ( size_t i = (size_t)pos; i < count; i++ )
{
wxListLineData *line = GetLine(i);
wxString line_upper = line->GetText(0).Upper();
if (!partial)
{
if (line_upper == str_upper )
return i;
}
else
{
if (line_upper.find(str_upper) == 0)
return i;
}
}
return wxNOT_FOUND;
}
long wxListMainWindow::FindItem(long start, wxUIntPtr data)
{
long pos = start;
if (pos < 0)
pos = 0;
size_t count = GetItemCount();
for (size_t i = (size_t)pos; i < count; i++)
{
wxListLineData *line = GetLine(i);
wxListItem item;
line->GetItem( 0, item );
if (item.m_data == data)
return i;
}
return wxNOT_FOUND;
}
long wxListMainWindow::FindItem( const wxPoint& pt )
{
size_t topItem;
GetVisibleLinesRange( &topItem, NULL );
wxPoint p;
GetItemPosition( GetItemCount() - 1, p );
if ( p.y == 0 )
return topItem;
long id = (long)floor( pt.y * double(GetItemCount() - topItem - 1) / p.y + topItem );
if ( id >= 0 && id < (long)GetItemCount() )
return id;
return wxNOT_FOUND;
}
long wxListMainWindow::HitTest( int x, int y, int &flags ) const
{
GetListCtrl()->CalcUnscrolledPosition( x, y, &x, &y );
size_t count = GetItemCount();
if ( InReportView() )
{
size_t current = y / GetLineHeight();
if ( current < count )
{
flags = HitTestLine(current, x, y);
if ( flags )
return current;
}
}
else // !report
{
// TODO: optimize it too! this is less simple than for report view but
// enumerating all items is still not a way to do it!!
for ( size_t current = 0; current < count; current++ )
{
flags = HitTestLine(current, x, y);
if ( flags )
return current;
}
}
return wxNOT_FOUND;
}
// ----------------------------------------------------------------------------
// adding stuff
// ----------------------------------------------------------------------------
void wxListMainWindow::InsertItem( wxListItem &item )
{
wxASSERT_MSG( !IsVirtual(), wxT("can't be used with virtual control") );
int count = GetItemCount();
wxCHECK_RET( item.m_itemId >= 0, wxT("invalid item index") );
if (item.m_itemId > count)
item.m_itemId = count;
size_t id = item.m_itemId;
m_dirty = true;
if ( InReportView() )
{
ResetVisibleLinesRange();
const unsigned col = item.GetColumn();
wxCHECK_RET( col < m_aColWidths.size(), "invalid item column" );
// calculate the width of the item and adjust the max column width
wxColWidthInfo *pWidthInfo = m_aColWidths.Item(col);
int width = GetItemWidthWithImage(&item);
item.SetWidth(width);
if (width > pWidthInfo->nMaxWidth)
{
pWidthInfo->nMaxWidth = width;
pWidthInfo->bNeedsUpdate = true;
}
}
wxListLineData *line = new wxListLineData(this);
line->SetItem( item.m_col, item );
if ( item.m_mask & wxLIST_MASK_IMAGE )
{
// Reset the buffered height if it's not big enough for the new image.
int image = item.GetImage();
if ( m_small_image_list && image != -1 && InReportView() )
{
int imageWidth, imageHeight;
m_small_image_list->GetSize(image, imageWidth, imageHeight);
if ( imageHeight > m_lineHeight )
m_lineHeight = 0;
}
}
m_lines.insert( m_lines.begin() + id, line );
m_dirty = true;
// If an item is selected at or below the point of insertion, we need to
// increment the member variables because the current row's index has gone
// up by one
if ( HasCurrent() && m_current >= id )
m_current++;
SendNotify(id, wxEVT_LIST_INSERT_ITEM);
RefreshLines(id, GetItemCount() - 1);
}
long wxListMainWindow::InsertColumn( long col, const wxListItem &item )
{
long idx = -1;
m_dirty = true;
if ( InReportView() )
{
wxListHeaderData *column = new wxListHeaderData( item );
if (item.m_width == wxLIST_AUTOSIZE_USEHEADER)
column->SetWidth(ComputeMinHeaderWidth(column));
wxColWidthInfo *colWidthInfo = new wxColWidthInfo(0, IsVirtual());
bool insert = (col >= 0) && ((size_t)col < m_columns.GetCount());
if ( insert )
{
wxListHeaderDataList::compatibility_iterator
node = m_columns.Item( col );
m_columns.Insert( node, column );
m_aColWidths.Insert( colWidthInfo, col );
idx = col;
}
else
{
idx = m_aColWidths.GetCount();
m_columns.Append( column );
m_aColWidths.Add( colWidthInfo );
}
if ( !IsVirtual() )
{
// update all the items
for ( size_t i = 0; i < m_lines.size(); i++ )
{
wxListLineData * const line = GetLine(i);
wxListItemData * const data = new wxListItemData(this);
if ( insert )
line->m_items.Insert(col, data);
else
line->m_items.Append(data);
}
}
// invalidate it as it has to be recalculated
m_headerWidth = 0;
}
return idx;
}
int wxListMainWindow::GetItemWidthWithImage(wxListItem * item)
{
int width = 0;
wxClientDC dc(this);
dc.SetFont( GetFont() );
if (item->GetImage() != -1)
{
int ix, iy;
GetImageSize( item->GetImage(), ix, iy );
width += ix + IMAGE_MARGIN_IN_REPORT_MODE;
}
if (!item->GetText().empty())
{
wxCoord w;
dc.GetTextExtent( item->GetText(), &w, NULL );
width += w;
}
return width;
}
// ----------------------------------------------------------------------------
// sorting
// ----------------------------------------------------------------------------
struct wxListLineComparator
{
wxListLineComparator(wxListCtrlCompare& f, wxIntPtr data)
: m_f(f),
m_data(data)
{
}
bool operator()(wxListLineData* const& line1,
wxListLineData* const& line2) const
{
wxListItem item;
line1->GetItem( 0, item );
wxUIntPtr data1 = item.m_data;
line2->GetItem( 0, item );
wxUIntPtr data2 = item.m_data;
return m_f(data1, data2, m_data) < 0;
}
const wxListCtrlCompare m_f;
const wxIntPtr m_data;
};
void wxListMainWindow::SortItems( wxListCtrlCompare fn, wxIntPtr data )
{
// selections won't make sense any more after sorting the items so reset
// them
HighlightAll(false);
ResetCurrent();
std::sort(m_lines.begin(), m_lines.end(), wxListLineComparator(fn, data));
m_dirty = true;
}
// ----------------------------------------------------------------------------
// scrolling
// ----------------------------------------------------------------------------
void wxListMainWindow::OnScroll(wxScrollWinEvent& event)
{
// update our idea of which lines are shown when we redraw the window the
// next time
ResetVisibleLinesRange();
if ( event.GetOrientation() == wxHORIZONTAL && HasHeader() )
{
wxGenericListCtrl* lc = GetListCtrl();
wxCHECK_RET( lc, wxT("no listctrl window?") );
if (lc->m_headerWin) // when we use wxLC_NO_HEADER, m_headerWin==NULL
{
lc->m_headerWin->Refresh();
lc->m_headerWin->Update();
}
}
}
int wxListMainWindow::GetCountPerPage() const
{
if ( !m_linesPerPage )
{
wxConstCast(this, wxListMainWindow)->
m_linesPerPage = GetClientSize().y / GetLineHeight();
}
return m_linesPerPage;
}
void wxListMainWindow::GetVisibleLinesRange(size_t *from, size_t *to)
{
wxASSERT_MSG( InReportView(), wxT("this is for report mode only") );
if ( m_lineFrom == (size_t)-1 )
{
size_t count = GetItemCount();
if ( count )
{
m_lineFrom = GetListCtrl()->GetScrollPos(wxVERTICAL);
// this may happen if SetScrollbars() hadn't been called yet
if ( m_lineFrom >= count )
m_lineFrom = count - 1;
// we redraw one extra line but this is needed to make the redrawing
// logic work when there is a fractional number of lines on screen
m_lineTo = m_lineFrom + m_linesPerPage;
if ( m_lineTo >= count )
m_lineTo = count - 1;
}
else // empty control
{
m_lineFrom = 0;
m_lineTo = (size_t)-1;
}
}
wxASSERT_MSG( IsEmpty() ||
(m_lineFrom <= m_lineTo && m_lineTo < GetItemCount()),
wxT("GetVisibleLinesRange() returns incorrect result") );
if ( from )
*from = m_lineFrom;
if ( to )
*to = m_lineTo;
}
size_t
wxListMainWindow::PrefixFindItem(size_t idParent,
const wxString& prefixOrig) const
{
// if no items then just return
if ( idParent == (size_t)-1 )
return idParent;
// match is case insensitive as this is more convenient to the user: having
// to press Shift-letter to go to the item starting with a capital letter
// would be too bothersome
wxString prefix = prefixOrig.Lower();
// determine the starting point: we shouldn't take the current item (this
// allows to switch between two items starting with the same letter just by
// pressing it) but we shouldn't jump to the next one if the user is
// continuing to type as otherwise he might easily skip the item he wanted
size_t itemid = idParent;
if ( prefix.length() == 1 )
{
itemid += 1;
}
// look for the item starting with the given prefix after it
while ( ( itemid < (size_t)GetItemCount() ) &&
!GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) )
{
itemid += 1;
}
// if we haven't found anything...
if ( !( itemid < (size_t)GetItemCount() ) )
{
// ... wrap to the beginning
itemid = 0;
// and try all the items (stop when we get to the one we started from)
while ( ( itemid < (size_t)GetItemCount() ) && itemid != idParent &&
!GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) )
{
itemid += 1;
}
// If we haven't found the item, id will be (size_t)-1, as per
// documentation
if ( !( itemid < (size_t)GetItemCount() ) ||
( ( itemid == idParent ) &&
!GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) ) )
{
itemid = (size_t)-1;
}
}
return itemid;
}
// -------------------------------------------------------------------------------------
// wxGenericListCtrl
// -------------------------------------------------------------------------------------
wxIMPLEMENT_DYNAMIC_CLASS(wxGenericListCtrl, wxControl);
wxBEGIN_EVENT_TABLE(wxGenericListCtrl,wxListCtrlBase)
EVT_SIZE(wxGenericListCtrl::OnSize)
EVT_SCROLLWIN(wxGenericListCtrl::OnScroll)
wxEND_EVENT_TABLE()
void wxGenericListCtrl::Init()
{
m_imageListNormal = NULL;
m_imageListSmall = NULL;
m_imageListState = NULL;
m_ownsImageListNormal =
m_ownsImageListSmall =
m_ownsImageListState = false;
m_mainWin = NULL;
m_headerWin = NULL;
}
wxGenericListCtrl::~wxGenericListCtrl()
{
if (m_ownsImageListNormal)
delete m_imageListNormal;
if (m_ownsImageListSmall)
delete m_imageListSmall;
if (m_ownsImageListState)
delete m_imageListState;
}
void wxGenericListCtrl::CreateOrDestroyHeaderWindowAsNeeded()
{
bool needs_header = HasHeader();
bool has_header = (m_headerWin != NULL);
if (needs_header == has_header)
return;
if (needs_header)
{
// Notice that we must initialize m_headerWin first, and create the
// real window only later, so that the test in the beginning of the
// function blocks repeated creation of the header as it could happen
// before via wxNavigationEnabled::AddChild() -> ToggleWindowStyle() ->
// SetWindowStyleFlag().
m_headerWin = new wxListHeaderWindow();
m_headerWin->Create
(
this, wxID_ANY, m_mainWin,
wxPoint(0,0),
wxSize
(
GetClientSize().x,
wxRendererNative::Get().GetHeaderButtonHeight(this)
),
wxTAB_TRAVERSAL
);
#if defined( __WXMAC__ )
static wxFont font( wxOSX_SYSTEM_FONT_SMALL );
m_headerWin->SetFont( font );
#endif
GetSizer()->Prepend( m_headerWin, 0, wxGROW );
}
else
{
GetSizer()->Detach( m_headerWin );
wxDELETE(m_headerWin);
}
}
bool wxGenericListCtrl::Create(wxWindow *parent,
wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style,
const wxValidator &validator,
const wxString &name)
{
Init();
// just like in other ports, an assert will fail if the user doesn't give any type style:
wxASSERT_MSG( (style & wxLC_MASK_TYPE),
wxT("wxListCtrl style should have exactly one mode bit set") );
if ( !wxListCtrlBase::Create( parent, id, pos, size,
style | wxVSCROLL | wxHSCROLL,
validator, name ) )
return false;
m_mainWin = new wxListMainWindow(this, wxID_ANY, wxPoint(0, 0), size);
SetTargetWindow( m_mainWin );
// We use the cursor keys for moving the selection, not scrolling, so call
// this method to ensure wxScrollHelperEvtHandler doesn't catch all
// keyboard events forwarded to us from wxListMainWindow.
DisableKeyboardScrolling();
wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
sizer->Add( m_mainWin, 1, wxGROW );
SetSizer( sizer );
CreateOrDestroyHeaderWindowAsNeeded();
SetInitialSize(size);
return true;
}
void wxGenericListCtrl::ExtendRulesAndAlternateColour(bool state)
{
wxCHECK_RET( m_mainWin, "can't be called before creation" );
wxASSERT_MSG( InReportView(), "can only be called in report mode" );
m_mainWin->ExtendRulesAndAlternateColour(state);
m_mainWin->Refresh();
}
wxBorder wxGenericListCtrl::GetDefaultBorder() const
{
return wxBORDER_THEME;
}
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
WXLRESULT wxGenericListCtrl::MSWWindowProc(WXUINT nMsg,
WXWPARAM wParam,
WXLPARAM lParam)
{
WXLRESULT rc = wxListCtrlBase::MSWWindowProc(nMsg, wParam, lParam);
// we need to process arrows ourselves for scrolling
if ( nMsg == WM_GETDLGCODE )
{
rc |= DLGC_WANTARROWS;
}
return rc;
}
#endif // __WXMSW__
wxSize wxGenericListCtrl::GetSizeAvailableForScrollTarget(const wxSize& size)
{
wxSize newsize = size;
if (m_headerWin)
newsize.y -= m_headerWin->GetSize().y;
return newsize;
}
void wxGenericListCtrl::OnScroll(wxScrollWinEvent& event)
{
// update our idea of which lines are shown when we redraw
// the window the next time
m_mainWin->ResetVisibleLinesRange();
if ( event.GetOrientation() == wxHORIZONTAL && HasHeader() )
{
m_headerWin->Refresh();
m_headerWin->Update();
}
// Let the window be scrolled as usual by the default handler.
event.Skip();
}
bool wxGenericListCtrl::HasCheckBoxes() const
{
if (!InReportView())
return false;
return m_mainWin->HasCheckBoxes();
}
bool wxGenericListCtrl::EnableCheckBoxes(bool enable)
{
if (!InReportView())
return false;
return m_mainWin->EnableCheckBoxes(enable);
}
void wxGenericListCtrl::CheckItem(long item, bool state)
{
if (InReportView())
m_mainWin->CheckItem(item, state);
}
bool wxGenericListCtrl::IsItemChecked(long item) const
{
if (!InReportView())
return false;
return m_mainWin->IsItemChecked(item);
}
void wxGenericListCtrl::SetSingleStyle( long style, bool add )
{
wxASSERT_MSG( !(style & wxLC_VIRTUAL),
wxT("wxLC_VIRTUAL can't be [un]set") );
long flag = GetWindowStyle();
if (add)
{
if (style & wxLC_MASK_TYPE)
flag &= ~(wxLC_MASK_TYPE | wxLC_VIRTUAL);
if (style & wxLC_MASK_ALIGN)
flag &= ~wxLC_MASK_ALIGN;
if (style & wxLC_MASK_SORT)
flag &= ~wxLC_MASK_SORT;
}
if (add)
flag |= style;
else
flag &= ~style;
// some styles can be set without recreating everything (as happens in
// SetWindowStyleFlag() which calls wxListMainWindow::DeleteEverything())
if ( !(style & ~(wxLC_HRULES | wxLC_VRULES)) )
{
Refresh();
wxWindow::SetWindowStyleFlag(flag);
}
else
{
SetWindowStyleFlag( flag );
}
}
void wxGenericListCtrl::SetWindowStyleFlag( long flag )
{
// we add wxHSCROLL and wxVSCROLL in ctor unconditionally and it never
// makes sense to remove them as we'll always add scrollbars anyhow when
// needed
flag |= wxHSCROLL | wxVSCROLL;
const bool wasInReportView = HasFlag(wxLC_REPORT);
// update the window style first so that the header is created or destroyed
// corresponding to the new style
wxWindow::SetWindowStyleFlag( flag );
if (m_mainWin)
{
const bool inReportView = (flag & wxLC_REPORT) != 0;
if ( inReportView != wasInReportView )
{
// we need to notify the main window about this change as it must
// update its data structures
m_mainWin->SetReportView(inReportView);
}
// m_mainWin->DeleteEverything(); wxMSW doesn't do that
CreateOrDestroyHeaderWindowAsNeeded();
GetSizer()->Layout();
}
}
bool wxGenericListCtrl::GetColumn(int col, wxListItem &item) const
{
m_mainWin->GetColumn( col, item );
return true;
}
bool wxGenericListCtrl::SetColumn( int col, const wxListItem& item )
{
m_mainWin->SetColumn( col, item );
return true;
}
int wxGenericListCtrl::GetColumnWidth( int col ) const
{
return m_mainWin->GetColumnWidth( col );
}
bool wxGenericListCtrl::SetColumnWidth( int col, int width )
{
m_mainWin->SetColumnWidth( col, width );
return true;
}
int wxGenericListCtrl::GetCountPerPage() const
{
return m_mainWin->GetCountPerPage(); // different from Windows ?
}
bool wxGenericListCtrl::GetItem( wxListItem &info ) const
{
m_mainWin->GetItem( info );
return true;
}
bool wxGenericListCtrl::SetItem( wxListItem &info )
{
m_mainWin->SetItem( info );
return true;
}
bool wxGenericListCtrl::SetItem( long index, int col, const wxString& label, int imageId )
{
wxListItem info;
info.m_text = label;
info.m_mask = wxLIST_MASK_TEXT;
info.m_itemId = index;
info.m_col = col;
if ( imageId > -1 )
{
info.m_image = imageId;
info.m_mask |= wxLIST_MASK_IMAGE;
}
m_mainWin->SetItem(info);
return true;
}
int wxGenericListCtrl::GetItemState( long item, long stateMask ) const
{
return m_mainWin->GetItemState( item, stateMask );
}
bool wxGenericListCtrl::SetItemState( long item, long state, long stateMask )
{
m_mainWin->SetItemState( item, state, stateMask );
return true;
}
bool
wxGenericListCtrl::SetItemImage( long item, int image, int WXUNUSED(selImage) )
{
return SetItemColumnImage(item, 0, image);
}
bool
wxGenericListCtrl::SetItemColumnImage( long item, long column, int image )
{
wxListItem info;
info.m_image = image;
info.m_mask = wxLIST_MASK_IMAGE;
info.m_itemId = item;
info.m_col = column;
m_mainWin->SetItem( info );
return true;
}
wxString wxGenericListCtrl::GetItemText( long item, int col ) const
{
return m_mainWin->GetItemText(item, col);
}
void wxGenericListCtrl::SetItemText( long item, const wxString& str )
{
m_mainWin->SetItemText(item, str);
}
wxUIntPtr wxGenericListCtrl::GetItemData( long item ) const
{
wxListItem info;
info.m_mask = wxLIST_MASK_DATA;
info.m_itemId = item;
m_mainWin->GetItem( info );
return info.m_data;
}
bool wxGenericListCtrl::SetItemPtrData( long item, wxUIntPtr data )
{
wxListItem info;
info.m_mask = wxLIST_MASK_DATA;
info.m_itemId = item;
info.m_data = data;
m_mainWin->SetItem( info );
return true;
}
wxRect wxGenericListCtrl::GetViewRect() const
{
return m_mainWin->GetViewRect();
}
bool wxGenericListCtrl::GetItemRect(long item, wxRect& rect, int code) const
{
return GetSubItemRect(item, wxLIST_GETSUBITEMRECT_WHOLEITEM, rect, code);
}
bool wxGenericListCtrl::GetSubItemRect(long item,
long subItem,
wxRect& rect,
int code) const
{
if ( !m_mainWin->GetSubItemRect( item, subItem, rect, code ) )
return false;
if ( m_mainWin->HasHeader() )
rect.y += m_headerWin->GetSize().y + 1;
return true;
}
bool wxGenericListCtrl::GetItemPosition( long item, wxPoint& pos ) const
{
m_mainWin->GetItemPosition( item, pos );
return true;
}
bool wxGenericListCtrl::SetItemPosition( long WXUNUSED(item), const wxPoint& WXUNUSED(pos) )
{
return false;
}
int wxGenericListCtrl::GetItemCount() const
{
return m_mainWin->GetItemCount();
}
int wxGenericListCtrl::GetColumnCount() const
{
return m_mainWin->GetColumnCount();
}
void wxGenericListCtrl::SetItemSpacing( int spacing, bool isSmall )
{
m_mainWin->SetItemSpacing( spacing, isSmall );
}
wxSize wxGenericListCtrl::GetItemSpacing() const
{
const int spacing = m_mainWin->GetItemSpacing(HasFlag(wxLC_SMALL_ICON));
return wxSize(spacing, spacing);
}
void wxGenericListCtrl::SetItemTextColour( long item, const wxColour &col )
{
wxListItem info;
info.m_itemId = item;
info.SetTextColour( col );
m_mainWin->SetItem( info );
}
wxColour wxGenericListCtrl::GetItemTextColour( long item ) const
{
wxListItem info;
info.m_itemId = item;
m_mainWin->GetItem( info );
return info.GetTextColour();
}
void wxGenericListCtrl::SetItemBackgroundColour( long item, const wxColour &col )
{
wxListItem info;
info.m_itemId = item;
info.SetBackgroundColour( col );
m_mainWin->SetItem( info );
}
wxColour wxGenericListCtrl::GetItemBackgroundColour( long item ) const
{
wxListItem info;
info.m_itemId = item;
m_mainWin->GetItem( info );
return info.GetBackgroundColour();
}
void wxGenericListCtrl::SetItemFont( long item, const wxFont &f )
{
wxListItem info;
info.m_itemId = item;
info.SetFont( f );
m_mainWin->SetItem( info );
}
wxFont wxGenericListCtrl::GetItemFont( long item ) const
{
wxListItem info;
info.m_itemId = item;
m_mainWin->GetItem( info );
return info.GetFont();
}
int wxGenericListCtrl::GetSelectedItemCount() const
{
return m_mainWin->GetSelectedItemCount();
}
wxColour wxGenericListCtrl::GetTextColour() const
{
return GetForegroundColour();
}
void wxGenericListCtrl::SetTextColour(const wxColour& col)
{
SetForegroundColour(col);
}
long wxGenericListCtrl::GetTopItem() const
{
size_t top;
m_mainWin->GetVisibleLinesRange(&top, NULL);
return (long)top;
}
long wxGenericListCtrl::GetNextItem( long item, int geom, int state ) const
{
return m_mainWin->GetNextItem( item, geom, state );
}
wxImageList *wxGenericListCtrl::GetImageList(int which) const
{
if (which == wxIMAGE_LIST_NORMAL)
return m_imageListNormal;
else if (which == wxIMAGE_LIST_SMALL)
return m_imageListSmall;
else if (which == wxIMAGE_LIST_STATE)
return m_imageListState;
return NULL;
}
void wxGenericListCtrl::SetImageList( wxImageList *imageList, int which )
{
if ( which == wxIMAGE_LIST_NORMAL )
{
if (m_ownsImageListNormal)
delete m_imageListNormal;
m_imageListNormal = imageList;
m_ownsImageListNormal = false;
}
else if ( which == wxIMAGE_LIST_SMALL )
{
if (m_ownsImageListSmall)
delete m_imageListSmall;
m_imageListSmall = imageList;
m_ownsImageListSmall = false;
}
else if ( which == wxIMAGE_LIST_STATE )
{
if (m_ownsImageListState)
delete m_imageListState;
m_imageListState = imageList;
m_ownsImageListState = false;
}
m_mainWin->SetImageList( imageList, which );
}
void wxGenericListCtrl::AssignImageList(wxImageList *imageList, int which)
{
SetImageList(imageList, which);
if ( which == wxIMAGE_LIST_NORMAL )
m_ownsImageListNormal = true;
else if ( which == wxIMAGE_LIST_SMALL )
m_ownsImageListSmall = true;
else if ( which == wxIMAGE_LIST_STATE )
m_ownsImageListState = true;
}
bool wxGenericListCtrl::Arrange( int WXUNUSED(flag) )
{
return 0;
}
bool wxGenericListCtrl::DeleteItem( long item )
{
m_mainWin->DeleteItem( item );
return true;
}
bool wxGenericListCtrl::DeleteAllItems()
{
m_mainWin->DeleteAllItems();
return true;
}
bool wxGenericListCtrl::DeleteAllColumns()
{
size_t count = m_mainWin->m_columns.GetCount();
for ( size_t n = 0; n < count; n++ )
DeleteColumn( 0 );
return true;
}
void wxGenericListCtrl::ClearAll()
{
m_mainWin->DeleteEverything();
}
bool wxGenericListCtrl::DeleteColumn( int col )
{
m_mainWin->DeleteColumn( col );
// if we don't have the header any longer, we need to relayout the window
// if ( !GetColumnCount() )
// Ensure that the non-existent columns are really removed from display.
Refresh();
return true;
}
wxTextCtrl *wxGenericListCtrl::EditLabel(long item,
wxClassInfo* textControlClass)
{
return m_mainWin->EditLabel( item, textControlClass );
}
bool wxGenericListCtrl::EndEditLabel(bool cancel)
{
return m_mainWin->EndEditLabel(cancel);
}
wxTextCtrl *wxGenericListCtrl::GetEditControl() const
{
return m_mainWin->GetEditControl();
}
bool wxGenericListCtrl::EnsureVisible( long item )
{
m_mainWin->EnsureVisible( item );
return true;
}
long wxGenericListCtrl::FindItem( long start, const wxString& str, bool partial )
{
return m_mainWin->FindItem( start, str, partial );
}
long wxGenericListCtrl::FindItem( long start, wxUIntPtr data )
{
return m_mainWin->FindItem( start, data );
}
long wxGenericListCtrl::FindItem( long WXUNUSED(start), const wxPoint& pt,
int WXUNUSED(direction))
{
return m_mainWin->FindItem( pt );
}
// TODO: sub item hit testing
long wxGenericListCtrl::HitTest(const wxPoint& point, int& flags, long *) const
{
return m_mainWin->HitTest( (int)point.x, (int)point.y, flags );
}
long wxGenericListCtrl::InsertItem( wxListItem& info )
{
m_mainWin->InsertItem( info );
return info.m_itemId;
}
long wxGenericListCtrl::InsertItem( long index, const wxString &label )
{
wxListItem info;
info.m_text = label;
info.m_mask = wxLIST_MASK_TEXT;
info.m_itemId = index;
return InsertItem( info );
}
long wxGenericListCtrl::InsertItem( long index, int imageIndex )
{
wxListItem info;
info.m_mask = wxLIST_MASK_IMAGE;
info.m_image = imageIndex;
info.m_itemId = index;
return InsertItem( info );
}
long wxGenericListCtrl::InsertItem( long index, const wxString &label, int imageIndex )
{
wxListItem info;
info.m_text = label;
info.m_image = imageIndex;
info.m_mask = wxLIST_MASK_TEXT;
if (imageIndex > -1)
info.m_mask |= wxLIST_MASK_IMAGE;
info.m_itemId = index;
return InsertItem( info );
}
long wxGenericListCtrl::DoInsertColumn( long col, const wxListItem &item )
{
wxCHECK_MSG( InReportView(), -1, wxT("can't add column in non report mode") );
long idx = m_mainWin->InsertColumn( col, item );
// NOTE: if wxLC_NO_HEADER was given, then we are in report view mode but
// still have m_headerWin==NULL
if (m_headerWin)
m_headerWin->Refresh();
return idx;
}
bool wxGenericListCtrl::ScrollList( int dx, int dy )
{
return m_mainWin->ScrollList(dx, dy);
}
// Sort items.
// fn is a function which takes 3 long arguments: item1, item2, data.
// item1 is the long data associated with a first item (NOT the index).
// item2 is the long data associated with a second item (NOT the index).
// data is the same value as passed to SortItems.
// The return value is a negative number if the first item should precede the second
// item, a positive number of the second item should precede the first,
// or zero if the two items are equivalent.
// data is arbitrary data to be passed to the sort function.
bool wxGenericListCtrl::SortItems( wxListCtrlCompare fn, wxIntPtr data )
{
m_mainWin->SortItems( fn, data );
return true;
}
// ----------------------------------------------------------------------------
// event handlers
// ----------------------------------------------------------------------------
void wxGenericListCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
{
if (!m_mainWin) return;
// We need to override OnSize so that our scrolled
// window a) does call Layout() to use sizers for
// positioning the controls but b) does not query
// the sizer for their size and use that for setting
// the scrollable area as set that ourselves by
// calling SetScrollbar() further down.
Layout();
m_mainWin->RecalculatePositions();
AdjustScrollbars();
}
void wxGenericListCtrl::OnInternalIdle()
{
wxWindow::OnInternalIdle();
if (m_mainWin->m_dirty)
m_mainWin->RecalculatePositions();
}
// ----------------------------------------------------------------------------
// font/colours
// ----------------------------------------------------------------------------
bool wxGenericListCtrl::SetBackgroundColour( const wxColour &colour )
{
if ( !wxWindow::SetBackgroundColour( colour ) )
return false;
if (m_mainWin)
{
m_mainWin->SetBackgroundColour( colour );
m_mainWin->m_dirty = true;
}
return true;
}
bool wxGenericListCtrl::SetForegroundColour( const wxColour &colour )
{
if ( !wxWindow::SetForegroundColour( colour ) )
return false;
if (m_mainWin)
{
m_mainWin->SetForegroundColour( colour );
m_mainWin->m_dirty = true;
}
return true;
}
bool wxGenericListCtrl::SetFont( const wxFont &font )
{
if (!BaseType::SetFont(font))
return false;
if (m_mainWin)
{
m_mainWin->SetFont( font );
m_mainWin->m_dirty = true;
}
if (m_headerWin)
{
m_headerWin->SetFont( font );
// CalculateAndSetHeaderHeight();
}
Refresh();
return true;
}
// static
wxVisualAttributes
wxGenericListCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
{
#if _USE_VISATTR
// Use the same color scheme as wxListBox
return wxListBox::GetClassDefaultAttributes(variant);
#else
wxUnusedVar(variant);
wxVisualAttributes attr;
attr.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
attr.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
attr.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
return attr;
#endif
}
// ----------------------------------------------------------------------------
// methods forwarded to m_mainWin
// ----------------------------------------------------------------------------
#if wxUSE_DRAG_AND_DROP
void wxGenericListCtrl::SetDropTarget( wxDropTarget *dropTarget )
{
m_mainWin->SetDropTarget( dropTarget );
}
wxDropTarget *wxGenericListCtrl::GetDropTarget() const
{
return m_mainWin->GetDropTarget();
}
#endif
bool wxGenericListCtrl::SetCursor( const wxCursor &cursor )
{
return m_mainWin ? m_mainWin->wxWindow::SetCursor(cursor) : false;
}
wxColour wxGenericListCtrl::GetBackgroundColour() const
{
return m_mainWin ? m_mainWin->GetBackgroundColour() : wxColour();
}
wxColour wxGenericListCtrl::GetForegroundColour() const
{
return m_mainWin ? m_mainWin->GetForegroundColour() : wxColour();
}
wxSize wxGenericListCtrl::DoGetBestClientSize() const
{
// The base class version can compute the best size in report view only.
wxSize sizeBest = wxListCtrlBase::DoGetBestClientSize();
if ( !InReportView() )
{
// Ensure that our minimal width is at least big enough to show all our
// items. This is important for wxListbook to size itself correctly.
// Remember the offset of the first item: this corresponds to the
// margins around the item so we will add it to the minimal size below
// to ensure that we have equal margins on all sides.
wxPoint ofs;
// We can iterate over all items as there shouldn't be too many of them
// in non-report view. If it ever becomes a problem, we could examine
// just the first few items probably, the determination of the best
// size is less important if we will need scrollbars anyhow.
for ( int n = 0; n < GetItemCount(); n++ )
{
const wxRect itemRect = m_mainWin->GetLineRect(n);
if ( !n )
{
// Remember the position of the first item as all the rest are
// offset by at least this number of pixels too.
ofs = itemRect.GetPosition();
}
sizeBest.IncTo(itemRect.GetSize());
}
sizeBest.IncBy(2*ofs);
// If we have the scrollbars we need to account for them too. And to
// make sure the scrollbars status is up to date we need to call this
// function to set them.
m_mainWin->RecalculatePositions(true /* no refresh */);
// Unfortunately we can't use wxWindow::HasScrollbar() here as we need
// to use m_mainWin client/virtual size for determination of whether we
// use scrollbars and not the size of this window itself. Maybe that
// function should be extended to work correctly in the case when our
// scrollbars manage a different window from this one but currently it
// doesn't work.
const wxSize sizeClient = m_mainWin->GetClientSize();
const wxSize sizeVirt = m_mainWin->GetVirtualSize();
if ( sizeVirt.x > sizeClient.x /* HasScrollbar(wxHORIZONTAL) */ )
sizeBest.y += wxSystemSettings::GetMetric(wxSYS_HSCROLL_Y);
if ( sizeVirt.y > sizeClient.y /* HasScrollbar(wxVERTICAL) */ )
sizeBest.x += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
}
return sizeBest;
}
// ----------------------------------------------------------------------------
// virtual list control support
// ----------------------------------------------------------------------------
void wxGenericListCtrl::SetItemCount(long count)
{
wxASSERT_MSG( IsVirtual(), wxT("this is for virtual controls only") );
m_mainWin->SetItemCount(count);
}
void wxGenericListCtrl::RefreshItem(long item)
{
m_mainWin->RefreshLine(item);
}
void wxGenericListCtrl::RefreshItems(long itemFrom, long itemTo)
{
m_mainWin->RefreshLines(itemFrom, itemTo);
}
void wxGenericListCtrl::EnableBellOnNoMatch( bool on )
{
m_mainWin->EnableBellOnNoMatch(on);
}
// Generic wxListCtrl is more or less a container for two other
// windows which drawings are done upon. These are namely
// 'm_headerWin' and 'm_mainWin'.
// Here we override 'virtual wxWindow::Refresh()' to mimic the
// behaviour wxListCtrl has under wxMSW.
//
void wxGenericListCtrl::Refresh(bool eraseBackground, const wxRect *rect)
{
if (!rect)
{
// The easy case, no rectangle specified.
if (m_headerWin)
m_headerWin->Refresh(eraseBackground);
if (m_mainWin)
m_mainWin->Refresh(eraseBackground);
}
else
{
// Refresh the header window
if (m_headerWin)
{
wxRect rectHeader = m_headerWin->GetRect();
rectHeader.Intersect(*rect);
if (rectHeader.GetWidth() && rectHeader.GetHeight())
{
int x, y;
m_headerWin->GetPosition(&x, &y);
rectHeader.Offset(-x, -y);
m_headerWin->Refresh(eraseBackground, &rectHeader);
}
}
// Refresh the main window
if (m_mainWin)
{
wxRect rectMain = m_mainWin->GetRect();
rectMain.Intersect(*rect);
if (rectMain.GetWidth() && rectMain.GetHeight())
{
int x, y;
m_mainWin->GetPosition(&x, &y);
rectMain.Offset(-x, -y);
m_mainWin->Refresh(eraseBackground, &rectMain);
}
}
}
}
void wxGenericListCtrl::Update()
{
if ( m_mainWin )
{
if ( m_mainWin->m_dirty )
m_mainWin->RecalculatePositions();
m_mainWin->Update();
}
if ( m_headerWin )
m_headerWin->Update();
}
#endif // wxUSE_LISTCTRL
| ric2b/Vivaldi-browser | update_notifier/thirdparty/wxWidgets/src/generic/listctrl.cpp | C++ | bsd-3-clause | 169,842 |
---
title : AL
layout : datapage
permalink : /states/AL/
---
<a name="top"></a>
[Project Homepage]({{ site.baseurl}}/)
[AL-01](#AL-01) [AL-02](#AL-02) [AL-03](#AL-03) [AL-04](#AL-04) [AL-05](#AL-05) [AL-06](#AL-06) [AL-07](#AL-07)
# AL -- Sen. Richard C. Shelby (R) and Sen. Doug Jones (D)
## Committees
Richard C. Shelby is the #10 Republican on the Senate Appropriations Subcommittee on Commerce, Justice, Science, and Related Agencies
Richard C. Shelby is the #1 Republican on the Senate Committee on Appropriations
Richard C. Shelby is the #3 Republican on the Senate Appropriations Subcommittee on Energy and Water Development
## HEP Grants
In the past 9 years, this state has received:
17 HEP grants, totalling <b> $5,383,000</b>
```
Year Institution Amount ($)
------ ---------------------------------- ------------
2019 University of Alabama 674,000
2019 University of Alabama - Birmingham 348,000
2018 University of Alabama 666,000
2018 University of Alabama - Birmingham 345,000
2017 University of Alabama 653,000
2017 University of Alabama - Birmingham 367,000
2016 University of Alabama 485,000
2015 University of Alabama 585,000
2014 University of Alabama 505,000
2013 University of Alabama 275,000
2013 University of South Alabama 0
2012 University of Alabama 410,000
2012 University of South Alabama 70,000
```
## SC Contracts
```
This state received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this state has received:
209 NSF MPS grants, totalling <b> $37,628,106</b>
```
Institution Amount ($)
----------------------------------- ------------
University Of Alabama 10,937,975
Auburn University 9,396,709
University Of Alabama At Birmingham 8,853,090
Tuskegee University 3,861,873
University Of Alabama In Huntsville 1,482,872
Alabama A & M University 1,401,010
University Of South Alabama 697,471
University Of Alabama Birmingham 652,189
Alabama State University 271,535
University Of North Alabama 48,544
Troy University 24,838
```
## SULI/CCI Interns
<p align="center">

</p>
From 2014-2018, this state had 57 SULI/CCI interns
```
# Interns Program College
----------- --------- ----------------------------------------------
16 SULI Auburn University
12 SULI The University of Alabama
7 SULI University of Alabama at Birmingham
7 SULI University of Alabama in Huntsville
6 SULI Alabama Agricultural and Mechanical University
2 SULI Birmingham-Southern College
2 SULI Tuskegee University
1 CCI J.F. Drake State Technical College
1 SULI Alabama State University
1 SULI Auburn University at Montgomery
1 SULI Troy University
1 SULI University of South Alabama
```
57
---
---
<a name="AL-01"></a>
[Back to top](#top)
## AL-01 -- Rep. Bradley Byrne (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-01)
## HEP Grants
In the past 9 years, this district has received:<b> $70,000 </b>in SC HEP grants.
```
Institution Amount ($) Start End Principal Investigator Project Title
--------------------------- ------------ ------- ----- ------------------------ -------------------------------------------------------------------------------------------------------------------------------
University of South Alabama 70000 2012 2014 Jenkins Experimental High Energy Physics at the University of South Alabama: Request to Continue Activities for CMS, BaBaR and Belle II
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this district has received:<b> $697,471 </b>in NSF MPS grants.
```
Year Institution Amount ($)
------ --------------------------- ------------
2019 University Of South Alabama 72,471
2018 University Of South Alabama 330,000
2017 University Of South Alabama 10,000
2015 University Of South Alabama 285,000
```
## SULI/CCI Interns
From 2014-2018, this district had 1 SULI/CCI intern
```
Term Name College Host Lab Program
----------- --------------- --------------------------- ------------------------------ ---------
Summer 2016 Danielle Adamek University of South Alabama Brookhaven National Laboratory SULI
```
---
<a name="AL-02"></a>
[Back to top](#top)
## AL-02 -- Rep. Martha Roby (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-02)
## Committees
Martha Roby is the #2 Republican on the House Appropriations Subcommittee on Commerce, Justice, and Science
Martha Roby is the #16 Republican on the House Committee on Appropriations
## HEP Grants
```
This district received no SC HEP grants from 2012-2020
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this district has received:<b> $660,406 </b>in NSF MPS grants.
```
Year Institution Amount ($)
------ ------------------------ ------------
2019 Auburn University 226,211
2019 Troy University 18,621
2018 Troy University 6,217
2016 Alabama State University 271,535
2015 Auburn University 137,822
```
## SULI/CCI Interns
From 2014-2018, this district had 2 SULI/CCI interns
```
Term Name College Host Lab Program
----------- -------------------------- ------------------------------- -------------------------------------- ---------
Summer 2018 Ernest Sebastian Keola Lee Troy University Brookhaven National Laboratory SULI
Spring 2018 Manal Abdalla Auburn University at Montgomery Lawrence Livermore National Laboratory SULI
```
---
<a name="AL-03"></a>
[Back to top](#top)
## AL-03 -- Rep. Mike Rogers (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-03)
## HEP Grants
```
This district received no SC HEP grants from 2012-2020
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this district has received:<b> $12,894,549 </b>in NSF MPS grants.
```
Year Institution Amount ($)
------ ------------------- ------------
2020 Auburn University 128,291
2019 Auburn University 648,976
2019 Tuskegee University 425,000
2018 Auburn University 2,699,546
2018 Tuskegee University 1,288,750
2017 Auburn University 1,363,650
2017 Tuskegee University 778,449
2016 Auburn University 1,651,178
2015 Auburn University 315,492
2015 Tuskegee University 507,374
2014 Auburn University 1,132,896
2014 Tuskegee University 862,300
2013 Auburn University 587,586
2012 Auburn University 505,061
```
## SULI/CCI Interns
From 2014-2018, this district had 18 SULI/CCI interns
```
Term Name College Host Lab Program
----------- ------------------------- ------------------- ---------------------------------------------- ---------
Summer 2018 Jonathan Carroll Auburn University Thomas Jefferson National Accelerator Facility SULI
Summer 2018 Madeline Elizabeth Dueitt Auburn University Lawrence Berkeley National Laboratory SULI
Summer 2018 Justin Thomas Smith Auburn University Brookhaven National Laboratory SULI
Summer 2018 Kaitlyn Leigh Lawrence Auburn University Oak Ridge National Laboratory SULI
Summer 2018 Jonathan Henry Phillips Tuskegee University Lawrence Berkeley National Laboratory SULI
Summer 2018 Jonathan Andrew Gonzalez Auburn University Lawrence Berkeley National Laboratory SULI
Summer 2018 Haley Barone Alix Auburn University Brookhaven National Laboratory SULI
Summer 2017 Ayden Joseph Kish Auburn University Princeton Plasma Physics Laboratory SULI
Summer 2017 Eartha Leann Thompson Tuskegee University Oak Ridge National Laboratory SULI
Summer 2016 Matthew Barry Auburn University Princeton Plasma Physics Laboratory SULI
Summer 2016 Zechun Yang Auburn University Brookhaven National Laboratory SULI
Summer 2016 Matthew David Preisser Auburn University Pacific Northwest National Laboratory SULI
Summer 2015 Matthew Barry Auburn University SLAC National Accelerator Laboratory SULI
Summer 2014 Brittany Margaret Sipin Auburn University Oak Ridge National Laboratory SULI
Summer 2014 Robert Joseph Joseph Auburn University Oak Ridge National Laboratory SULI
Spring 2017 Jonathan Andrew Gonzalez Auburn University National Renewable Energy Laboratory SULI
Fall 2018 Elizabeth Prior Auburn University Oak Ridge National Laboratory SULI
Fall 2014 Daniel Dario Martinez Auburn University Lawrence Berkeley National Laboratory SULI
```
---
<a name="AL-04"></a>
[Back to top](#top)
## AL-04 -- Rep. Robert B. Aderholt (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-04)
## Committees
Robert B. Aderholt is the #1 Republican on the House Appropriations Subcommittee on Commerce, Justice, and Science
Robert B. Aderholt is the #3 Republican on the House Committee on Appropriations
## HEP Grants
```
This district received no SC HEP grants from 2012-2020
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
```
This district received no NSF MPS grants from 2012-2020
```
## SULI/CCI Interns
```
This district had no SULI/CCI interns from 2014-2018
```
---
<a name="AL-05"></a>
[Back to top](#top)
## AL-05 -- Rep. Mo Brooks (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-05)
## Committees
Mo Brooks is the #2 Republican on the House Committee on Science, Space, and Technology
## HEP Grants
```
This district received no SC HEP grants from 2012-2020
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this district has received:<b> $2,932,426 </b>in NSF MPS grants.
```
Year Institution Amount ($)
------ ----------------------------------- ------------
2020 University Of Alabama In Huntsville 35,000
2019 Alabama A & M University 45,000
2018 University Of Alabama In Huntsville 145,847
2018 Alabama A & M University 716,058
2017 University Of Alabama In Huntsville 588,304
2017 Alabama A & M University 137,431
2016 Alabama A & M University 124,741
2015 University Of Alabama In Huntsville 198,343
2015 Alabama A & M University 159,280
2014 University Of Alabama In Huntsville 60,172
2014 Alabama A & M University 89,000
2013 University Of North Alabama 29,430
2013 University Of Alabama In Huntsville 84,929
2013 Alabama A & M University 89,000
2012 University Of Alabama In Huntsville 370,277
2012 University Of North Alabama 19,114
2012 Alabama A & M University 40,500
```
## SULI/CCI Interns
From 2014-2018, this district had 14 SULI/CCI interns
```
Term Name College Host Lab Program
----------- -------------------- ---------------------------------------------- ------------------------------ ---------
Summer 2018 Jacob Kunisch University of Alabama in Huntsville Argonne National Laboratory SULI
Summer 2017 Lauren Walker Alabama Agricultural and Mechanical University Oak Ridge National Laboratory SULI
Summer 2017 Derek Mitchell University of Alabama in Huntsville Oak Ridge National Laboratory SULI
Summer 2017 Tiia Vesalainen University of Alabama in Huntsville Oak Ridge National Laboratory SULI
Summer 2016 Rachel Sanders Alabama Agricultural and Mechanical University Brookhaven National Laboratory SULI
Summer 2016 Lauren Walker Alabama Agricultural and Mechanical University Brookhaven National Laboratory SULI
Summer 2016 William Blake Hawley University of Alabama in Huntsville Oak Ridge National Laboratory SULI
Summer 2015 Renee Chan University of Alabama in Huntsville Brookhaven National Laboratory SULI
Summer 2014 john mwathi Alabama Agricultural and Mechanical University Brookhaven National Laboratory SULI
Summer 2014 Michael Avery Knotts Alabama Agricultural and Mechanical University Oak Ridge National Laboratory SULI
Summer 2014 Shaun Perryman J.F. Drake State Technical College Oak Ridge National Laboratory CCI
Spring 2016 Daniel Smallwood University of Alabama in Huntsville Oak Ridge National Laboratory SULI
Spring 2015 William Blake Hawley University of Alabama in Huntsville Oak Ridge National Laboratory SULI
Spring 2014 Belther Monono Alabama Agricultural and Mechanical University Oak Ridge National Laboratory SULI
```
---
<a name="AL-06"></a>
[Back to top](#top)
## AL-06 -- Rep. Gary J. Palmer (R) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-06)
## HEP Grants
```
This district received no SC HEP grants from 2012-2020
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
```
This district received no NSF MPS grants from 2012-2020
```
## SULI/CCI Interns
From 2014-2018, this district had 7 SULI/CCI interns
```
Term Name College Host Lab Program
----------- ------------------------ ----------------------------------- ------------------------------------- ---------
Summer 2018 Karly Casey University of Alabama at Birmingham Brookhaven National Laboratory SULI
Summer 2017 Joanna Schmidt University of Alabama at Birmingham Los Alamos National Laboratory SULI
Summer 2016 Kristina Celeste Fong University of Alabama at Birmingham Brookhaven National Laboratory SULI
Summer 2016 Aidan O'beirne University of Alabama at Birmingham Los Alamos National Laboratory SULI
Summer 2015 Kristina Celeste Fong University of Alabama at Birmingham Brookhaven National Laboratory SULI
Summer 2015 Luke Mitchell McClintock University of Alabama at Birmingham Los Alamos National Laboratory SULI
Spring 2016 Joshua Josiah Pritchett University of Alabama at Birmingham Lawrence Berkeley National Laboratory SULI
```
---
<a name="AL-07"></a>
[Back to top](#top)
## AL-07 -- Rep. Terri A. Sewell (D) -- [Wikipedia](https://en.wikipedia.org/wiki/AL-07)
## HEP Grants
In the past 9 years, this district has received:<b> $5,313,000 </b>in SC HEP grants.
```
Institution Amount ($) Start End Principal Investigator Project Title
---------------------------------- ------------ ------- ----- ------------------------ ------------------------------------------------------------------------------------------------------
University of Alabama - Birmingham 1,060,000 2017 2020 Mirov, Sergey Novel, Middle and Long Wave Infrared Lasers For Particle Accelerator and X-ray Generation Applications
University of Alabama 120,000 2015 2017 Okada, Nobuchika Research in Theoretical High Energy Physics
University of Alabama 3,448,000 2014 2020 Busenitz, Jerome Research in Elementary Particle Physics
University of Alabama 635,000 2012 2014 Busenitz Research in Neutrino Physics
University of Alabama 50,000 2012 2013 Okada Research in Theoretical High Energy Physics
```
## SC Contracts
```
This district received no SC contracts from 2012-2020
```
## NSF MPS Grants
In the past 9 years, this district has received:<b> $20,443,254 </b>in NSF MPS grants.
```
Year Institution Amount ($)
------ ----------------------------------- ------------
2020 University Of Alabama 369,288
2019 University Of Alabama At Birmingham 1,878,743
2019 University Of Alabama 1,417,487
2018 University Of Alabama At Birmingham 1,170,762
2018 University Of Alabama 1,497,759
2017 University Of Alabama At Birmingham 1,083,885
2017 University Of Alabama 541,526
2016 University Of Alabama At Birmingham 1,772,912
2016 University Of Alabama 653,761
2015 University Of Alabama Birmingham 652,189
2015 University Of Alabama At Birmingham 771,862
2015 University Of Alabama 1,517,934
2014 University Of Alabama At Birmingham 711,592
2014 University Of Alabama 1,134,870
2013 University Of Alabama At Birmingham 753,080
2013 University Of Alabama 1,600,098
2012 University Of Alabama At Birmingham 710,254
2012 University Of Alabama 2,205,252
```
## SULI/CCI Interns
From 2014-2018, this district had 15 SULI/CCI interns
```
Term Name College Host Lab Program
----------- ---------------------------- --------------------------- ------------------------------------- ---------
Summer 2018 Zach Macintyre The University of Alabama Oak Ridge National Laboratory SULI
Summer 2018 Margot Blaire Woolverton Birmingham-Southern College Oak Ridge National Laboratory SULI
Summer 2017 Daryl Lakner The University of Alabama Argonne National Laboratory SULI
Summer 2016 Travis Taylor The University of Alabama Oak Ridge National Laboratory SULI
Summer 2016 Emma Clements The University of Alabama National Renewable Energy Laboratory SULI
Summer 2016 Matthew Fister The University of Alabama Los Alamos National Laboratory SULI
Summer 2015 Zachary Thane Thompson The University of Alabama Oak Ridge National Laboratory SULI
Summer 2014 Laurel Johnson The University of Alabama Argonne National Laboratory SULI
Summer 2014 Barry Clay Burrows The University of Alabama Oak Ridge National Laboratory SULI
Summer 2014 Trisha D. Handley Alabama State University Ames National Laboratory SULI
Summer 2014 Jake Farell The University of Alabama Savannah River National Laboratory SULI
Spring 2015 Marissa Amey Jenness Leshnov The University of Alabama National Renewable Energy Laboratory SULI
Fall 2018 Jared Horner The University of Alabama Oak Ridge National Laboratory SULI
Fall 2015 Kaitlyn Leigh Somazze The University of Alabama Idaho National Laboratory SULI
Fall 2014 Huda Qureshi Birmingham-Southern College Lawrence Berkeley National Laboratory SULI
```
---
| mbaumer/us_hep_funding | docs/_states/AL.md | Markdown | bsd-3-clause | 20,416 |
{-|
Module : Reactive.DOM.Children.MonotoneList
Description : Definition of the MonotoneList children container.
Copyright : (c) Alexander Vieth, 2016
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Reactive.DOM.Children.MonotoneList where
import Data.Semigroup
import Data.Functor.Compose
import Reactive.DOM.Internal.ChildrenContainer
import Reactive.DOM.Internal.Mutation
newtype MonotoneList t inp out f = MonotoneList {
runMonotoneList :: [f t]
}
deriving instance Semigroup (MonotoneList t inp out f)
deriving instance Monoid (MonotoneList t inp out f)
instance FunctorTransformer (MonotoneList inp out t) where
functorTrans trans (MonotoneList fts) = MonotoneList (trans <$> fts)
functorCommute (MonotoneList fts) = MonotoneList <$> sequenceA (getCompose <$> fts)
instance ChildrenContainer (MonotoneList inp out t) where
type Change (MonotoneList t inp out) = MonotoneList t inp out
getChange get (MonotoneList news) (MonotoneList olds) =
let nextList = MonotoneList (olds <> news)
mutations = AppendChild . get <$> news
in (nextList, mutations)
childrenContainerList get (MonotoneList ts) = get <$> ts
| avieth/reactive-dom | Reactive/DOM/Children/MonotoneList.hs | Haskell | bsd-3-clause | 1,438 |
//=============================================================================
/**
* @file main.cpp
*
* This is the main program - it just hands control off to the
* process instance to figure out what to do. This program only
* runs on Win32.
*
* @author Gonzalo Diethelm <gonzo@cs.wustl.edu> and Steve Huston <shuston@riverace.com>
*/
//=============================================================================
#include "ace/Get_Opt.h"
#include "ace/Init_ACE.h"
#include "ntsvc.h"
#if defined (ACE_WIN32) && !defined (ACE_LACKS_WIN32_SERVICES)
// FUZZ: disable check_for_streams_include
#include "ace/streams.h"
#include "ace/OS_NS_errno.h"
// Default for the -i (install) option
#define DEFAULT_SERVICE_INIT_STARTUP SERVICE_AUTO_START
class Process
{
public:
Process (void);
~Process (void);
int run(int argc, ACE_TCHAR* argv[]);
private:
void parse_args (int argc,
ACE_TCHAR* argv[]);
void print_usage_and_die (void);
private:
char progname[128];
int opt_install;
int opt_remove;
int opt_start;
int opt_kill;
int opt_type;
int opt_debug;
int opt_startup;
};
typedef ACE_Singleton<Process, ACE_Mutex> PROCESS;
Process::Process (void)
: opt_install (0),
opt_remove (0),
opt_start (0),
opt_kill (0),
opt_type (0),
opt_debug (0),
opt_startup (0)
{
ACE_OS::strcpy (progname,
"service");
ACE::init ();
}
Process::~Process (void)
{
ACE::fini ();
}
void
Process::print_usage_and_die (void)
{
ACE_DEBUG ((LM_INFO,
"Usage: %s"
" -in -r -s -k -tn -d\n"
" -i: Install this program as an NT service, with specified startup\n"
" -r: Remove this program from the Service Manager\n"
" -s: Start the service\n"
" -k: Kill the service\n"
" -t: Set startup for an existing service\n"
" -d: Debug; run as a regular application\n",
progname,
0));
ACE_OS::exit(1);
}
void
Process::parse_args (int argc, ACE_TCHAR* argv[])
{
ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("i:rskt:d"));
int c;
while ((c = get_opt ()) != -1)
switch (c)
{
case 'i':
opt_install = 1;
opt_startup = ACE_OS::atoi (get_opt.opt_arg ());
if (opt_startup <= 0)
print_usage_and_die ();
break;
case 'r':
opt_remove = 1;
break;
case 's':
opt_start = 1;
break;
case 'k':
opt_kill = 1;
break;
case 't':
opt_type = 1;
opt_startup = ACE_OS::atoi (get_opt.opt_arg ());
if (opt_startup <= 0)
print_usage_and_die ();
break;
case 'd':
opt_debug = 1;
break;
default:
// -i can also be given without a value - if so, it defaults
// to defined value.
if (ACE_OS::strcmp (get_opt.argv ()[get_opt.opt_ind () - 1], ACE_TEXT ("-i")) == 0)
{
opt_install = 1;
opt_startup = DEFAULT_SERVICE_INIT_STARTUP;
}
else
{
print_usage_and_die ();
}
break;
}
}
// Define a function to handle Ctrl+C to cleanly shut this down.
static BOOL WINAPI
ConsoleHandler (DWORD /*ctrlType*/)
{
SERVICE::instance ()->handle_control (SERVICE_CONTROL_STOP);
return TRUE;
}
ACE_NT_SERVICE_DEFINE (Beeper,
Service,
ACE_TEXT ("Annoying Beeper Service"));
int
Process::run (int argc, ACE_TCHAR* argv[])
{
SERVICE::instance ()->name (ACE_TEXT ("Beeper"),
ACE_TEXT ("Annoying Beeper Service"));
parse_args (argc, argv);
if (opt_install && !opt_remove)
{
if (-1 == SERVICE::instance ()->insert (opt_startup))
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("insert")));
return -1;
}
return 0;
}
if (opt_remove && !opt_install)
{
if (-1 == SERVICE::instance ()->remove ())
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("remove")));
return -1;
}
return 0;
}
if (opt_start && opt_kill)
print_usage_and_die ();
if (opt_start)
{
if (-1 == SERVICE::instance ()->start_svc ())
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("start")));
return -1;
}
return 0;
}
if (opt_kill)
{
if (-1 == SERVICE::instance ()->stop_svc ())
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("stop")));
return -1;
}
return 0;
}
if (opt_type)
{
if (-1 == SERVICE::instance ()->startup (opt_startup))
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("set startup")));
return -1;
}
return 0;
}
// If we get here, we either run the app in debug mode (-d) or are
// being called from the service manager to start the service.
if (opt_debug)
{
SetConsoleCtrlHandler (&ConsoleHandler, 1);
SERVICE::instance ()->svc ();
}
else
{
ofstream *output_file = new ofstream("ntsvc.log", ios::out);
if (output_file && output_file->rdstate() == ios::goodbit)
ACE_LOG_MSG->msg_ostream(output_file, 1);
ACE_LOG_MSG->open(argv[0],
ACE_Log_Msg::STDERR | ACE_Log_Msg::OSTREAM,
0);
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%T (%t): Starting service.\n")));
ACE_NT_SERVICE_RUN (Beeper,
SERVICE::instance (),
ret);
if (ret == 0)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("Couldn't start service")));
else
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%T (%t): Service stopped.\n")));
}
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR* argv[])
{
return PROCESS::instance ()->run (argc, argv);
}
#else
#include "ace/OS_main.h"
int
ACE_TMAIN (int, ACE_TCHAR*[])
{
// This program needs Windows services.
return 0;
}
#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_SERVICES */
| wfnex/openbras | src/ace/ACE_wrappers/examples/NT_Service/main.cpp | C++ | bsd-3-clause | 6,097 |
# 2012-04-09
## Reviewed by: your_name_here
## Raw image gallery: http://physics.mnstate.edu/feder_gallery/2012-04-09
## Unusual images?
Are there any images that look unusual? List the file name of any unusual images for this night here, with description:
+ `crazy-object-001R.fit` -- not sure what this is an image of
+ `another-crazy-object-003B.fit` -- this looks more like a flat than a science image.
+ `full-moon-005B.fit` -- nice satellite or plane track in here.
Delete this list if there are no unusual images.
## Missing information?
Check these off if they are true:
- [ ] No images are missing filter information (except BIAS and DARK, which need no filter).
- [ ] No images are missing pointing information (RA/Dec and WCS)
- [ ] No images are missing object names (only applies to science images)
- [x] EXAMPLE checked-off box, please delete.
If any images are missing information and you have been unable to fix them please list
them below with a short description of the problem.
+ `m34-002R.fit` -- no WCS, looks like there were maybe clouds.
+ `m404-001B.fit` -- Not sure what object this, and googling `m404` got me a 404.
+ `sa113-099V.fit` -- No filter in the FITS header, not sure what it should be.
## What, if anything, did you have to do to fix images on this night?
Remember, you should do your changes with scripts that you number and place in the
directory along with the data so the procedure could be repeated if needed or
desired.
Here, explain in English (not code) what you fixed, if anything.
| feder-observatory/processed_images | nights/2012-04-09-README.md | Markdown | bsd-3-clause | 1,544 |
/*
* Copyright © 2009 CNRS
* Copyright © 2009-2010 INRIA. All rights reserved.
* Copyright © 2009-2011 Université Bordeaux 1
* Copyright © 2011 Cisco Systems, Inc. All rights reserved.
* See COPYING in top-level directory.
*/
/** \file
* \brief Macros to help interaction between hwloc and glibc scheduling routines.
*
* Applications that use both hwloc and glibc scheduling routines such as
* sched_getaffinity may want to include this file so as to ease conversion
* between their respective types.
*/
#ifndef HWLOC_GLIBC_SCHED_H
#define HWLOC_GLIBC_SCHED_H
#include <hwloc.h>
#include <hwloc/helper.h>
#include <assert.h>
#if !defined _GNU_SOURCE || !defined _SCHED_H || !defined CPU_SETSIZE
#error Please make sure to include sched.h before including glibc-sched.h, and define _GNU_SOURCE before any inclusion of sched.h
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HWLOC_HAVE_CPU_SET
/** \defgroup hwlocality_glibc_sched Helpers for manipulating glibc sched affinity
* @{
*/
/** \brief Convert hwloc CPU set \p toposet into glibc sched affinity CPU set \p schedset
*
* This function may be used before calling sched_setaffinity or any other function
* that takes a cpu_set_t as input parameter.
*
* \p schedsetsize should be sizeof(cpu_set_t) unless \p schedset was dynamically allocated with CPU_ALLOC
*/
static __hwloc_inline int
hwloc_cpuset_to_glibc_sched_affinity(hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t hwlocset,
cpu_set_t *schedset, size_t schedsetsize)
{
#ifdef CPU_ZERO_S
unsigned cpu;
CPU_ZERO_S(schedsetsize, schedset);
hwloc_bitmap_foreach_begin(cpu, hwlocset)
CPU_SET_S(cpu, schedsetsize, schedset);
hwloc_bitmap_foreach_end();
#else /* !CPU_ZERO_S */
unsigned cpu;
CPU_ZERO(schedset);
assert(schedsetsize == sizeof(cpu_set_t));
hwloc_bitmap_foreach_begin(cpu, hwlocset)
CPU_SET(cpu, schedset);
hwloc_bitmap_foreach_end();
#endif /* !CPU_ZERO_S */
return 0;
}
/** \brief Convert glibc sched affinity CPU set \p schedset into hwloc CPU set
*
* This function may be used before calling sched_setaffinity or any other function
* that takes a cpu_set_t as input parameter.
*
* \p schedsetsize should be sizeof(cpu_set_t) unless \p schedset was dynamically allocated with CPU_ALLOC
*/
static __hwloc_inline int
hwloc_cpuset_from_glibc_sched_affinity(hwloc_topology_t topology __hwloc_attribute_unused, hwloc_cpuset_t hwlocset,
const cpu_set_t *schedset, size_t schedsetsize)
{
#ifdef CPU_ZERO_S
int cpu, count;
#endif
hwloc_bitmap_zero(hwlocset);
#ifdef CPU_ZERO_S
count = CPU_COUNT_S(schedsetsize, schedset);
cpu = 0;
while (count) {
if (CPU_ISSET_S(cpu, schedsetsize, schedset)) {
hwloc_bitmap_set(hwlocset, cpu);
count--;
}
cpu++;
}
#else /* !CPU_ZERO_S */
/* sched.h does not support dynamic cpu_set_t (introduced in glibc 2.7),
* assume we have a very old interface without CPU_COUNT (added in 2.6)
*/
int cpu;
assert(schedsetsize == sizeof(cpu_set_t));
for(cpu=0; cpu<CPU_SETSIZE; cpu++)
if (CPU_ISSET(cpu, schedset))
hwloc_bitmap_set(hwlocset, cpu);
#endif /* !CPU_ZERO_S */
return 0;
}
/** @} */
#endif /* CPU_SET */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* HWLOC_GLIBC_SCHED_H */
| gnu3ra/SCC15HPCRepast | INSTALLATION/mpich2-1.4.1p1/src/pm/hydra/tools/topo/hwloc/hwloc/include/hwloc/glibc-sched.h | C | bsd-3-clause | 3,349 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "bindings/core/v8/ScriptStreamer.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "bindings/core/v8/V8ScriptRunner.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/PendingScript.h"
#include "core/fetch/ScriptResource.h"
#include "core/frame/Settings.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "platform/SharedBuffer.h"
#include "platform/TraceEvent.h"
#include "public/platform/Platform.h"
#include "wtf/MainThread.h"
#include "wtf/text/TextEncodingRegistry.h"
namespace blink {
namespace {
const char* kHistogramName = "WebCore.Scripts.Async.StartedStreaming";
}
// For passing data between the main thread (producer) and the streamer thread
// (consumer). The main thread prepares the data (copies it from Resource) and
// the streamer thread feeds it to V8.
class SourceStreamDataQueue {
WTF_MAKE_NONCOPYABLE(SourceStreamDataQueue);
public:
SourceStreamDataQueue()
: m_finished(false) { }
~SourceStreamDataQueue()
{
while (!m_data.isEmpty()) {
std::pair<const uint8_t*, size_t> next_data = m_data.takeFirst();
delete[] next_data.first;
}
}
void produce(const uint8_t* data, size_t length)
{
MutexLocker locker(m_mutex);
m_data.append(std::make_pair(data, length));
m_haveData.signal();
}
void finish()
{
MutexLocker locker(m_mutex);
m_finished = true;
m_haveData.signal();
}
void consume(const uint8_t** data, size_t* length)
{
MutexLocker locker(m_mutex);
while (!tryGetData(data, length))
m_haveData.wait(m_mutex);
}
private:
bool tryGetData(const uint8_t** data, size_t* length)
{
if (!m_data.isEmpty()) {
std::pair<const uint8_t*, size_t> next_data = m_data.takeFirst();
*data = next_data.first;
*length = next_data.second;
return true;
}
if (m_finished) {
*length = 0;
return true;
}
return false;
}
WTF::Deque<std::pair<const uint8_t*, size_t>> m_data;
bool m_finished;
Mutex m_mutex;
ThreadCondition m_haveData;
};
// SourceStream implements the streaming interface towards V8. The main
// functionality is preparing the data to give to V8 on main thread, and
// actually giving the data (via GetMoreData which is called on a background
// thread).
class SourceStream : public v8::ScriptCompiler::ExternalSourceStream {
WTF_MAKE_NONCOPYABLE(SourceStream);
public:
SourceStream()
: v8::ScriptCompiler::ExternalSourceStream()
, m_cancelled(false)
, m_dataPosition(0) { }
virtual ~SourceStream() { }
// Called by V8 on a background thread. Should block until we can return
// some data.
virtual size_t GetMoreData(const uint8_t** src) override
{
ASSERT(!isMainThread());
{
MutexLocker locker(m_mutex);
if (m_cancelled)
return 0;
}
size_t length = 0;
// This will wait until there is data.
m_dataQueue.consume(src, &length);
{
MutexLocker locker(m_mutex);
if (m_cancelled)
return 0;
}
return length;
}
void didFinishLoading()
{
ASSERT(isMainThread());
m_dataQueue.finish();
}
void didReceiveData(ScriptStreamer* streamer, size_t lengthOfBOM)
{
ASSERT(isMainThread());
prepareDataOnMainThread(streamer, lengthOfBOM);
}
void cancel()
{
ASSERT(isMainThread());
// The script is no longer needed by the upper layers. Stop streaming
// it. The next time GetMoreData is called (or woken up), it will return
// 0, which will be interpreted as EOS by V8 and the parsing will
// fail. ScriptStreamer::streamingComplete will be called, and at that
// point we will release the references to SourceStream.
{
MutexLocker locker(m_mutex);
m_cancelled = true;
}
m_dataQueue.finish();
}
private:
void prepareDataOnMainThread(ScriptStreamer* streamer, size_t lengthOfBOM)
{
ASSERT(isMainThread());
// The Resource must still be alive; otherwise we should've cancelled
// the streaming (if we have cancelled, the background thread is not
// waiting).
ASSERT(streamer->resource());
// BOM can only occur at the beginning of the data.
ASSERT(lengthOfBOM == 0 || m_dataPosition == 0);
CachedMetadataHandler* cacheHandler = streamer->resource()->cacheHandler();
if (cacheHandler && cacheHandler->cachedMetadata(V8ScriptRunner::tagForCodeCache(cacheHandler))) {
// The resource has a code cache, so it's unnecessary to stream and
// parse the code. Cancel the streaming and resume the non-streaming
// code path.
streamer->suppressStreaming();
{
MutexLocker locker(m_mutex);
m_cancelled = true;
}
m_dataQueue.finish();
return;
}
if (!m_resourceBuffer) {
// We don't have a buffer yet. Try to get it from the resource.
SharedBuffer* buffer = streamer->resource()->resourceBuffer();
m_resourceBuffer = RefPtr<SharedBuffer>(buffer);
}
// Get as much data from the ResourceBuffer as we can.
const char* data = 0;
Vector<const char*> chunks;
Vector<unsigned> chunkLengths;
size_t dataLength = 0;
while (unsigned length = m_resourceBuffer->getSomeData(data, m_dataPosition)) {
// FIXME: Here we can limit based on the total length, if it turns
// out that we don't want to give all the data we have (memory
// vs. speed).
chunks.append(data);
chunkLengths.append(length);
dataLength += length;
m_dataPosition += length;
}
// Copy the data chunks into a new buffer, since we're going to give the
// data to a background thread.
if (dataLength > lengthOfBOM) {
dataLength -= lengthOfBOM;
uint8_t* copiedData = new uint8_t[dataLength];
unsigned offset = 0;
for (size_t i = 0; i < chunks.size(); ++i) {
memcpy(copiedData + offset, chunks[i] + lengthOfBOM, chunkLengths[i] - lengthOfBOM);
offset += chunkLengths[i] - lengthOfBOM;
// BOM is only in the first chunk
lengthOfBOM = 0;
}
m_dataQueue.produce(copiedData, dataLength);
}
}
// For coordinating between the main thread and background thread tasks.
// Guarded by m_mutex.
bool m_cancelled;
Mutex m_mutex;
unsigned m_dataPosition; // Only used by the main thread.
RefPtr<SharedBuffer> m_resourceBuffer; // Only used by the main thread.
SourceStreamDataQueue m_dataQueue; // Thread safe.
};
size_t ScriptStreamer::kSmallScriptThreshold = 30 * 1024;
void ScriptStreamer::startStreaming(PendingScript& script, Settings* settings, ScriptState* scriptState)
{
// We don't yet know whether the script will really be streamed. E.g.,
// suppressing streaming for short scripts is done later. Record only the
// sure negative cases here.
bool startedStreaming = startStreamingInternal(script, settings, scriptState);
if (!startedStreaming)
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
}
bool ScriptStreamer::convertEncoding(const char* encodingName, v8::ScriptCompiler::StreamedSource::Encoding* encoding)
{
// Here's a list of encodings we can use for streaming. These are
// the canonical names.
if (strcmp(encodingName, "windows-1252") == 0
|| strcmp(encodingName, "ISO-8859-1") == 0
|| strcmp(encodingName, "US-ASCII") == 0) {
*encoding = v8::ScriptCompiler::StreamedSource::ONE_BYTE;
return true;
}
if (strcmp(encodingName, "UTF-8") == 0) {
*encoding = v8::ScriptCompiler::StreamedSource::UTF8;
return true;
}
// We don't stream other encodings; especially we don't stream two
// byte scripts to avoid the handling of endianness. Most scripts
// are Latin1 or UTF-8 anyway, so this should be enough for most
// real world purposes.
return false;
}
void ScriptStreamer::streamingCompleteOnBackgroundThread()
{
ASSERT(!isMainThread());
MutexLocker locker(m_mutex);
m_parsingFinished = true;
// notifyFinished might already be called, or it might be called in the
// future (if the parsing finishes earlier because of a parse error).
callOnMainThread(WTF::bind(&ScriptStreamer::streamingComplete, this));
}
void ScriptStreamer::cancel()
{
ASSERT(isMainThread());
// The upper layer doesn't need the script any more, but streaming might
// still be ongoing. Tell SourceStream to try to cancel it whenever it gets
// the control the next time. It can also be that V8 has already completed
// its operations and streamingComplete will be called soon.
m_detached = true;
m_resource = 0;
if (m_stream)
m_stream->cancel();
}
void ScriptStreamer::suppressStreaming()
{
MutexLocker locker(m_mutex);
ASSERT(!m_loadingFinished);
// It can be that the parsing task has already finished (e.g., if there was
// a parse error).
m_streamingSuppressed = true;
}
void ScriptStreamer::notifyAppendData(ScriptResource* resource)
{
ASSERT(isMainThread());
ASSERT(m_resource == resource);
{
MutexLocker locker(m_mutex);
if (m_streamingSuppressed)
return;
}
size_t lengthOfBOM = 0;
if (!m_haveEnoughDataForStreaming) {
// Even if the first data chunk is small, the script can still be big
// enough - wait until the next data chunk comes before deciding whether
// to start the streaming.
ASSERT(resource->resourceBuffer());
if (resource->resourceBuffer()->size() < kSmallScriptThreshold)
return;
m_haveEnoughDataForStreaming = true;
// Encoding should be detected only when we have some data. It's
// possible that resource->encoding() returns a different encoding
// before the loading has started and after we got some data. In
// addition, check for byte order marks. Note that checking the byte
// order mark might change the encoding. We cannot decode the full text
// here, because it might contain incomplete UTF-8 characters. Also note
// that have at least kSmallScriptThreshold worth of data, which is more
// than enough for detecting a BOM.
const char* data = 0;
unsigned length = resource->resourceBuffer()->getSomeData(data, 0);
OwnPtr<TextResourceDecoder> decoder(TextResourceDecoder::create("application/javascript", resource->encoding()));
lengthOfBOM = decoder->checkForBOM(data, length);
// Maybe the encoding changed because we saw the BOM; get the encoding
// from the decoder.
if (!convertEncoding(decoder->encoding().name(), &m_encoding)) {
suppressStreaming();
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
return;
}
if (ScriptStreamerThread::shared()->isRunningTask()) {
// At the moment we only have one thread for running the tasks. A
// new task shouldn't be queued before the running task completes,
// because the running task can block and wait for data from the
// network.
suppressStreaming();
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
return;
}
if (!m_scriptState->contextIsValid()) {
suppressStreaming();
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
return;
}
ASSERT(!m_stream);
ASSERT(!m_source);
m_stream = new SourceStream();
// m_source takes ownership of m_stream.
m_source = adoptPtr(new v8::ScriptCompiler::StreamedSource(m_stream, m_encoding));
ScriptState::Scope scope(m_scriptState.get());
WTF::OwnPtr<v8::ScriptCompiler::ScriptStreamingTask> scriptStreamingTask(adoptPtr(v8::ScriptCompiler::StartStreamingScript(m_scriptState->isolate(), m_source.get(), m_compileOptions)));
if (!scriptStreamingTask) {
// V8 cannot stream the script.
suppressStreaming();
m_stream = 0;
m_source.clear();
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
return;
}
// ScriptStreamer needs to stay alive as long as the background task is
// running. This is taken care of with a manual ref() & deref() pair;
// the corresponding deref() is in streamingComplete.
ref();
ScriptStreamingTask* task = new ScriptStreamingTask(scriptStreamingTask.release(), this);
ScriptStreamerThread::shared()->postTask(task);
blink::Platform::current()->histogramEnumeration(kHistogramName, 1, 2);
}
if (m_stream)
m_stream->didReceiveData(this, lengthOfBOM);
}
void ScriptStreamer::notifyFinished(Resource* resource)
{
ASSERT(isMainThread());
ASSERT(m_resource == resource);
// A special case: empty and small scripts. We didn't receive enough data to
// start the streaming before this notification. In that case, there won't
// be a "parsing complete" notification either, and we should not wait for
// it.
if (!m_haveEnoughDataForStreaming) {
blink::Platform::current()->histogramEnumeration(kHistogramName, 0, 2);
suppressStreaming();
}
if (m_stream)
m_stream->didFinishLoading();
m_loadingFinished = true;
// Calling notifyFinishedToClient can result into the upper layers dropping
// references to ScriptStreamer. Keep it alive until this function ends.
RefPtrWillBeRawPtr<ScriptStreamer> protect(this);
notifyFinishedToClient();
}
ScriptStreamer::ScriptStreamer(ScriptResource* resource, ScriptState* scriptState, v8::ScriptCompiler::CompileOptions compileOptions)
: m_resource(resource)
, m_detached(false)
, m_stream(0)
, m_client(0)
, m_loadingFinished(false)
, m_parsingFinished(false)
, m_haveEnoughDataForStreaming(false)
, m_streamingSuppressed(false)
, m_compileOptions(compileOptions)
, m_scriptState(scriptState)
, m_encoding(v8::ScriptCompiler::StreamedSource::TWO_BYTE) // Unfortunately there's no dummy encoding value in the enum; let's use one we don't stream.
{
}
ScriptStreamer::~ScriptStreamer()
{
}
void ScriptStreamer::trace(Visitor* visitor)
{
visitor->trace(m_resource);
}
void ScriptStreamer::streamingComplete()
{
// The background task is completed; do the necessary ramp-down in the main
// thread.
ASSERT(isMainThread());
// It's possible that the corresponding Resource was deleted before V8
// finished streaming. In that case, the data or the notification is not
// needed. In addition, if the streaming is suppressed, the non-streaming
// code path will resume after the resource has loaded, before the
// background task finishes.
if (m_detached || m_streamingSuppressed) {
deref();
return;
}
// We have now streamed the whole script to V8 and it has parsed the
// script. We're ready for the next step: compiling and executing the
// script.
notifyFinishedToClient();
// The background thread no longer holds an implicit reference.
deref();
}
void ScriptStreamer::notifyFinishedToClient()
{
ASSERT(isMainThread());
// Usually, the loading will be finished first, and V8 will still need some
// time to catch up. But the other way is possible too: if V8 detects a
// parse error, the V8 side can complete before loading has finished. Send
// the notification after both loading and V8 side operations have
// completed. Here we also check that we have a client: it can happen that a
// function calling notifyFinishedToClient was already scheduled in the task
// queue and the upper layer decided that it's not interested in the script
// and called removeClient.
{
MutexLocker locker(m_mutex);
if (!isFinished())
return;
}
if (m_client)
m_client->notifyFinished(m_resource);
}
bool ScriptStreamer::startStreamingInternal(PendingScript& script, Settings* settings, ScriptState* scriptState)
{
ASSERT(isMainThread());
ScriptResource* resource = script.resource();
if (resource->isLoaded())
return false;
if (!resource->url().protocolIsInHTTPFamily())
return false;
if (resource->resourceToRevalidate()) {
// This happens e.g., during reloads. We're actually not going to load
// the current Resource of the PendingScript but switch to another
// Resource -> don't stream.
return false;
}
// We cannot filter out short scripts, even if we wait for the HTTP headers
// to arrive: the Content-Length HTTP header is not sent for chunked
// downloads.
if (!scriptState->contextIsValid())
return false;
// Decide what kind of cached data we should produce while streaming. By
// default, we generate the parser cache for streamed scripts, to emulate
// the non-streaming behavior (see V8ScriptRunner::compileScript).
v8::ScriptCompiler::CompileOptions compileOption = v8::ScriptCompiler::kProduceParserCache;
if (settings->v8CacheOptions() == V8CacheOptionsCode || settings->v8CacheOptions() == V8CacheOptionsCodeCompressed)
compileOption = v8::ScriptCompiler::kProduceCodeCache;
// The Resource might go out of scope if the script is no longer
// needed. This makes PendingScript notify the ScriptStreamer when it is
// destroyed.
script.setStreamer(ScriptStreamer::create(resource, scriptState, compileOption));
return true;
}
} // namespace blink
| CTSRD-SOAAP/chromium-42.0.2311.135 | third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.cpp | C++ | bsd-3-clause | 18,525 |
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('entries', '0005_resultsmode_json'),
]
operations = [
migrations.AlterField(
model_name='resultsmode',
name='json',
field=models.TextField(default='', blank=True),
),
]
| mjtamlyn/archery-scoring | entries/migrations/0006_auto_20150612_2307.py | Python | bsd-3-clause | 372 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/device_sensors/sensor_manager_android.h"
#include <string.h>
#include "base/android/context_utils.h"
#include "base/android/jni_android.h"
#include "base/bind.h"
#include "base/memory/singleton.h"
#include "base/metrics/histogram.h"
#include "content/public/browser/browser_thread.h"
#include "jni/DeviceSensors_jni.h"
using base::android::AttachCurrentThread;
using base::android::JavaParamRef;
namespace {
void UpdateDeviceOrientationHistogram(
content::SensorManagerAndroid::OrientationSensorType type) {
UMA_HISTOGRAM_ENUMERATION("InertialSensor.DeviceOrientationSensorAndroid",
type, content::SensorManagerAndroid::ORIENTATION_SENSOR_MAX);
}
void SetOrientation(content::DeviceOrientationHardwareBuffer* buffer,
double alpha, double beta, double gamma) {
buffer->seqlock.WriteBegin();
buffer->data.alpha = alpha;
buffer->data.hasAlpha = true;
buffer->data.beta = beta;
buffer->data.hasBeta = true;
buffer->data.gamma = gamma;
buffer->data.hasGamma = true;
buffer->seqlock.WriteEnd();
}
void SetOrientationBufferStatus(
content::DeviceOrientationHardwareBuffer* buffer,
bool ready, bool absolute) {
buffer->seqlock.WriteBegin();
buffer->data.absolute = absolute;
buffer->data.allAvailableSensorsAreActive = ready;
buffer->seqlock.WriteEnd();
}
} // namespace
namespace content {
SensorManagerAndroid::SensorManagerAndroid()
: number_active_device_motion_sensors_(0),
device_light_buffer_(nullptr),
device_motion_buffer_(nullptr),
device_orientation_buffer_(nullptr),
motion_buffer_initialized_(false),
orientation_buffer_initialized_(false),
is_shutdown_(false) {
memset(received_motion_data_, 0, sizeof(received_motion_data_));
device_sensors_.Reset(Java_DeviceSensors_getInstance(
AttachCurrentThread(), base::android::GetApplicationContext()));
}
SensorManagerAndroid::~SensorManagerAndroid() {
}
bool SensorManagerAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
SensorManagerAndroid* SensorManagerAndroid::GetInstance() {
return base::Singleton<
SensorManagerAndroid,
base::LeakySingletonTraits<SensorManagerAndroid>>::get();
}
void SensorManagerAndroid::GotOrientation(JNIEnv*,
const JavaParamRef<jobject>&,
double alpha,
double beta,
double gamma) {
base::AutoLock autolock(orientation_buffer_lock_);
if (!device_orientation_buffer_)
return;
SetOrientation(device_orientation_buffer_, alpha, beta, gamma);
if (!orientation_buffer_initialized_) {
OrientationSensorType type =
static_cast<OrientationSensorType>(GetOrientationSensorTypeUsed());
SetOrientationBufferStatus(device_orientation_buffer_, true,
type != GAME_ROTATION_VECTOR);
orientation_buffer_initialized_ = true;
UpdateDeviceOrientationHistogram(type);
}
}
void SensorManagerAndroid::GotOrientationAbsolute(JNIEnv*,
const JavaParamRef<jobject>&,
double alpha,
double beta,
double gamma) {
base::AutoLock autolock(orientation_absolute_buffer_lock_);
if (!device_orientation_absolute_buffer_)
return;
SetOrientation(device_orientation_absolute_buffer_, alpha, beta, gamma);
if (!orientation_absolute_buffer_initialized_) {
SetOrientationBufferStatus(device_orientation_absolute_buffer_, true, true);
orientation_absolute_buffer_initialized_ = true;
// TODO(timvolodine): Add UMA.
}
}
void SensorManagerAndroid::GotAcceleration(JNIEnv*,
const JavaParamRef<jobject>&,
double x,
double y,
double z) {
base::AutoLock autolock(motion_buffer_lock_);
if (!device_motion_buffer_)
return;
device_motion_buffer_->seqlock.WriteBegin();
device_motion_buffer_->data.accelerationX = x;
device_motion_buffer_->data.hasAccelerationX = true;
device_motion_buffer_->data.accelerationY = y;
device_motion_buffer_->data.hasAccelerationY = true;
device_motion_buffer_->data.accelerationZ = z;
device_motion_buffer_->data.hasAccelerationZ = true;
device_motion_buffer_->seqlock.WriteEnd();
if (!motion_buffer_initialized_) {
received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION] = 1;
CheckMotionBufferReadyToRead();
}
}
void SensorManagerAndroid::GotAccelerationIncludingGravity(
JNIEnv*,
const JavaParamRef<jobject>&,
double x,
double y,
double z) {
base::AutoLock autolock(motion_buffer_lock_);
if (!device_motion_buffer_)
return;
device_motion_buffer_->seqlock.WriteBegin();
device_motion_buffer_->data.accelerationIncludingGravityX = x;
device_motion_buffer_->data.hasAccelerationIncludingGravityX = true;
device_motion_buffer_->data.accelerationIncludingGravityY = y;
device_motion_buffer_->data.hasAccelerationIncludingGravityY = true;
device_motion_buffer_->data.accelerationIncludingGravityZ = z;
device_motion_buffer_->data.hasAccelerationIncludingGravityZ = true;
device_motion_buffer_->seqlock.WriteEnd();
if (!motion_buffer_initialized_) {
received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION_INCL_GRAVITY] = 1;
CheckMotionBufferReadyToRead();
}
}
void SensorManagerAndroid::GotRotationRate(JNIEnv*,
const JavaParamRef<jobject>&,
double alpha,
double beta,
double gamma) {
base::AutoLock autolock(motion_buffer_lock_);
if (!device_motion_buffer_)
return;
device_motion_buffer_->seqlock.WriteBegin();
device_motion_buffer_->data.rotationRateAlpha = alpha;
device_motion_buffer_->data.hasRotationRateAlpha = true;
device_motion_buffer_->data.rotationRateBeta = beta;
device_motion_buffer_->data.hasRotationRateBeta = true;
device_motion_buffer_->data.rotationRateGamma = gamma;
device_motion_buffer_->data.hasRotationRateGamma = true;
device_motion_buffer_->seqlock.WriteEnd();
if (!motion_buffer_initialized_) {
received_motion_data_[RECEIVED_MOTION_DATA_ROTATION_RATE] = 1;
CheckMotionBufferReadyToRead();
}
}
void SensorManagerAndroid::GotLight(JNIEnv*,
const JavaParamRef<jobject>&,
double value) {
base::AutoLock autolock(light_buffer_lock_);
if (!device_light_buffer_)
return;
device_light_buffer_->seqlock.WriteBegin();
device_light_buffer_->data.value = value;
device_light_buffer_->seqlock.WriteEnd();
}
bool SensorManagerAndroid::Start(ConsumerType consumer_type) {
DCHECK(!device_sensors_.is_null());
int rate_in_microseconds = (consumer_type == CONSUMER_TYPE_LIGHT)
? kLightSensorIntervalMicroseconds
: kDeviceSensorIntervalMicroseconds;
return Java_DeviceSensors_start(AttachCurrentThread(),
device_sensors_.obj(),
reinterpret_cast<intptr_t>(this),
static_cast<jint>(consumer_type),
rate_in_microseconds);
}
void SensorManagerAndroid::Stop(ConsumerType consumer_type) {
DCHECK(!device_sensors_.is_null());
Java_DeviceSensors_stop(AttachCurrentThread(),
device_sensors_.obj(),
static_cast<jint>(consumer_type));
}
int SensorManagerAndroid::GetNumberActiveDeviceMotionSensors() {
DCHECK(!device_sensors_.is_null());
return Java_DeviceSensors_getNumberActiveDeviceMotionSensors(
AttachCurrentThread(), device_sensors_.obj());
}
SensorManagerAndroid::OrientationSensorType
SensorManagerAndroid::GetOrientationSensorTypeUsed() {
DCHECK(!device_sensors_.is_null());
return static_cast<SensorManagerAndroid::OrientationSensorType>(
Java_DeviceSensors_getOrientationSensorTypeUsed(
AttachCurrentThread(), device_sensors_.obj()));
}
// ----- Shared memory API methods
// --- Device Light
void SensorManagerAndroid::StartFetchingDeviceLightData(
DeviceLightHardwareBuffer* buffer) {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StartFetchingLightDataOnUI(buffer);
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StartFetchingLightDataOnUI,
base::Unretained(this),
buffer));
}
}
void SensorManagerAndroid::StartFetchingLightDataOnUI(
DeviceLightHardwareBuffer* buffer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(buffer);
if (is_shutdown_)
return;
{
base::AutoLock autolock(light_buffer_lock_);
device_light_buffer_ = buffer;
SetLightBufferValue(-1);
}
bool success = Start(CONSUMER_TYPE_LIGHT);
if (!success) {
base::AutoLock autolock(light_buffer_lock_);
SetLightBufferValue(std::numeric_limits<double>::infinity());
}
}
void SensorManagerAndroid::StopFetchingDeviceLightData() {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StopFetchingLightDataOnUI();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StopFetchingLightDataOnUI,
base::Unretained(this)));
}
void SensorManagerAndroid::StopFetchingLightDataOnUI() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (is_shutdown_)
return;
Stop(CONSUMER_TYPE_LIGHT);
{
base::AutoLock autolock(light_buffer_lock_);
if (device_light_buffer_) {
SetLightBufferValue(-1);
device_light_buffer_ = nullptr;
}
}
}
void SensorManagerAndroid::SetLightBufferValue(double lux) {
device_light_buffer_->seqlock.WriteBegin();
device_light_buffer_->data.value = lux;
device_light_buffer_->seqlock.WriteEnd();
}
// --- Device Motion
void SensorManagerAndroid::StartFetchingDeviceMotionData(
DeviceMotionHardwareBuffer* buffer) {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StartFetchingMotionDataOnUI(buffer);
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StartFetchingMotionDataOnUI,
base::Unretained(this),
buffer));
}
}
void SensorManagerAndroid::StartFetchingMotionDataOnUI(
DeviceMotionHardwareBuffer* buffer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(buffer);
if (is_shutdown_)
return;
{
base::AutoLock autolock(motion_buffer_lock_);
device_motion_buffer_ = buffer;
ClearInternalMotionBuffers();
}
Start(CONSUMER_TYPE_MOTION);
// If no motion data can ever be provided, the number of active device motion
// sensors will be zero. In that case flag the shared memory buffer
// as ready to read, as it will not change anyway.
number_active_device_motion_sensors_ = GetNumberActiveDeviceMotionSensors();
{
base::AutoLock autolock(motion_buffer_lock_);
CheckMotionBufferReadyToRead();
}
}
void SensorManagerAndroid::StopFetchingDeviceMotionData() {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StopFetchingMotionDataOnUI();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StopFetchingMotionDataOnUI,
base::Unretained(this)));
}
void SensorManagerAndroid::StopFetchingMotionDataOnUI() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (is_shutdown_)
return;
Stop(CONSUMER_TYPE_MOTION);
{
base::AutoLock autolock(motion_buffer_lock_);
if (device_motion_buffer_) {
ClearInternalMotionBuffers();
device_motion_buffer_ = nullptr;
}
}
}
void SensorManagerAndroid::CheckMotionBufferReadyToRead() {
if (received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION] +
received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION_INCL_GRAVITY] +
received_motion_data_[RECEIVED_MOTION_DATA_ROTATION_RATE] ==
number_active_device_motion_sensors_) {
device_motion_buffer_->seqlock.WriteBegin();
device_motion_buffer_->data.interval =
kDeviceSensorIntervalMicroseconds / 1000.;
device_motion_buffer_->seqlock.WriteEnd();
SetMotionBufferReadyStatus(true);
UMA_HISTOGRAM_BOOLEAN("InertialSensor.AccelerometerAndroidAvailable",
received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION] > 0);
UMA_HISTOGRAM_BOOLEAN(
"InertialSensor.AccelerometerIncGravityAndroidAvailable",
received_motion_data_[RECEIVED_MOTION_DATA_ACCELERATION_INCL_GRAVITY]
> 0);
UMA_HISTOGRAM_BOOLEAN("InertialSensor.GyroscopeAndroidAvailable",
received_motion_data_[RECEIVED_MOTION_DATA_ROTATION_RATE] > 0);
}
}
void SensorManagerAndroid::SetMotionBufferReadyStatus(bool ready) {
device_motion_buffer_->seqlock.WriteBegin();
device_motion_buffer_->data.allAvailableSensorsAreActive = ready;
device_motion_buffer_->seqlock.WriteEnd();
motion_buffer_initialized_ = ready;
}
void SensorManagerAndroid::ClearInternalMotionBuffers() {
memset(received_motion_data_, 0, sizeof(received_motion_data_));
number_active_device_motion_sensors_ = 0;
SetMotionBufferReadyStatus(false);
}
// --- Device Orientation
void SensorManagerAndroid::StartFetchingDeviceOrientationData(
DeviceOrientationHardwareBuffer* buffer) {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StartFetchingOrientationDataOnUI(buffer);
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StartFetchingOrientationDataOnUI,
base::Unretained(this),
buffer));
}
}
void SensorManagerAndroid::StartFetchingOrientationDataOnUI(
DeviceOrientationHardwareBuffer* buffer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(buffer);
if (is_shutdown_)
return;
{
base::AutoLock autolock(orientation_buffer_lock_);
device_orientation_buffer_ = buffer;
}
bool success = Start(CONSUMER_TYPE_ORIENTATION);
{
base::AutoLock autolock(orientation_buffer_lock_);
// If Start() was unsuccessful then set the buffer ready flag to true
// to start firing all-null events.
SetOrientationBufferStatus(buffer, !success /* ready */,
false /* absolute */);
orientation_buffer_initialized_ = !success;
}
if (!success)
UpdateDeviceOrientationHistogram(NOT_AVAILABLE);
}
void SensorManagerAndroid::StopFetchingDeviceOrientationData() {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StopFetchingOrientationDataOnUI();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StopFetchingOrientationDataOnUI,
base::Unretained(this)));
}
void SensorManagerAndroid::StopFetchingOrientationDataOnUI() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (is_shutdown_)
return;
Stop(CONSUMER_TYPE_ORIENTATION);
{
base::AutoLock autolock(orientation_buffer_lock_);
if (device_orientation_buffer_) {
SetOrientationBufferStatus(device_orientation_buffer_, false, false);
orientation_buffer_initialized_ = false;
device_orientation_buffer_ = nullptr;
}
}
}
void SensorManagerAndroid::StartFetchingDeviceOrientationAbsoluteData(
DeviceOrientationHardwareBuffer* buffer) {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StartFetchingOrientationAbsoluteDataOnUI(buffer);
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&SensorManagerAndroid::StartFetchingOrientationAbsoluteDataOnUI,
base::Unretained(this),
buffer));
}
}
void SensorManagerAndroid::StopFetchingDeviceOrientationAbsoluteData() {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
StopFetchingOrientationAbsoluteDataOnUI();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SensorManagerAndroid::StopFetchingOrientationAbsoluteDataOnUI,
base::Unretained(this)));
}
void SensorManagerAndroid::StartFetchingOrientationAbsoluteDataOnUI(
DeviceOrientationHardwareBuffer* buffer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(buffer);
if (is_shutdown_)
return;
{
base::AutoLock autolock(orientation_absolute_buffer_lock_);
device_orientation_absolute_buffer_ = buffer;
}
bool success = Start(CONSUMER_TYPE_ORIENTATION_ABSOLUTE);
{
base::AutoLock autolock(orientation_absolute_buffer_lock_);
// If Start() was unsuccessful then set the buffer ready flag to true
// to start firing all-null events.
SetOrientationBufferStatus(buffer, !success /* ready */,
false /* absolute */);
orientation_absolute_buffer_initialized_ = !success;
}
}
void SensorManagerAndroid::StopFetchingOrientationAbsoluteDataOnUI() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (is_shutdown_)
return;
Stop(CONSUMER_TYPE_ORIENTATION_ABSOLUTE);
{
base::AutoLock autolock(orientation_absolute_buffer_lock_);
if (device_orientation_absolute_buffer_) {
SetOrientationBufferStatus(device_orientation_absolute_buffer_, false,
false);
orientation_absolute_buffer_initialized_ = false;
device_orientation_absolute_buffer_ = nullptr;
}
}
}
void SensorManagerAndroid::Shutdown() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
is_shutdown_ = true;
}
} // namespace content
| danakj/chromium | content/browser/device_sensors/sensor_manager_android.cc | C++ | bsd-3-clause | 18,015 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
/* @var $this yii\web\View */
/* @var $model app\models\Cosechadia */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="row">
<div class="col-xs-12">
<?php $form = ActiveForm::begin([
'options' => ['class' => 'form-horizontal'],
]); ?>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> </label>
<div class="col-xs-10 col-sm-5">
<?= $form->field($model, 'empleado_id')->dropdownList($data, array('prompt'=>'Seleccione una empleado')) ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> </label>
<div class="col-xs-10 col-sm-5">
<?= '<label class="control-label">Fecha</label>'; ?>
<?=
DatePicker::widget([
'model' => $model,
'name' => 'check_issue_date',
'value' => date('Y-m-d'),
'options' => ['placeholder' => 'Presione para seleccionar una Fecha ...'],
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'todayHighlight' => true
]
]);
?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> </label>
<div class="col-xs-10 col-sm-5">
<?= $form->field($model, 'cantidad')->textInput() ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> </label>
<div class="col-xs-10 col-sm-5">
<?= $form->field($model, 'total')->textInput() ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> </label>
<div class="col-xs-10 col-sm-5">
<?= $form->field($model, 'pagado')->textInput() ?>
</div>
</div>
<div class="clearfix form-actions">
<div class="col-md-offset-3 col-md-9">
<?= Html::submitButton($model->isNewRecord ? 'Crear Cosecha' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div> | ppino/Cosecha | views/cosechadia/_form.php | PHP | bsd-3-clause | 2,646 |
#ifndef NEK_CONTAINER_CONTAINER_TRAITS_CONTAINER_TRAITS_HPP
#define NEK_CONTAINER_CONTAINER_TRAITS_CONTAINER_TRAITS_HPP
#include <cstddef>
#include <nek/container/container_traits/container_tag.hpp>
#include <nek/mpl/identity.hpp>
#include <nek/mpl/eval_if.hpp>
#include <nek/type_traits/is_array.hpp>
#include <nek/utility/has_xxx_def.hpp>
#ifdef NEK_CONTAINER_MEMBER_TYPE_DEF
# undef NEK_CONTAINER_MEMBER_TYPE_DEF
#endif
#define NEK_CONTAINER_MEMBER_TYPE_DEF(TYPE, ARRAY_TYPE)\
template <class Container>\
struct TYPE\
{\
using type = typename Container::TYPE;\
};\
\
template <class T, std::size_t N>\
struct TYPE<T[N]>\
{\
using type = ARRAY_TYPE;\
};\
\
template <class T>\
struct TYPE<T[]>\
{\
using type = ARRAY_TYPE;\
};\
\
template <class Container>\
using TYPE##_t = typename TYPE<Container>::type
namespace nek
{
namespace container_traits
{
namespace container_traits_detail
{
NEK_HAS_XXX_TYPE_DEF(container_tag);
template <class Container>
struct get_container_tag
{
using type = typename Container::container_tag;
};
}
NEK_CONTAINER_MEMBER_TYPE_DEF(value_type, T);
NEK_CONTAINER_MEMBER_TYPE_DEF(size_type, std::size_t);
template <class Container>
struct container_tag
{
using type = mpl::if_t<
nek::is_array<Container>,
array_container_tag,
typename mpl::eval_if_t<container_traits_detail::has_container_tag<Container>,
container_traits_detail::get_container_tag<Container>,
mpl::identity<unknown_container_tag>>>;
};
template <class Container>
using container_tag_t = typename container_tag<Container>::type;
}
}
#undef NEK_CONTAINER_MEMBER_TYPE_DEF
#endif
| nekko1119/nek | nek/container/container_traits/container_traits.hpp | C++ | bsd-3-clause | 1,864 |
<!DOCTYPE html>
<html>
<head data-gwd-animation-mode="proMode">
<meta charset="utf-8">
<title>Login</title>
<meta name="generator" content="Google Web Designer 1.4.2.0915">
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
.gwd-div-1yun {
width: 1024px;
height: 100%;
margin: auto;
background-color: transparent;
}
</style>
</head>
<body class="gwd-body">
<div class="gwd-div-1yun"></div>
<gwd_animation_label_element data-label-name="label-1" data-label-time="0" data-label-animation-class-name="label-1"></gwd_animation_label_element>
</body>
</html> | krystouf/injazfuj | Login/Login.html | HTML | bsd-3-clause | 656 |
/**
* @file
*
* @brief A plugin that converts keys to metakeys and vice versa
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include "keytometa.h"
#ifndef HAVE_KDBCONFIG
#include "kdbconfig.h"
#endif
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
static const char * CONVERT_METANAME = "convert/metaname";
static const char * CONVERT_TARGET = "convert/to";
static const char * CONVERT_APPEND_SAMELEVEL = "convert/append/samelevel";
static const char * CONVERT_APPENDMODE = "convert/append";
/*
* Wrapper for the function comparing by order metadata. As
* qsort is not stable returning 0 on missing order may
* mess up the original order.
*/
int elektraKeyCmpOrderWrapper (const void * a, const void * b)
{
const Key ** ka = (const Key **) a;
const Key ** kb = (const Key **) b;
int orderResult = elektraKeyCmpOrder (*ka, *kb);
/* comparing the order meta could not order the keys
* revert to comparing the names instead
*/
if (orderResult == 0) return keyCmp (*ka, *kb);
return orderResult;
}
/* The KeySet MUST be sorted alphabetically (or at least ascending
* by the length of keynames) for this function to work
*/
static Key * findNearestParent (Key * key, KeySet * ks)
{
Key * current;
ksSetCursor (ks, ksGetSize (ks) - 1);
while ((current = ksPrev (ks)) != 0)
{
if (keyIsBelow (current, key))
{
return current;
}
}
return 0;
}
/*
* Appends a line to the MetaKey of the supplied Key
* If no MetaKey with the given name exists yet, a new
* one is created containing the supplied line. If
* the MetaKey exists, the supplied line is added as
* a new line to the value of the MetaKey (i.e. a newline
* followed by the given line is appended to the metadata)
*
* @param target the Key whose MetaKey is to be modified
* @param metaName the name of the MetaKey which is to be modified
* @param line the line to be appended to the matadata
* @return the new value size of the modified MetaKey
* @retval -1 on NULL pointers or if a memory allocation error occurs
*
* @see keyGetValueSize(Key *key)
*
*/
int elektraKeyAppendMetaLine (Key * target, const char * metaName, const char * line)
{
if (!target) return 0;
if (!metaName) return 0;
if (!line) return 0;
if (!keyGetMeta (target, metaName))
{
keySetMeta (target, metaName, line);
return keyGetValueSize (keyGetMeta (target, metaName));
}
const Key * existingMeta = keyGetMeta (target, metaName);
char * buffer = elektraMalloc (keyGetValueSize (existingMeta) + strlen (line) + 1);
if (!buffer) return 0;
keyGetString (existingMeta, buffer, keyGetValueSize (existingMeta));
strcat (buffer, "\n");
strncat (buffer, line, strlen (line));
keySetMeta (target, metaName, buffer);
elektraFree (buffer);
return keyGetValueSize (keyGetMeta (target, metaName));
}
static const char * getAppendMode (Key * key)
{
const Key * appendModeKey = keyGetMeta (key, CONVERT_APPENDMODE);
const char * appendMode;
/* append to the next key is the default */
appendMode = appendModeKey != 0 ? keyString (appendModeKey) : "next";
return appendMode;
}
void removeKeyFromResult (Key * convertKey, Key * target, KeySet * orig)
{
/* remember which key this key was converted to
* before removing it from the result
*/
keySetMeta (convertKey, CONVERT_TARGET, keyName (target));
Key * key = ksLookup (orig, convertKey, KDB_O_POP);
keyDel (key);
}
static void flushConvertedKeys (Key * target, KeySet * converted, KeySet * orig)
{
if (ksGetSize (converted) == 0) return;
ksRewind (converted);
Key * current;
while ((current = ksNext (converted)))
{
Key * appendTarget = target;
const char * metaName = keyString (keyGetMeta (current, CONVERT_METANAME));
Key * currentDup = keyDup (current);
Key * targetDup = keyDup (appendTarget);
keySetBaseName (currentDup, 0);
keySetBaseName (targetDup, 0);
/* the convert key request to be converted to a key
* on the same level, but the target is below or above
*/
if (keyGetMeta (current, CONVERT_APPEND_SAMELEVEL) && keyCmp (currentDup, targetDup))
{
appendTarget = 0;
}
keyDel (currentDup);
keyDel (targetDup);
/* no target key was found of the target
* was discarded for some reason. Revert to the parent
*/
if (!appendTarget)
{
appendTarget = findNearestParent (current, orig);
}
elektraKeyAppendMetaLine (appendTarget, metaName, keyString (current));
removeKeyFromResult (current, target, orig);
}
ksClear (converted);
}
static KeySet * convertKeys (Key ** keyArray, size_t numKeys, KeySet * orig)
{
Key * current = 0;
Key * prevAppendTarget = 0;
KeySet * prevConverted = ksNew (0, KS_END);
KeySet * nextConverted = ksNew (0, KS_END);
KeySet * result = ksNew (0, KS_END);
for (size_t index = 0; index < numKeys; index++)
{
current = keyArray[index];
if (!keyGetMeta (current, CONVERT_METANAME))
{
/* flush out "previous" and "next" keys which may have been collected
* because the current key serves as a new border
*/
ksAppend (result, prevConverted);
flushConvertedKeys (prevAppendTarget, prevConverted, orig);
prevAppendTarget = current;
ksAppend (result, nextConverted);
flushConvertedKeys (current, nextConverted, orig);
continue;
}
const char * appendMode = getAppendMode (current);
const char * metaName = keyString (keyGetMeta (current, CONVERT_METANAME));
Key * bufferKey = 0;
if (!strcmp (appendMode, "previous"))
{
ksAppendKey (prevConverted, current);
}
if (!strcmp (appendMode, "next"))
{
ksAppendKey (nextConverted, current);
}
if (!strcmp (appendMode, "parent"))
{
Key * parent = findNearestParent (current, orig);
elektraKeyAppendMetaLine (parent, metaName, keyString (current));
ksAppendKey (result, current);
removeKeyFromResult (current, parent, orig);
}
if (bufferKey)
{
keySetString (bufferKey, keyName (current));
}
}
ksAppend (result, prevConverted);
flushConvertedKeys (prevAppendTarget, prevConverted, orig);
ksAppend (result, nextConverted);
flushConvertedKeys (0, nextConverted, orig);
ksDel (nextConverted);
ksDel (prevConverted);
return result;
}
int elektraKeyToMetaGet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
int errnosave = errno;
/* configuration only */
if (!strcmp (keyName (parentKey), "system/elektra/modules/keytometa"))
{
KeySet * info =
#include "contract.h"
ksAppend (returned, info);
ksDel (info);
return 1;
}
Key ** keyArray = calloc (ksGetSize (returned), sizeof (Key *));
int ret = elektraKsToMemArray (returned, keyArray);
if (ret < 0)
{
elektraFree (keyArray);
ELEKTRA_SET_ERROR (87, parentKey, strerror (errno));
errno = errnosave;
return 0;
}
size_t numKeys = ksGetSize (returned);
qsort (keyArray, numKeys, sizeof (Key *), elektraKeyCmpOrderWrapper);
KeySet * convertedKeys = convertKeys (keyArray, numKeys, returned);
elektraFree (keyArray);
/* cleanup what might have been left from a previous call */
KeySet * old = elektraPluginGetData (handle);
if (old)
{
ksDel (old);
}
elektraPluginSetData (handle, convertedKeys);
errno = errnosave;
return 1; /* success */
}
int elektraKeyToMetaSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
KeySet * converted = elektraPluginGetData (handle);
/* nothing to do */
if (converted == 0) return 1;
ksRewind (converted);
char * saveptr = 0;
char * value = 0;
Key * current;
Key * previous = 0;
while ((current = ksNext (converted)) != 0)
{
const Key * targetName = keyGetMeta (current, CONVERT_TARGET);
const Key * metaName = keyGetMeta (current, CONVERT_METANAME);
/* they should always exist, just to be sure */
if (targetName && metaName)
{
Key * target = ksLookupByName (returned, keyString (targetName), KDB_O_NONE);
/* this might be NULL as the key might have been deleted */
if (target)
{
char * result = 0;
if (target != previous)
{
/* handle the first meta line this means initializing strtok and related buffers */
elektraFree (value);
const Key * valueKey = keyGetMeta (target, keyString (metaName));
size_t valueSize = keyGetValueSize (valueKey);
value = elektraMalloc (valueSize);
keyGetString (valueKey, value, valueSize);
keySetMeta (target, keyString (metaName), 0);
result = strtok_r (value, "\n", &saveptr);
}
else
{
/* just continue splitting the metadata */
result = strtok_r (NULL, "\n", &saveptr);
}
keySetString (current, result);
previous = target;
}
}
keySetMeta (current, CONVERT_TARGET, 0);
keySetMeta (current, CONVERT_METANAME, 0);
ksAppendKey (returned, current);
}
elektraFree (value);
ksDel (converted);
elektraPluginSetData (handle, 0);
return 1; /* success */
}
int elektraKeyToMetaClose (Plugin * handle, Key * errorKey ELEKTRA_UNUSED)
{
KeySet * old = elektraPluginGetData (handle);
if (old)
{
ksDel (old);
}
return 1;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (keytometa)
{
// clang-format off
return elektraPluginExport("keytometa",
ELEKTRA_PLUGIN_GET, &elektraKeyToMetaGet,
ELEKTRA_PLUGIN_SET, &elektraKeyToMetaSet,
ELEKTRA_PLUGIN_CLOSE, &elektraKeyToMetaClose,
ELEKTRA_PLUGIN_END);
}
| e1528532/libelektra | src/plugins/keytometa/keytometa.c | C | bsd-3-clause | 9,287 |
package com.feeyo.net.nio.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ConcurrentModificationException;
public class SelectorUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(SelectorUtil.class);
public static final int REBUILD_COUNT_THRESHOLD = 512;
public static final long MIN_SELECT_TIME_IN_NANO_SECONDS = 500000L;
public static Selector rebuildSelector(final Selector oldSelector) throws IOException {
final Selector newSelector;
try {
newSelector = Selector.open();
} catch (Exception e) {
LOGGER.warn("Failed to create a new Selector.", e);
return null;
}
for (;;) {
try {
for (SelectionKey key: oldSelector.keys()) {
Object a = key.attachment();
try {
if (!key.isValid() || key.channel().keyFor(newSelector) != null) {
continue;
}
int interestOps = key.interestOps();
key.cancel();
key.channel().register(newSelector, interestOps, a);
} catch (Exception e) {
LOGGER.warn("Failed to re-register a Channel to the new Selector.", e);
// Q: 在这个catch里面是否需要处理attachment: Connection 的关闭 ? 假设当前key的channel真的register失败的话 ? 看netty里面是进行了channel的close的样子
// A: 其实不需要,当前NIO 本身的机制就可以关闭Connection。这里直接返回null,依赖本身的机制关闭相关的资源
}
}
// Q: 在什么情况下会发生并发修改异常ConcurrentModificationException ?
// A: oldSelector.keys()返回UngrowableSet(只能Remove,不能add),这个方法会cancel掉key,cancel掉key的同时,将key加入Selector的removeSet,在下次select的时候,Selector会remove掉这些key。
// 目前的NIO架构不会触发这个(一个Selector只对应一个线程操作,无论是Acceptor还是Connector还是Reactor),但考虑移植代码完整性还有以后新设计的安全性,保留这个原有设计
} catch (ConcurrentModificationException e) {
// Probably due to concurrent modification of the key set.
continue;
}
break;
}
oldSelector.close();
return newSelector;
}
}
| variflight/feeyo-redisproxy | src/main/java/com/feeyo/net/nio/util/SelectorUtil.java | Java | bsd-3-clause | 2,816 |
import * as API from './sessionApi';
import * as constants from './sessionConstants';
import { getNullUser, camelCaseObjKeys } from 'ssUtil';
export const setUser = user => ({
type: constants.SET_USER,
user
});
export const resetUser = () => ({
type: constants.RESET_USER
});
export const login = user => async dispatch => {
const currentUser = await API.login(user);
dispatch(setUser(camelCaseObjKeys(currentUser, false)));
};
export const logout = () => async dispatch => {
const currentUser = await API.logout();
dispatch(resetUser());
};
| jaredjj3/string-sync | client/src/data/api/session/sessionActions.ts | TypeScript | bsd-3-clause | 560 |
<!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" lang="es-ES" xml:lang="es-ES">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>LightZone: Styles: Exporting</title><!--[if lt IE 7]>
<script defer type="text/javascript" src="IE_PNG.js"></script>
<link rel="stylesheet" type="text/css" href="IE.css" media="all"/>
<![endif]-->
<meta name="description" content="How to export your styles."/>
<link rel="stylesheet" type="text/css" href="Help.css" media="all"/>
<link rel="stylesheet" type="text/css" href="Platform.css" media="all"/>
</head>
<body>
<div id="banner">
<div id="banner_left">
<a href="index.html">Ayuda de LightZone</a>
</div>
<div id="banner_right">
<a href="index/index.html">Index</a>
</div>
</div><!-- LC_Index: styles > converting --><!-- LC_Index: lzt files -->
<a name="Styles-Exporting"></a>
<img src="images/app_icon-32.png" width="32" height="32"
class="title_icon"/>
<h2>Styles: Exporting</h2>
<a href="Styles-Importing.html" id="next">4 of 6</a>
<p>
After <a href="Styles-Creating.html">creating</a>
one or more styles,
you can export them as LightZone Style files
(having an <code>lzt</code> extension)
that can be
<a href="Styles-Importing.html">imported</a>
into LightZone on other computers.
</p>
<div class="task_box">
<h3>To export a style:</h3>
<ol>
<li>
Select File > Manage Styles...
</li>
<li>
Select the style you want to export.
</li>
<li>
Click Export...
</li>
<li>
Navigate to the folder where you want to export the style file to.
</li>
<li>
Click Choose.
(The style will be written to a file having an <code>lzt</code>
extension.)
</li>
<li>
Click OK.
</li>
</ol>
</div>
<div>
<h4>See also:</h4>
<ul>
<li>
<a href="Styles-Importing.html">Styles: Importing</a>
</li>
</ul>
</div>
</body>
</html><!-- vim:set et sw=2 ts=2: -->
| MarinnaCole/LightZone | lightcrafts/help/Spanish/Styles-Exporting.html | HTML | bsd-3-clause | 2,490 |
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LOGIN_MANAGER_MOCK_POLICY_STORE_H_
#define LOGIN_MANAGER_MOCK_POLICY_STORE_H_
#include "login_manager/policy_store.h"
namespace login_manager{
class MockPolicyStore : public PolicyStore {
public:
MockPolicyStore();
virtual ~MockPolicyStore();
MOCK_METHOD0(DefunctPrefsFilePresent, bool(void));
MOCK_METHOD0(LoadOrCreate, bool(void));
MOCK_CONST_METHOD0(Get,
const enterprise_management::PolicyFetchResponse&(void));
MOCK_METHOD0(Persist, bool(void));
MOCK_METHOD1(Set, void(const enterprise_management::PolicyFetchResponse&));
};
} // namespace login_manager
#endif // LOGIN_MANAGER_MOCK_POLICY_STORE_H_
| chadversary/chromiumos.platform.login_manager | mock_policy_store.h | C | bsd-3-clause | 826 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Polymer Codelab Messina</title>
<link rel="stylesheet" href="styles/main.css">
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="elements/elements.html">
</head>
<body unresolved>
<template is="dom-bind" id="app">
<iron-ajax url="api/users.json" last-response="{{data}}" auto></iron-ajax>
<app-header shadow>
<app-toolbar>
<a href="/">
<h3>Best app ever</h3>
</a>
</app-toolbar>
</app-header>
<iron-pages attr-for-selected="data-route" selected="[[route]]">
<section data-route="home">
<paper-material>
<table class="users">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Company</th>
</tr>
<template is="dom-repeat" items="[[data]]" as="u">
<tr id="[[u.id]]" on-tap="viewDetail">
<td>[[u.name]]</td>
<td>[[u.surname]]</td>
<td>[[u.company]]</td>
</tr>
</template>
</table>
</paper-material>
</section>
<section data-route="user">
<user-detail users="[[data]]" user-id="[[params.id]]"></user-detail>
</section>
</iron-pages>
</template>
<script src="scripts/app.js"></script>
</body>
</html>
| Granze/polymer-codelab-messina | app/index.html | HTML | bsd-3-clause | 1,580 |
<?php
namespace Application\Gateway;
use Rox\Gateway\MongoDb\AbstractGateway;
class Karts extends AbstractGateway
{
}
| marcelojeff/kart | module/Application/src/Application/Gateway/Karts.php | PHP | bsd-3-clause | 125 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Markup
* @subpackage Renderer_Markup_Html
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Markup\Renderer\Markup\Html;
use Zend\Markup\Token;
/**
* Simple replace markup for HTML
*
* @uses \Zend\Markup\Renderer\Markup\Html\AbstractHtml
* @uses \Zend\Markup\Token
* @category Zend
* @package Zend_Markup
* @subpackage Renderer_Markup_Html
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Replace extends AbstractHtml
{
/**
* Invoke the markup on the token
*
* @param Token $token
* @param string $text
*
* @return string
*/
public function __invoke(Token $token, $text)
{
return $text;
}
}
| TrafeX/zf2 | library/Zend/Markup/Renderer/Markup/Html/Root.php | PHP | bsd-3-clause | 1,464 |
<?php
defined('COT_CODE') or die('Wrong URL.');
if(empty($GLOBALS['db_files_folders'])) {
cot::$db->registerTable('files_folders');
cot_extrafields_register_table('files_folders');
}
/**
* Модель File Folder
*
* @method static files_model_Folder getById($pk, $staticCache = true);
* @method static files_model_Folder fetchOne($conditions = array(), $order = '')
* @method static files_model_Folder[] findByCondition($conditions = array(), $limit = 0, $offset = 0, $order = '')
*
* @property int $ff_id
* @property int $user_id id пользователя - владельца или 0 - если это site file space
* @property string $ff_title Название папки/альбома
* @property string $ff_desc Описание папки/альбома
* @property bool $ff_public Публичный?
* @property bool $ff_album Галерея?
* @property int $ff_count Количество элементов
* @property string $ff_created Дата создания
* @property string $ff_updated Дата последнего изменения
*
*/
class files_model_Folder extends Som_Model_ActiveRecord
{
protected static $_db = null;
protected static $_tbname = '';
protected static $_primary_key = 'ff_id';
/**
* Static constructor
* @param string $db Data base connection config name
*/
public static function __init($db = 'db')
{
static::$_tbname = cot::$db->files_folders;
parent::__init($db);
}
protected function beforeInsert()
{
if(empty($this->_data['ff_created'])){
$this->_data['ff_created'] = date('Y-m-d H:i:s', cot::$sys['now']);
}
if(empty($this->_data['ff_updated'])){
$this->_data['ff_updated'] = date('Y-m-d H:i:s', cot::$sys['now']);
}
return parent::beforeInsert();
}
protected function beforeUpdate()
{
$this->_data['ff_updated'] = date('Y-m-d H:i:s', cot::$sys['now']);
// Update files count in this folder
if(!array_key_exists('ff_count', $this->_oldData)) {
$source = ($this->_data['user_id'] > 0) ? 'pfs' : 'sfs';
$condition = array(
array('file_source', $source),
array('file_item', $this->_data['ff_id']),
);
$this->_data['ff_count'] = files_model_File::count($condition);
}
return parent::beforeUpdate();
}
/**
* Delete
* @return bool
*/
public function delete()
{
$uid = (int)$this->_data['user_id'];
$isSFS = false; // is Site File Space
if($uid == 0) $isSFS = true;
$source = $isSFS ? 'sfs' : 'pfs';
// Remove all files
$files = files_model_File::findByCondition(array(
array('file_source', $source),
array('file_item', $this->_data['ff_id'])
));
if(!empty($files)){
foreach($files as $fileRow){
$fileRow->delete();
}
}
return parent::delete();
}
public static function fieldList() {
return array(
'ff_id' =>
array(
'name' => 'ff_id',
'type' => 'bigint',
'primary' => true,
'description' => 'id'
),
'user_id' =>
array(
'name' => 'user_id',
'type' => 'int',
'nullable' => true,
'description' => 'id пользователя - владельца или 0 - если это site file space'
),
'ff_title' =>
array(
'name' => 'ff_title',
'type' => 'varchar',
'length' => '255',
'description' => 'Название папки/альбома'
),
'ff_desc' =>
array(
'name' => 'ff_desc',
'type' => 'varchar',
'length' => '255',
'nullable' => true,
'default' => '',
'description' => 'Описание папки/альбома'
),
'ff_public' =>
array(
'name' => 'ff_public',
'type' => 'bool',
'nullable' => true,
'default' => 1,
'description' => 'Публичный?'
),
'ff_album' =>
array(
'name' => 'ff_album',
'type' => 'bool',
'nullable' => true,
'default' => 0,
'description' => 'Галерея?'
),
'ff_count' =>
array(
'name' => 'ff_count',
'type' => 'int',
'nullable' => true,
'default' => 0,
'description' => 'Количество элементов'
),
'ff_created' =>
array(
'name' => 'ff_created',
'type' => 'datetime',
'nullable' => true,
'default' => NULL,
'description' => 'Дата создания'
),
'ff_updated' =>
array(
'name' => 'ff_updated',
'type' => 'datetime',
'nullable' => true,
'default' => NULL,
'description' => 'Дата последней модификации'
),
);
}
// === Методы для работы с шаблонами ===
/**
* Returns all Group tags for coTemplate
*
* @param files_model_Folder|int $item vuz_model_Vuz object or ID
* @param string $tagPrefix Prefix for tags
* @param array $urlParams
* @param bool $cacheitem Cache tags
* @return array|void
*/
public static function generateTags($item, $tagPrefix = '', $urlParams = array(), $cacheitem = true){
global $cfg, $L, $usr, $cot_countries;
static $extp_first = null, $extp_main = null;
static $cacheArr = array();
if (is_null($extp_first)){
$extp_first = cot_getextplugins('files.folder.tags.first');
$extp_main = cot_getextplugins('files.folder.tags.main');
}
/* === Hook === */
foreach ($extp_first as $pl){
include $pl;
}
/* ===== */
if(empty($urlParams)) $urlParams = array('m' => 'pfs');
list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('files', 'a');
if ( ($item instanceof files_model_Folder) && is_array($cacheArr[$item->ff_id]) ) {
$temp_array = $cacheArr[$item->ff_id];
}elseif (is_int($item) && is_array($cacheArr[$item])){
$temp_array = $cacheArr[$item];
}else{
if (is_int($item) && $item > 0){
$item = files_model_Folder::getById($item);
}
/** @var files_model_Folder $item */
if ($item){
$itemUrl = cot_url('files', array('f' => $item->ff_id));
$itemEditUrl = '';
$itemDelUrl = '';
$itemPfsUrl = '';
if($usr['isadmin'] || ($usr['id'] > 0 && $usr['id'] == $item->user_id)){
$urlParams['f'] = $item->ff_id;
$itemPfsUrl = cot_url('files',$urlParams);
$tmp = $urlParams;
$tmp['a'] = 'editFolder';
$itemEditUrl = cot_url('files', $tmp);
$tmp['a'] = 'deleteFolder';
$itemDelUrl = cot_confirm_url(cot_url('files', $tmp));
}
$date_format = 'datetime_medium';
$temp_array = array(
'URL' => $itemUrl,
'EDIT_URL' => $itemEditUrl,
'PFS_URL' => $itemPfsUrl,
'DELETE_URL' => $itemDelUrl,
'ID' => $item->ff_id,
'TITLE' => htmlspecialchars($item->ff_title),
'DESC' => htmlspecialchars($item->ff_desc),
'ITEMS_COUNT' => $item->ff_count,
'PUBLIC' => (bool)$item->ff_public ? cot::$L['Yes'] : cot::$L['No'],
'ALBUM' => (bool)$item->ff_album ? cot::$L['Yes'] : cot::$L['No'],
'ISPUBLIC' => $item->ff_public,
'ISALBUM' => $item->ff_album,
'CREATE_DATE' => cot_date($date_format, strtotime($item->ff_created)),
'UPDATE_DATE' => cot_date($date_format, strtotime($item->ff_updated)),
'CREATED' => $item->ff_created,
'UPDATED' => $item->ff_updated,
'CREATED_RAW' => strtotime($item->ff_created),
'UPDATED_RAW' => strtotime($item->ff_updated),
'ICON' => $item->ff_album ? cot::$R['files_icon_gallery'] : cot::$R['files_icon_folder'],
);
/* === Hook === */
foreach ($extp_main as $pl)
{
include $pl;
}
/* ===== */
$cacheitem && $cacheArr[$item->ff_id] = $temp_array;
}else{
}
}
$return_array = array();
foreach ($temp_array as $key => $val){
$return_array[$tagPrefix . $key] = $val;
}
return $return_array;
}
}
files_model_Folder::__init(); | Alex300/files | files/model/Folder.php | PHP | bsd-3-clause | 10,024 |
/*
* Copyright (c) 2014, Araz Abishov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 org.dhis2.mobile.utils.date;
import org.dhis2.mobile.utils.date.exceptions.PeriodNotSupportedException;
import org.dhis2.mobile.utils.date.iterators.BiMonthIterator;
import org.dhis2.mobile.utils.date.iterators.BiWeekIterator;
import org.dhis2.mobile.utils.date.iterators.DayIterator;
import org.dhis2.mobile.utils.date.iterators.FinAprilYearIterator;
import org.dhis2.mobile.utils.date.iterators.FinJulyYearIterator;
import org.dhis2.mobile.utils.date.iterators.FinOctYearIterator;
import org.dhis2.mobile.utils.date.iterators.MonthIterator;
import org.dhis2.mobile.utils.date.iterators.QuarterYearIterator;
import org.dhis2.mobile.utils.date.iterators.SixMonthAprilIterator;
import org.dhis2.mobile.utils.date.iterators.SixMonthIterator;
import org.dhis2.mobile.utils.date.iterators.WeekIterator;
import org.dhis2.mobile.utils.date.iterators.WeekSaturdayIterator;
import org.dhis2.mobile.utils.date.iterators.WeekSundayIterator;
import org.dhis2.mobile.utils.date.iterators.WeekThursdayIterator;
import org.dhis2.mobile.utils.date.iterators.WeekWednesdayIterator;
import org.dhis2.mobile.utils.date.iterators.YearIterator;
import java.util.ArrayList;
public class DateIteratorFactory {
// private static final String WRONG_ALLOW_FP_PARAM = "Wrong allowFuturePeriod parameter";
// private static final String WRONG_PERIOD_TYPE = "Wrong periodType";
public static final String TRUE = "true";
public static final String FALSE = "false";
public static CustomDateIterator<ArrayList<DateHolder>> getDateIterator(String periodType,
int openFuturePeriods, String[] dataInputPeriods)
throws PeriodNotSupportedException {
if (periodType != null) {
if (periodType.equals(PeriodFilterFactory.YEARLY)) {
return (new YearIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.FINANCIAL_APRIL)) {
return (new FinAprilYearIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.FINANCIAL_JULY)) {
return (new FinJulyYearIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.FINANCIAL_OCT)) {
return (new FinOctYearIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.SIX_MONTHLY)) {
return (new SixMonthIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.SIX_MONTHLY_APRIL)) {
return (new SixMonthAprilIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.QUARTERLY)) {
return (new QuarterYearIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.BIMONTHLY)) {
return (new BiMonthIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.MONTHLY)) {
return (new MonthIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.BIWEEKLY)) {
return (new BiWeekIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.WEEKLY)) {
return (new WeekIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.WEEKLY_WEDNESDAY)) {
return (new WeekWednesdayIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.WEEKLY_THURSDAY)) {
return (new WeekThursdayIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.WEEKLY_SATURDAY)) {
return (new WeekSaturdayIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.WEEKLY_SUNDAY)) {
return (new WeekSundayIterator(openFuturePeriods, dataInputPeriods));
} else if (periodType.equals(PeriodFilterFactory.DAILY)) {
return (new DayIterator(openFuturePeriods, dataInputPeriods));
}
}
throw new PeriodNotSupportedException("Unsupported period type",periodType);
}
}
| dhis2/dhis2-android-datacapture | dhis2-android-app/src/main/java/org/dhis2/mobile/utils/date/DateIteratorFactory.java | Java | bsd-3-clause | 5,974 |
/******************************************************************************
* Copyright (c) 2010-2011, PCMS Lab
* 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 the <organization> 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 "PCMS Lab" BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <v8.h>
#include <string>
#include <exception>
#include "scripting.h"
#include "resource.h"
#include "appinfo.h"
using namespace v8;
const char* ToCString( const String::Utf8Value& value )
{
return *value ? *value : "<string conversion failed>";
}
std::string toString( int v )
{
char s[128];
sprintf(s, "%i", v );
return s;
}
std::string getExceptionMessage( TryCatch* try_catch )
{
HandleScope handle_scope;
String::Utf8Value exception( try_catch->Exception() );
const char* exception_string = ToCString(exception);
v8::Handle<v8::Message> message = try_catch->Message();
if (message.IsEmpty())
{
return exception_string;
}
String::Utf8Value filename( message->GetScriptResourceName() );
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber();
std::string exceptionMessage = filename_string;
exceptionMessage.append(1, ':');
exceptionMessage.append(toString(linenum));
exceptionMessage.append(": ");
exceptionMessage.append(exception_string);
exceptionMessage.append(1, '\n');
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
exceptionMessage.append(sourceline_string);
exceptionMessage.append(1, '\n');
int start = message->GetStartColumn();
exceptionMessage.append(start, ' ');
int end = message->GetEndColumn();
exceptionMessage.append(end-start, '^');
exceptionMessage.append(1, '\n');
String::Utf8Value stack_trace( try_catch->StackTrace() );
if (stack_trace.length() > 0)
{
const char* stack_trace_string = ToCString(stack_trace);
exceptionMessage.append(stack_trace_string);
exceptionMessage.append(1, '\n');
}
return exceptionMessage;
}
void ReportException( const char* title, TryCatch* try_catch )
{
HandleScope handle_scope;
String::Utf8Value exception( try_catch->Exception() );
const char* exception_string = ToCString(exception);
v8::Handle<v8::Message> message = try_catch->Message();
printf( "%s\n", title );
if (message.IsEmpty())
{
printf( "%s\n", exception_string );
return;
}
String::Utf8Value filename( message->GetScriptResourceName() );
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber();
printf("%s:%i: %s\n", filename_string, linenum, exception_string);
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
printf("%s\n", sourceline_string);
int start = message->GetStartColumn();
for (int i = 0; i < start; i++)
{
printf(" ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++)
{
printf("^");
}
printf("\n");
String::Utf8Value stack_trace( try_catch->StackTrace() );
if (stack_trace.length() > 0)
{
const char* stack_trace_string = ToCString(stack_trace);
printf("%s\n", stack_trace_string);
}
}
bool ExecuteScript( const std::string& source, const std::string& fileName )
{
return ExecuteScript( String::New(source.c_str()), String::New(fileName.c_str()) );
}
bool ExecuteScript( Handle<String> source, Handle<String> fileName )
{
HandleScope handle_scope;
TryCatch try_catch;
Handle<Script> script = Script::Compile( source, fileName );
if ( script.IsEmpty() )
{
std::string msg = "An exception occured while compiling the script.\n";
msg += getExceptionMessage( &try_catch );
throw std::exception( msg.c_str() );
}
Handle<Value> result = script->Run();
if ( result.IsEmpty() )
{
std::string msg = "An exception occured while executing the script.\n";
msg += getExceptionMessage( &try_catch );
throw std::exception( msg.c_str() );
}
if ( result->IsInt32() )
{
return result->Int32Value()==0?false:true;
}
return true;
}
Handle<String> ReadFile( const char* fileName )
{
FILE* f = fopen( fileName, "rb" );
if ( f == NULL )
{
return Handle<String>();
}
fseek( f, 0, SEEK_END );
int size = ftell( f );
rewind( f );
char* content = new char[size+1];
content[size] = '\0';
for( int i=0; i<size; )
{
int red = fread( &content[i], 1, size-i, f );
i += red;
}
fclose(f);
Handle<String> result = String::New(content, size);
delete[] content;
return result;
}
Handle<Value> Include( const Arguments& args )
{
HandleScope handleScope;
if ( args.Length() != 1 )
{
return ThrowException( String::New("Include has only one argument.") );
}
String::Utf8Value file(args[0]);
if ( *file==NULL )
{
return ThrowException( String::New("First argument of include must be a string.") );
}
Handle<String> source = ReadFile(*file);
if ( source.IsEmpty() )
{
std::string errMsg = "File not found '";
errMsg += *file;
errMsg += "'.\n";
return ThrowException( String::New(errMsg.c_str()) );
}
ExecuteScript( source, String::New(*file) );
return Undefined();
}
Handle<Value> Print( const Arguments& args )
{
for( int i = 0; i < args.Length(); i++ )
{
HandleScope handleScope;
String::Utf8Value str(args[i]);
const char* cstr = ToCString(str);
printf( "%s", cstr );
}
return Undefined();
}
Handle<Value> LoadStringFromResourceJS( const Arguments& args )
{
if ( args.Length() != 1 )
{
return ThrowException( v8::String::New("Wrong number of paremeters.") );
}
if ( !args[0]->IsString() )
{
return ThrowException( v8::String::New("First parameter must be a string.") );
}
v8::String::Value resourceName(args[0]);
TCHAR* t = reinterpret_cast<TCHAR*>(*resourceName);
return String::New( LoadStringFromResource(t).c_str() );
}
bool ReadAndExecute( char* fileName )
{
Handle<String> source = ReadFile(fileName);
if (source.IsEmpty())
{
printf("Error: cannot open file '%s'.\n", fileName );
return false;
}
return ExecuteScript( source, String::New(fileName) );
}
Handle<Value> AppInfoPropertyGetter(Local<String> property, const AccessorInfo& info)
{
String::AsciiValue ascii_property(property);
std::string s_property = *ascii_property;
if ( s_property == "AppName" )
{
return String::New(APPINFO_APPNAME);
}
if ( s_property == "Version" )
{
return String::New(APPINFO_VERSION);
}
if ( s_property == "Description" )
{
return String::New(APPINFO_DESCRIPTION);
}
if ( s_property == "Copyright" )
{
return String::New(APPINFO_COPYRIGHT);
}
return Undefined();
} | tectronics/jssunit | src/jssUnit-Console/scripting.cpp | C++ | bsd-3-clause | 8,245 |
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, Willow Garage, Inc.
* Copyright (c) 2014-2016, Open Source Robotics Foundation
* 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 Open Source Robotics Foundation 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 OWNER 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.
*/
/** @author Jia Pan */
#ifndef FCL_TRAVERSAL_MESHSHAPEDISTANCETRAVERSALNODE_H
#define FCL_TRAVERSAL_MESHSHAPEDISTANCETRAVERSALNODE_H
#include "fcl/geometry/shape/utility.h"
#include "fcl/narrowphase/detail/traversal/distance/bvh_shape_distance_traversal_node.h"
namespace fcl
{
namespace detail
{
/// @brief Traversal node for distance between mesh and shape
template <typename BV, typename Shape, typename NarrowPhaseSolver>
class MeshShapeDistanceTraversalNode
: public BVHShapeDistanceTraversalNode<BV, Shape>
{
public:
using S = typename BV::S;
MeshShapeDistanceTraversalNode();
/// @brief Distance testing between leaves (one triangle and one shape)
void leafTesting(int b1, int b2) const;
/// @brief Whether the traversal process can stop early
bool canStop(S c) const;
Vector3<S>* vertices;
Triangle* tri_indices;
S rel_err;
S abs_err;
const NarrowPhaseSolver* nsolver;
};
template <typename BV, typename Shape, typename NarrowPhaseSolver>
void meshShapeDistanceOrientedNodeLeafTesting(
int b1, int /* b2 */,
const BVHModel<BV>* model1,
const Shape& model2,
Vector3<typename BV::S>* vertices,
Triangle* tri_indices,
const Transform3<typename BV::S>& tf1,
const Transform3<typename BV::S>& tf2,
const NarrowPhaseSolver* nsolver,
bool enable_statistics,
int & num_leaf_tests,
const DistanceRequest<typename BV::S>& /* request */,
DistanceResult<typename BV::S>& result);
template <typename BV, typename Shape, typename NarrowPhaseSolver>
void distancePreprocessOrientedNode(
const BVHModel<BV>* model1,
Vector3<typename BV::S>* vertices,
Triangle* tri_indices,
int init_tri_id,
const Shape& model2,
const Transform3<typename BV::S>& tf1,
const Transform3<typename BV::S>& tf2,
const NarrowPhaseSolver* nsolver,
const DistanceRequest<typename BV::S>& /* request */,
DistanceResult<typename BV::S>& result);
/// @brief Initialize traversal node for distance computation between one mesh
/// and one shape, given the current transforms
template <typename BV, typename Shape, typename NarrowPhaseSolver>
bool initialize(
MeshShapeDistanceTraversalNode<BV, Shape, NarrowPhaseSolver>& node,
BVHModel<BV>& model1,
Transform3<typename BV::S>& tf1,
const Shape& model2,
const Transform3<typename BV::S>& tf2,
const NarrowPhaseSolver* nsolver,
const DistanceRequest<typename BV::S>& request,
DistanceResult<typename BV::S>& result,
bool use_refit = false, bool refit_bottomup = false);
/// @brief Traversal node for distance between mesh and shape, when mesh BVH is one of the oriented node (RSS, OBBRSS, kIOS)
template <typename Shape, typename NarrowPhaseSolver>
class MeshShapeDistanceTraversalNodeRSS
: public MeshShapeDistanceTraversalNode<
RSS<typename Shape::S>, Shape, NarrowPhaseSolver>
{
public:
using S = typename Shape::S;
MeshShapeDistanceTraversalNodeRSS();
void preprocess();
void postprocess();
S BVTesting(int b1, int b2) const;
void leafTesting(int b1, int b2) const;
};
template <typename Shape, typename NarrowPhaseSolver>
bool initialize(
MeshShapeDistanceTraversalNodeRSS<Shape, NarrowPhaseSolver>& node,
const BVHModel<RSS<typename Shape::S>>& model1,
const Transform3<typename Shape::S>& tf1,
const Shape& model2,
const Transform3<typename Shape::S>& tf2,
const NarrowPhaseSolver* nsolver,
const DistanceRequest<typename Shape::S>& request,
DistanceResult<typename Shape::S>& result);
template <typename Shape, typename NarrowPhaseSolver>
class MeshShapeDistanceTraversalNodekIOS
: public MeshShapeDistanceTraversalNode<kIOS<typename Shape::S>, Shape, NarrowPhaseSolver>
{
public:
using S = typename Shape::S;
MeshShapeDistanceTraversalNodekIOS();
void preprocess();
void postprocess();
S BVTesting(int b1, int b2) const;
void leafTesting(int b1, int b2) const;
};
/// @brief Initialize traversal node for distance computation between one mesh and one shape, specialized for kIOS type
template <typename Shape, typename NarrowPhaseSolver>
bool initialize(
MeshShapeDistanceTraversalNodekIOS<Shape, NarrowPhaseSolver>& node,
const BVHModel<kIOS<typename Shape::S>>& model1, const Transform3<typename Shape::S>& tf1,
const Shape& model2, const Transform3<typename Shape::S>& tf2,
const NarrowPhaseSolver* nsolver,
const DistanceRequest<typename Shape::S>& request,
DistanceResult<typename Shape::S>& result);
template <typename Shape, typename NarrowPhaseSolver>
class MeshShapeDistanceTraversalNodeOBBRSS
: public MeshShapeDistanceTraversalNode<OBBRSS<typename Shape::S>, Shape, NarrowPhaseSolver>
{
public:
using S = typename Shape::S;
MeshShapeDistanceTraversalNodeOBBRSS();
void preprocess();
void postprocess();
S BVTesting(int b1, int b2) const;
void leafTesting(int b1, int b2) const;
};
/// @brief Initialize traversal node for distance computation between one mesh and one shape, specialized for OBBRSS type
template <typename Shape, typename NarrowPhaseSolver>
bool initialize(
MeshShapeDistanceTraversalNodeOBBRSS<Shape, NarrowPhaseSolver>& node,
const BVHModel<OBBRSS<typename Shape::S>>& model1,
const Transform3<typename Shape::S>& tf1,
const Shape& model2,
const Transform3<typename Shape::S>& tf2,
const NarrowPhaseSolver* nsolver,
const DistanceRequest<typename Shape::S>& request,
DistanceResult<typename Shape::S>& result);
} // namespace detail
} // namespace fcl
#include "fcl/narrowphase/detail/traversal/distance/mesh_shape_distance_traversal_node-inl.h"
#endif
| hsu/fcl | include/fcl/narrowphase/detail/traversal/distance/mesh_shape_distance_traversal_node.h | C | bsd-3-clause | 7,388 |
<?php
use yii\helpers\Html;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\ExpenceSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Expences';
$this->params['breadcrumbs'][] = $this->title;
$search = "$('.search-button').click(function(){
$('.search-form').toggle(1000);
return false;
});";
$this->registerJs($search);
?>
<div class="expence-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Expence', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Advance Search', '#', ['class' => 'btn btn-info search-button']) ?>
</p>
<div class="search-form" style="display:none">
<?= $this->render('_search', ['model' => $searchModel]); ?>
</div>
<?php
$gridColumn = [
['class' => 'yii\grid\SerialColumn'],
[
'class' => 'kartik\grid\ExpandRowColumn',
'width' => '50px',
'value' => function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail' => function ($model, $key, $index, $column) {
return Yii::$app->controller->renderPartial('_expand', ['model' => $model]);
},
'headerOptions' => ['class' => 'kartik-sheet-style'],
'expandOneOnly' => true
],
['attribute' => 'id', 'hidden' => true],
'description',
'amount',
'date',
[
'attribute' => 'project_id',
'label' => 'Project',
'value' => function($model){
return $model->project->name;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map(\app\models\Project::find()->asArray()->all(), 'id', 'name'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Proman project', 'id' => 'grid-expence-search-project_id']
],
[
'class' => 'yii\grid\ActionColumn',
],
];
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumn,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-expence']],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<span class="glyphicon glyphicon-book"></span> ' . Html::encode($this->title),
],
// set a label for default menu
'export' => [
'label' => 'Page',
'fontAwesome' => true,
],
// your toolbar can include the additional full export menu
'toolbar' => [
'{export}',
ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumn,
'target' => ExportMenu::TARGET_BLANK,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]) ,
],
]); ?>
</div>
| djn21/proman | _protected/views/expence/index.php | PHP | bsd-3-clause | 3,652 |
package com.smartdevicelink.proxy.rpc.enums;
public enum DeliveryMode {
PROMPT,
DESTINATION,
QUEUE,
;
public static DeliveryMode valueForString(String value) {
try{
return valueOf(value);
}catch(Exception e){
return null;
}
}
}
| 914802951/sdl_android | sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/enums/DeliveryMode.java | Java | bsd-3-clause | 299 |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now
from zope.interface import implementer
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, List, Optional, Tuple
irc.RPL_WHOWASIP = "379"
@implementer(IPlugin, IModuleData, ICommand)
class WhowasCommand(ModuleData, Command):
name = "WhowasCommand"
core = True
def actions(self) -> List[Tuple[str, int, Callable]]:
return [ ("quit", 10, self.addUserToWhowas),
("remotequit", 10, self.addUserToWhowas),
("localquit", 10, self.addUserToWhowas) ]
def userCommands(self) -> List[Tuple[str, int, Command]]:
return [ ("WHOWAS", 1, self) ]
def load(self) -> None:
if "whowas" not in self.ircd.storage:
self.ircd.storage["whowas"] = {}
def verifyConfig(self, config: Dict[str, Any]) -> None:
if "whowas_duration" in config and not isinstance(config["whowas_duration"], str) and not isinstance(config["whowas_duration"], int):
raise ConfigValidationError("whowas_duration", "value must be an integer or a duration string")
if "whowas_max_entries" in config and (not isinstance(config["whowas_max_entries"], int) or config["whowas_max_entries"] < 0):
raise ConfigValidationError("whowas_max_entries", "invalid number")
def removeOldEntries(self, whowasEntries: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
expireDuration = durationToSeconds(self.ircd.config.get("whowas_duration", "1d"))
maxCount = self.ircd.config.get("whowas_max_entries", 10)
while whowasEntries and len(whowasEntries) > maxCount:
whowasEntries.pop(0)
expireDifference = timedelta(seconds=expireDuration)
expireTime = now() - expireDifference
while whowasEntries and whowasEntries[0]["when"] < expireTime:
whowasEntries.pop(0)
return whowasEntries
def addUserToWhowas(self, user: "IRCUser", reason: str, fromServer: "IRCServer" = None) -> None:
if not user.isRegistered():
# user never registered a nick, so no whowas entry to add
return
lowerNick = ircLower(user.nick)
allWhowas = self.ircd.storage["whowas"]
if lowerNick in allWhowas:
whowasEntries = allWhowas[lowerNick]
else:
whowasEntries = []
serverName = self.ircd.name
if user.uuid[:3] != self.ircd.serverID:
serverName = self.ircd.servers[user.uuid[:3]].name
whowasEntries.append({
"nick": user.nick,
"ident": user.ident,
"host": user.host(),
"realhost": user.realHost,
"ip": ipAddressToShow(user.ip),
"gecos": user.gecos,
"server": serverName,
"when": now()
})
whowasEntries = self.removeOldEntries(whowasEntries)
if whowasEntries:
allWhowas[lowerNick] = whowasEntries
elif lowerNick in allWhowas:
del allWhowas[lowerNick]
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]:
if not params:
user.sendSingleError("WhowasCmd", irc.ERR_NEEDMOREPARAMS, "WHOWAS", "Not enough parameters")
return None
lowerParam = ircLower(params[0])
if lowerParam not in self.ircd.storage["whowas"]:
user.sendSingleError("WhowasNick", irc.ERR_WASNOSUCHNICK, params[0], "There was no such nickname")
return None
return {
"nick": lowerParam,
"param": params[0]
}
def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool:
nick = data["nick"]
allWhowas = self.ircd.storage["whowas"]
whowasEntries = allWhowas[nick]
whowasEntries = self.removeOldEntries(whowasEntries)
if not whowasEntries:
del allWhowas[nick]
self.ircd.storage["whowas"] = allWhowas
user.sendMessage(irc.ERR_WASNOSUCHNICK, data["param"], "There was no such nickname")
return True
allWhowas[nick] = whowasEntries # Save back to the list excluding the removed entries
self.ircd.storage["whowas"] = allWhowas
for entry in whowasEntries:
entryNick = entry["nick"]
user.sendMessage(irc.RPL_WHOWASUSER, entryNick, entry["ident"], entry["host"], "*", entry["gecos"])
if self.ircd.runActionUntilValue("userhasoperpermission", user, "whowas-host", users=[user]):
user.sendMessage(irc.RPL_WHOWASIP, entryNick, "was connecting from {}@{} {}".format(entry["ident"], entry["realhost"], entry["ip"]))
user.sendMessage(irc.RPL_WHOISSERVER, entryNick, entry["server"], str(entry["when"]))
user.sendMessage(irc.RPL_ENDOFWHOWAS, nick, "End of WHOWAS")
return True
whowasCmd = WhowasCommand() | Heufneutje/txircd | txircd/modules/rfc/cmd_whowas.py | Python | bsd-3-clause | 4,564 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin, use {% url 'admin:index' %}
url(r'^' + settings.ADMIN_URL, include(admin.site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# User management
url(r'^users/', include("therapyinvoicing.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
url(r'^customers/', include("therapyinvoicing.customers.urls", namespace="customers")),
url(r'^customerinvoicing/', include("therapyinvoicing.customerinvoicing.urls", namespace="customerinvoicing")),
url(r'^kelainvoicing/', include("therapyinvoicing.kelainvoicing.urls", namespace="kelainvoicing")),
url(r'^api/', include("therapyinvoicing.api.urls", namespace="api")),
url(r'^reporting/', include("therapyinvoicing.reporting.urls", namespace="reporting")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request),
url(r'^403/$', default_views.permission_denied),
url(r'^404/$', default_views.page_not_found),
url(r'^500/$', default_views.server_error),
]
| ylitormatech/terapialaskutus | config/urls.py | Python | bsd-3-clause | 1,837 |
import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base = base
self.header_name = header_name
@property
def regex(self):
return '(%s)(.*)' % self.base
def header(self):
return 'HTTP_' + self.header_name.upper().replace('-', '_')
def __call__(self, doc, environ):
key = self.header()
if not key in environ:
return doc
prefix = environ[key]
def replacement(match):
base, path = match.groups()
return '%s/%s%s' % (base, prefix, path)
rewriter = URLRewriter(self.keys, self.regex, replacement)
return rewriter(doc)
class RewriteMiddleware(object):
def __init__(self, app, rewriter):
self.app = app
self.rewriter = rewriter
@staticmethod
def content_type(headers):
return dict([(k.lower(), v) for k, v in headers]).get('content-type')
def is_json(self, headers):
return 'json' in self.content_type(headers)
@staticmethod
def ok(status):
return status.startswith('20')
def rewrite(self, resp, environ):
doc = self.rewriter(self.json(resp), environ)
return json.dumps(doc)
def json(self, resp):
return json.loads(''.join(resp))
def __call__(self, environ, start_response):
# Set a local variable for the request
self.do_rewrite = False
# Our request local start response wrapper to grab the
# response headers
def sr(status, response_headers, exc_info=None):
if self.ok(status) and self.is_json(response_headers):
self.do_rewrite = True
# Call the original start_response
return start_response(status, response_headers, exc_info)
# call our app
resp = self.app(environ, sr)
# Our local variable should have been set to True if we should
# rewrite
if self.do_rewrite:
return [self.rewrite(resp, environ)]
return resp
def json_url_rewriter_filter_factory(global_conf, *args, **kw):
print(global_conf, args, kw)
raise Exception('Blastoff')
| ionrock/json_url_rewriter | json_url_rewriter/middleware.py | Python | bsd-3-clause | 2,398 |
Rainbows! do
name = 'project-status'
use :ThreadPool
case ENV['RACK_ENV'].to_sym
when :development
worker_processes 2
worker_connections 4
listen 9292
when :production
worker_processes 2
worker_connections 32
timeout 30
listen "unix:/var/run/geoloqi/#{name}.sock", :backlog => 4096
pid "/var/run/geoloqi/#{name}.pid"
stderr_path "/var/log/geoloqi/#{name}.log"
stdout_path "/var/log/geoloqi/#{name}.log"
###
# Hardcore performance tweaks, described here: https://github.com/blog/517-unicorn
###
# This loads the app in master, and then forks workers. Kill with USR2 and it will do a graceful restart using the block proceeding.
preload_app true
before_fork do |server, worker|
##
# When sent a USR2, Unicorn will suffix its pidfile with .oldbin and
# immediately start loading up a new version of itself (loaded with a new
# version of our app). When this new Unicorn is completely loaded
# it will begin spawning workers. The first worker spawned will check to
# see if an .oldbin pidfile exists. If so, this means we've just booted up
# a new Unicorn and need to tell the old one that it can now die. To do so
# we send it a QUIT.
#
# Using this method we get 0 downtime deploys.
old_pid = "/var/run/geoloqi/#{name}.pid.oldbin"
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
end
end
| aaronpk/Project-Status | rainbows_config.rb | Ruby | bsd-3-clause | 1,628 |
<!DOCTYPE html>
<html>
<head>
<title>Change source | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="../../../dist/public/carto.js"></script>
<style>
* {
box-sizing: border-box;
}
body, *{ margin: 0; padding: 0; }
#map {
position: absolute;
height: 100%;
width: 100%;
z-index: 0;
}
#controls {
position: absolute;
padding: 20px;
background: white;
top: 12px;
right: 12px;
box-shadow: 0 0 16px rgba(0, 0, 0, 0.12);
border-radius: 4px;
width: 200px;
color: #2E3C43;
z-index: 2;
}
#controls li {
list-style-type: none;
margin: 0 0 8px 0;
display: flex;
vertical-align: middle;
}
#controls li input {
margin: 0 8px 0 0;
}
#controls li label {
font: 12px/16px 'Open Sans';
cursor: pointer;
}
#controls li:last-child {
margin-bottom: 0;
}
#controls li:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="controls">
<ul>
<li onclick="setAllCities()">
<input type="radio" name="style" value="01" checked id="red">
<label for="red">All cities</label>
</li>
<li onclick="setEuropeCities()">
<input type="radio" name="style" value="02" id="green">
<label for="green">Europe cities</label>
</li>
<li onclick="setSpainCities()">
<input type="radio" name="style" value="03" id="blue">
<label for="blue">Spain cities</label>
</li>
</ul>
</div>
<script>
const map = L.map('map').setView([30, 0], 3);
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const client = new carto.Client({
apiKey: 'YOUR_API_KEY',
username: 'cartojs-test'
});
const source = new carto.source.SQL(`
SELECT *
FROM ne_10m_populated_places_simple
`);
const style = new carto.style.CartoCSS(`
#layer {
marker-width: 7;
marker-fill: #EE4D5A;
marker-line-color: #FFFFFF;
}
`);
const layer = new carto.layer.Layer(source, style);
client.addLayer(layer);
client.getLeafletLayer().addTo(map);
function setAllCities() {
source.setQuery(`
SELECT *
FROM ne_10m_populated_places_simple
`);
}
function setEuropeCities() {
source.setQuery(`
SELECT *
FROM ne_10m_populated_places_simple
WHERE adm0name IN (SELECT admin FROM ne_adm0_europe)
`);
}
function setSpainCities() {
source.setQuery(`
SELECT *
FROM ne_10m_populated_places_simple
WHERE adm0name = \'Spain\'
`);
}
</script>
</body>
</html>
| splashblot/cartodb.js | examples/public/layers/change-source-leaflet.html | HTML | bsd-3-clause | 3,322 |
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qpd_MainWindow w;
w.show();
return a.exec();
}
| errordeveloper/qpd-projects | basic/blank/main.cpp | C++ | bsd-3-clause | 181 |
TC_ARCH = cedarview
TC_VERS = 7.0
TC_KERNEL = 3.10.108
TC_GCC = 7.3.0
TC_GLIBC = 2.26
TC_DIST = cedarview-gcc730_glibc226_x86_64-GPL
TC_DIST_SITE_PATH = Intel%20x86%20Linux%203.10.108%20%28Cedarview%29
TC_TARGET = x86_64-pc-linux-gnu
TC_SYSROOT = $(TC_TARGET)/sys-root
include ../../mk/spksrc.tc.mk
| Zetten/spksrc | toolchain/syno-cedarview-7.0/Makefile | Makefile | bsd-3-clause | 302 |
def extractSweetjamtranslationsCom(item):
'''
Parser for 'sweetjamtranslations.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSweetjamtranslationsCom.py | Python | bsd-3-clause | 561 |
def extractMiratlsWordpressCom(item):
'''
Parser for 'miratls.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMiratlsWordpressCom.py | Python | bsd-3-clause | 554 |
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "svm.h"
char* line;
int max_line_len = 1024;
struct svm_node *x;
int max_nr_attr = 64;
struct svm_model* model;
int predict_probability=0;
void predict(FILE *input, FILE *output)
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm_get_svm_type(model);
int nr_class=svm_get_nr_class(model);
int *labels=(int *) malloc(nr_class*sizeof(int));
double *prob_estimates=NULL;
int j;
if(predict_probability)
{
if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
printf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
else
{
svm_get_labels(model,labels);
prob_estimates = (double *) malloc(nr_class*sizeof(double));
fprintf(output,"labels");
for(j=0;j<nr_class;j++)
fprintf(output," %d",labels[j]);
fprintf(output,"\n");
}
}
while(1)
{
int i = 0;
int c;
double target,v;
if (fscanf(input,"%lf",&target)==EOF)
break;
while(1)
{
if(i>=max_nr_attr-1) // need one more for index = -1
{
max_nr_attr *= 2;
x = (struct svm_node *) realloc(x,max_nr_attr*sizeof(struct svm_node));
}
do {
c = getc(input);
if(c=='\n' || c==EOF) goto out2;
} while(isspace(c));
ungetc(c,input);
if (fscanf(input,"%d:%lf",&x[i].index,&x[i].value) < 2)
{
fprintf(stderr,"Wrong input format at line %d\n", total+1);
exit(1);
}
++i;
}
out2:
x[i++].index = -1;
if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
{
v = svm_predict_probability(model,x,prob_estimates);
fprintf(output,"%g ",v);
for(j=0;j<nr_class;j++)
fprintf(output,"%g ",prob_estimates[j]);
fprintf(output,"\n");
}
else
{
v = svm_predict(model,x);
fprintf(output,"%g\n",v);
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
{
printf("Mean squared error = %g (regression)\n",error/total);
printf("Squared correlation coefficient = %g (regression)\n",
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))
);
}
else
printf("Accuracy = %g%% (%d/%d) (classification)\n",
(double)correct/total*100,correct,total);
if(predict_probability)
{
free(prob_estimates);
free(labels);
}
}
void exit_with_help()
{
printf(
"Usage: svm-predict [options] test_file model_file output_file\n"
"options:\n"
"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported\n"
);
exit(1);
}
int main(int argc, char **argv)
{
FILE *input, *output;
int i;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
switch(argv[i-1][1])
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
fprintf(stderr,"unknown option\n");
exit_with_help();
}
}
if(i>=argc)
exit_with_help();
input = fopen(argv[i],"r");
if(input == NULL)
{
fprintf(stderr,"can't open input file %s\n",argv[i]);
exit(1);
}
output = fopen(argv[i+2],"w");
if(output == NULL)
{
fprintf(stderr,"can't open output file %s\n",argv[i+2]);
exit(1);
}
if((model=svm_load_model(argv[i+1]))==0)
{
fprintf(stderr,"can't open model file %s\n",argv[i+1]);
exit(1);
}
line = (char *) malloc(max_line_len*sizeof(char));
x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
if(predict_probability)
if(svm_check_probability_model(model)==0)
{
fprintf(stderr,"Model does not support probabiliy estimates\n");
exit(1);
}
predict(input,output);
svm_destroy_model(model);
free(line);
free(x);
fclose(input);
fclose(output);
return 0;
}
| npinto/libsvm-2.84_varma-np | svm-predict.c | C | bsd-3-clause | 4,007 |
from textwrap import dedent
from sympy import (
symbols, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix,
factorial, true)
from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
from sympy.utilities.iterables import (
_partition, _set_partitions, binary_partitions, bracelets, capture,
cartes, common_prefix, common_suffix, dict_merge, flatten,
generate_bell, generate_derangements, generate_involutions,
generate_oriented_forest, group, has_dups, kbins, minlex, multiset,
multiset_combinations, multiset_partitions, multiset_permutations,
necklaces, numbered_symbols, ordered, partitions, permutations,
postfixes, postorder_traversal, prefixes, reshape, rotate_left,
rotate_right, runs, sift, subsets, take, topological_sort, unflatten,
uniq, variations)
from sympy.core.singleton import S
from sympy.functions.elementary.piecewise import Piecewise, ExprCondPair
from sympy.utilities.pytest import raises
w, x, y, z = symbols('w,x,y,z')
def test_postorder_traversal():
expr = z + w*(x + y)
expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z]
assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(expr, keys=True)) == expected
expr = Piecewise((x, x < 1), (x**2, True))
expected = [
x, 1, x, x < 1, ExprCondPair(x, x < 1),
2, x, x**2, true,
ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True))
]
assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(
[expr], keys=default_sort_key)) == expected + [[expr]]
assert list(postorder_traversal(Integral(x**2, (x, 0, 1)),
keys=default_sort_key)) == [
2, x, x**2, 0, 1, x, Tuple(x, 0, 1),
Integral(x**2, Tuple(x, 0, 1))
]
assert list(postorder_traversal(('abc', ('d', 'ef')))) == [
'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))]
def test_flatten():
assert flatten((1, (1,))) == [1, 1]
assert flatten((x, (x,))) == [x, x]
ls = [[(-2, -1), (1, 2)], [(0, 0)]]
assert flatten(ls, levels=0) == ls
assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)]
assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0]
assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0]
raises(ValueError, lambda: flatten(ls, levels=-1))
class MyOp(Basic):
pass
assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z]
assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z]
assert flatten(set([1, 11, 2])) == list(set([1, 11, 2]))
def test_group():
assert group([]) == []
assert group([], multiple=False) == []
assert group([1]) == [[1]]
assert group([1], multiple=False) == [(1, 1)]
assert group([1, 1]) == [[1, 1]]
assert group([1, 1], multiple=False) == [(1, 2)]
assert group([1, 1, 1]) == [[1, 1, 1]]
assert group([1, 1, 1], multiple=False) == [(1, 3)]
assert group([1, 2, 1]) == [[1], [2], [1]]
assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)]
assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]]
assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2),
(2, 3), (1, 1), (3, 2)]
def test_subsets():
# combinations
assert list(subsets([1, 2, 3], 0)) == [()]
assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)]
assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)]
l = list(range(4))
assert list(subsets(l, 0, repetition=True)) == [()]
assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 1), (1, 2),
(1, 3), (2, 2), (2, 3),
(3, 3)]
assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1),
(0, 0, 2), (0, 0, 3),
(0, 1, 1), (0, 1, 2),
(0, 1, 3), (0, 2, 2),
(0, 2, 3), (0, 3, 3),
(1, 1, 1), (1, 1, 2),
(1, 1, 3), (1, 2, 2),
(1, 2, 3), (1, 3, 3),
(2, 2, 2), (2, 2, 3),
(2, 3, 3), (3, 3, 3)]
assert len(list(subsets(l, 4, repetition=True))) == 35
assert list(subsets(l[:2], 3, repetition=False)) == []
assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(1, 1, 1)]
assert list(subsets([1, 2], repetition=True)) == \
[(), (1,), (2,), (1, 1), (1, 2), (2, 2)]
assert list(subsets([1, 2], repetition=False)) == \
[(), (1,), (2,), (1, 2)]
assert list(subsets([1, 2, 3], 2)) == \
[(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 2, repetition=True)) == \
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
def test_variations():
# permutations
l = list(range(4))
assert list(variations(l, 0, repetition=False)) == [()]
assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)]
assert list(variations(l, 0, repetition=True)) == [()]
assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 0), (1, 1),
(1, 2), (1, 3), (2, 0),
(2, 1), (2, 2), (2, 3),
(3, 0), (3, 1), (3, 2),
(3, 3)]
assert len(list(variations(l, 3, repetition=True))) == 64
assert len(list(variations(l, 4, repetition=True))) == 256
assert list(variations(l[:2], 3, repetition=False)) == []
assert list(variations(l[:2], 3, repetition=True)) == [
(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)
]
def test_cartes():
assert list(cartes([1, 2], [3, 4, 5])) == \
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
assert list(cartes()) == [()]
assert list(cartes('a')) == [('a',)]
assert list(cartes('a', repeat=2)) == [('a', 'a')]
assert list(cartes(list(range(2)))) == [(0,), (1,)]
def test_numbered_symbols():
s = numbered_symbols(cls=Dummy)
assert isinstance(next(s), Dummy)
def test_sift():
assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
def test_take():
X = numbered_symbols()
assert take(X, 5) == list(symbols('x0:5'))
assert take(X, 5) == list(symbols('x5:10'))
assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_dict_merge():
assert dict_merge({}, {1: x, y: z}) == {1: x, y: z}
assert dict_merge({1: x, y: z}, {}) == {1: x, y: z}
assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z}
def test_prefixes():
assert list(prefixes([])) == []
assert list(prefixes([1])) == [[1]]
assert list(prefixes([1, 2])) == [[1], [1, 2]]
assert list(prefixes([1, 2, 3, 4, 5])) == \
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
def test_postfixes():
assert list(postfixes([])) == []
assert list(postfixes([1])) == [[1]]
assert list(postfixes([1, 2])) == [[2], [1, 2]]
assert list(postfixes([1, 2, 3, 4, 5])) == \
[[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
def test_topological_sort():
V = [2, 3, 5, 7, 8, 9, 10, 11]
E = [(7, 11), (7, 8), (5, 11),
(3, 8), (3, 10), (11, 2),
(11, 9), (11, 10), (8, 9)]
assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10]
assert topological_sort((V, E), key=lambda v: -v) == \
[7, 5, 11, 3, 10, 8, 9, 2]
raises(ValueError, lambda: topological_sort((V, E + [(10, 7)])))
def test_rotate():
A = [0, 1, 2, 3, 4]
assert rotate_left(A, 2) == [2, 3, 4, 0, 1]
assert rotate_right(A, 1) == [4, 0, 1, 2, 3]
A = []
B = rotate_right(A, 1)
assert B == []
B.append(1)
assert A == []
B = rotate_left(A, 1)
assert B == []
B.append(1)
assert A == []
def test_multiset_partitions():
A = [0, 1, 2, 3, 4]
assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]]
assert len(list(multiset_partitions(A, 4))) == 10
assert len(list(multiset_partitions(A, 3))) == 25
assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [
[[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]],
[[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]]
assert list(multiset_partitions([1, 1, 2, 2], 2)) == [
[[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]],
[[1, 2], [1, 2]]]
assert list(multiset_partitions([1, 2, 3, 4], 2)) == [
[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
assert list(multiset_partitions([1, 2, 2], 2)) == [
[[1, 2], [2]], [[1], [2, 2]]]
assert list(multiset_partitions(3)) == [
[[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]],
[[0], [1], [2]]]
assert list(multiset_partitions(3, 2)) == [
[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]]
assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]]
assert list(multiset_partitions([1] * 3)) == [
[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
a = [3, 2, 1]
assert list(multiset_partitions(a)) == \
list(multiset_partitions(sorted(a)))
assert list(multiset_partitions(a, 5)) == []
assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]]
assert list(multiset_partitions(a + [4], 5)) == []
assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]]
assert list(multiset_partitions(2, 5)) == []
assert list(multiset_partitions(2, 1)) == [[[0, 1]]]
assert list(multiset_partitions('a')) == [[['a']]]
assert list(multiset_partitions('a', 2)) == []
assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]]
assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]]
assert list(multiset_partitions('aaa', 1)) == [['aaa']]
assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]]
def test_multiset_combinations():
ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips',
'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss']
assert [''.join(i) for i in
list(multiset_combinations('mississippi', 3))] == ans
M = multiset('mississippi')
assert [''.join(i) for i in
list(multiset_combinations(M, 3))] == ans
assert [''.join(i) for i in multiset_combinations(M, 30)] == []
assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]]
assert len(list(multiset_combinations('a', 3))) == 0
assert len(list(multiset_combinations('a', 0))) == 1
assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']]
def test_multiset_permutations():
ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab',
'byba', 'yabb', 'ybab', 'ybba']
assert [''.join(i) for i in multiset_permutations('baby')] == ans
assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans
assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]]
assert list(multiset_permutations([0, 2, 1], 2)) == [
[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
assert len(list(multiset_permutations('a', 0))) == 1
assert len(list(multiset_permutations('a', 3))) == 0
def test():
for i in range(1, 7):
print(i)
for p in multiset_permutations([0, 0, 1, 0, 1], i):
print(p)
assert capture(lambda: test()) == dedent('''\
1
[0]
[1]
2
[0, 0]
[0, 1]
[1, 0]
[1, 1]
3
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
4
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]
5
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[0, 0, 1, 1, 0]
[0, 1, 0, 0, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 0]
[1, 0, 0, 0, 1]
[1, 0, 0, 1, 0]
[1, 0, 1, 0, 0]
[1, 1, 0, 0, 0]
6\n''')
def test_partitions():
assert [p.copy() for p in partitions(6, k=2)] == [
{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]
assert [p.copy() for p in partitions(6, k=3)] == [
{3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2},
{1: 4, 2: 1}, {1: 6}]
assert [p.copy() for p in partitions(6, k=2, m=2)] == []
assert [p.copy() for p in partitions(8, k=4, m=3)] == [
{4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [
i.copy() for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i)
and sum(i.values()) <=3]
assert [p.copy() for p in partitions(S(3), m=2)] == [
{3: 1}, {1: 1, 2: 1}]
assert [i.copy() for i in partitions(4, k=3)] == [
{1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [
i.copy() for i in partitions(4) if all(k <= 3 for k in i)]
raises(ValueError, lambda: list(partitions(3, 0)))
# Consistency check on output of _partitions and RGS_unrank.
# This provides a sanity test on both routines. Also verifies that
# the total number of partitions is the same in each case.
# (from pkrathmann2)
for n in range(2, 6):
i = 0
for m, q in _set_partitions(n):
assert q == RGS_unrank(i, n)
i = i+1
assert i == RGS_enum(n)
def test_binary_partitions():
assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1],
[4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1],
[4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2],
[2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1],
[2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
assert len([j[:] for j in binary_partitions(16)]) == 36
def test_bell_perm():
assert [len(list(generate_bell(i))) for i in range(1, 7)] == [
factorial(i) for i in range(1, 7)]
assert list(generate_bell(3)) == [
(0, 1, 2), (1, 0, 2), (1, 2, 0), (2, 1, 0), (2, 0, 1), (0, 2, 1)]
def test_involutions():
lengths = [1, 2, 4, 10, 26, 76]
for n, N in enumerate(lengths):
i = list(generate_involutions(n + 1))
assert len(i) == N
assert len(set([Permutation(j)**2 for j in i])) == 1
def test_derangements():
assert len(list(generate_derangements(list(range(6))))) == 265
assert ''.join(''.join(i) for i in generate_derangements('abcde')) == (
'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd'
'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab'
'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb'
'edbacedbca')
assert list(generate_derangements([0, 1, 2, 3])) == [
[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1],
[2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]]
assert list(generate_derangements([0, 1, 2, 2])) == [
[2, 2, 0, 1], [2, 2, 1, 0]]
def test_necklaces():
def count(n, k, f):
return len(list(necklaces(n, k, f)))
m = []
for i in range(1, 8):
m.append((
i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1)))
assert Matrix(m) == Matrix([
[1, 2, 2, 3],
[2, 3, 3, 6],
[3, 4, 4, 10],
[4, 6, 6, 21],
[5, 8, 8, 39],
[6, 14, 13, 92],
[7, 20, 18, 198]])
def test_generate_oriented_forest():
assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0],
[0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2],
[0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0],
[0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0],
[0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
assert len(list(generate_oriented_forest(10))) == 1842
def test_unflatten():
r = list(range(10))
assert unflatten(r) == list(zip(r[::2], r[1::2]))
assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])]
raises(ValueError, lambda: unflatten(list(range(10)), 3))
raises(ValueError, lambda: unflatten(list(range(10)), -2))
def test_common_prefix_suffix():
assert common_prefix([], [1]) == []
assert common_prefix(list(range(3))) == [0, 1, 2]
assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2]
assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2]
assert common_prefix([1, 2, 3], [1, 3, 5]) == [1]
assert common_suffix([], [1]) == []
assert common_suffix(list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(4))) == []
assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3]
assert common_suffix([1, 2, 3], [9, 7, 3]) == [3]
def test_minlex():
assert minlex([1, 2, 0]) == (0, 1, 2)
assert minlex((1, 2, 0)) == (0, 1, 2)
assert minlex((1, 0, 2)) == (0, 2, 1)
assert minlex((1, 0, 2), directed=False) == (0, 1, 2)
assert minlex('aba') == 'aab'
def test_ordered():
assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]]
assert list(ordered((x, y), hash, default=False)) == \
list(ordered((y, x), hash, default=False))
assert list(ordered((x, y))) == [x, y]
seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]],
(lambda x: len(x), lambda x: sum(x))]
assert list(ordered(seq, keys, default=False, warn=False)) == \
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
raises(ValueError, lambda:
list(ordered(seq, keys, default=False, warn=True)))
def test_runs():
assert runs([]) == []
assert runs([1]) == [[1]]
assert runs([1, 1]) == [[1], [1]]
assert runs([1, 1, 2]) == [[1], [1, 2]]
assert runs([1, 2, 1]) == [[1, 2], [1]]
assert runs([2, 1, 1]) == [[2], [1], [1]]
from operator import lt
assert runs([2, 1, 1], lt) == [[2, 1], [1]]
def test_reshape():
seq = list(range(1, 9))
assert reshape(seq, [4]) == \
[[1, 2, 3, 4], [5, 6, 7, 8]]
assert reshape(seq, (4,)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, 2)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, [2])) == \
[(1, 2, [3, 4]), (5, 6, [7, 8])]
assert reshape(seq, ((2,), [2])) == \
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
assert reshape(seq, (1, [2], 1)) == \
[(1, [2, 3], 4), (5, [6, 7], 8)]
assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
assert reshape(tuple(seq), ([1], 1, (2,))) == \
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
assert reshape(list(range(12)), [2, [3], set([2]), (1, (3,), 1)]) == \
[[0, 1, [2, 3, 4], set([5, 6]), (7, (8, 9, 10), 11)]]
def test_uniq():
assert list(uniq(p.copy() for p in partitions(4))) == \
[{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}]
assert list(uniq(x % 2 for x in range(5))) == [0, 1]
assert list(uniq('a')) == ['a']
assert list(uniq('ababc')) == list('abc')
assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]]
assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \
[([1], 2, 2), (2, [1], 2), (2, 2, [1])]
assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \
[2, 3, 4, [2], [1], [3]]
def test_kbins():
assert len(list(kbins('1123', 2, ordered=1))) == 24
assert len(list(kbins('1123', 2, ordered=11))) == 36
assert len(list(kbins('1123', 2, ordered=10))) == 10
assert len(list(kbins('1123', 2, ordered=0))) == 5
assert len(list(kbins('1123', 2, ordered=None))) == 3
def test():
for ordered in [None, 0, 1, 10, 11]:
print('ordered =', ordered)
for p in kbins([0, 0, 1], 2, ordered=ordered):
print(' ', p)
assert capture(lambda : test()) == dedent('''\
ordered = None
[[0], [0, 1]]
[[0, 0], [1]]
ordered = 0
[[0, 0], [1]]
[[0, 1], [0]]
ordered = 1
[[0], [0, 1]]
[[0], [1, 0]]
[[1], [0, 0]]
ordered = 10
[[0, 0], [1]]
[[1], [0, 0]]
[[0, 1], [0]]
[[0], [0, 1]]
ordered = 11
[[0], [0, 1]]
[[0, 0], [1]]
[[0], [1, 0]]
[[0, 1], [0]]
[[1], [0, 0]]
[[1, 0], [0]]\n''')
def test():
for ordered in [None, 0, 1, 10, 11]:
print('ordered =', ordered)
for p in kbins(list(range(3)), 2, ordered=ordered):
print(' ', p)
assert capture(lambda : test()) == dedent('''\
ordered = None
[[0], [1, 2]]
[[0, 1], [2]]
ordered = 0
[[0, 1], [2]]
[[0, 2], [1]]
[[0], [1, 2]]
ordered = 1
[[0], [1, 2]]
[[0], [2, 1]]
[[1], [0, 2]]
[[1], [2, 0]]
[[2], [0, 1]]
[[2], [1, 0]]
ordered = 10
[[0, 1], [2]]
[[2], [0, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[0], [1, 2]]
[[1, 2], [0]]
ordered = 11
[[0], [1, 2]]
[[0, 1], [2]]
[[0], [2, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[1, 0], [2]]
[[1], [2, 0]]
[[1, 2], [0]]
[[2], [0, 1]]
[[2, 0], [1]]
[[2], [1, 0]]
[[2, 1], [0]]\n''')
def test_has_dups():
assert has_dups(set()) is False
assert has_dups(list(range(3))) is False
assert has_dups([1, 2, 1]) is True
def test__partition():
assert _partition('abcde', [1, 0, 1, 2, 0]) == [
['b', 'e'], ['a', 'c'], ['d']]
assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [
['b', 'e'], ['a', 'c'], ['d']]
output = (3, [1, 0, 1, 2, 0])
assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']]
| hrashk/sympy | sympy/utilities/tests/test_iterables.py | Python | bsd-3-clause | 24,090 |
/*
* Copyright (c) 2015, Ford Motor Company
* 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 the Ford Motor Company 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.
*/
#include "gtest/gtest.h"
#include "utils/lock.h"
namespace test {
namespace components {
namespace utils_test {
using sync_primitives::Lock;
using sync_primitives::RecursiveLock;
TEST(LockBoostTest, TestNonRecursive) {
// Create Lock object
Lock test_mutex;
// Lock mutex
test_mutex.Acquire();
// Check if created mutex is non-recursive
EXPECT_FALSE(test_mutex.Try());
// Release mutex before destroy
test_mutex.Release();
}
TEST(LockBoostTest, TestRecursive) {
// Create Lock object
RecursiveLock test_mutex;
// Lock mutex
test_mutex.Acquire();
// Check if created mutex is recursive
EXPECT_TRUE(test_mutex.Try());
// Release mutex before destroy
test_mutex.Release();
test_mutex.Release();
}
TEST(LockBoostTest, ReleaseMutex_ExpectMutexReleased) {
// Create Lock object (non-recursive mutex)
Lock test_mutex;
// Lock mutex
test_mutex.Acquire();
// Release mutex
test_mutex.Release();
// Try to lock it again. If released expect true
EXPECT_TRUE(test_mutex.Try());
test_mutex.Release();
}
TEST(LockBoostTest, TryLockNonRecursiveMutex_ExpectMutexNotLockedTwice) {
// Create Lock object (non-recursive mutex)
Lock test_mutex;
// Lock mutex
test_mutex.Try();
// Try to lock it again. If locked expect false
EXPECT_FALSE(test_mutex.Try());
test_mutex.Release();
}
TEST(LockBoostTest, TryLockRecursiveMutex_ExpectMutexLockedTwice) {
// Create Lock object (recursive mutex)
RecursiveLock test_mutex;
// Lock mutex
test_mutex.Try();
// Try to lock it again. Expect true and internal counter increase
EXPECT_TRUE(test_mutex.Try());
// Release mutex twice as was locked twice.
// Every Release() will decrement internal counter
test_mutex.Release();
test_mutex.Release();
}
} // namespace utils_test
} // namespace components
} // namespace test
| smartdevicelink/sdl_core | src/components/utils/test/lock_boost_test.cc | C++ | bsd-3-clause | 3,407 |
import { IRangeElem } from './IRangeElem';
import { IIterator } from '../../base/iterator';
export declare class SingleRangeElem implements IRangeElem {
readonly from: number;
constructor(from: number);
get step(): number;
get to(): number;
get isAll(): boolean;
get isSingle(): boolean;
get isUnbound(): boolean;
size(size?: number): number;
clone(): SingleRangeElem;
contains(value: number, size?: number): boolean;
reverse(): SingleRangeElem;
invert(index: number, size?: number): number;
iter(size?: number): IIterator<number>;
get __iterator__(): IIterator<number>;
toString(): string;
}
| datavisyn/tdp_core | dist/range/internal/SingleRangeElem.d.ts | TypeScript | bsd-3-clause | 653 |
/*
* Android SDK for Piwik
*
* @link https://github.com/piwik/piwik-android-sdk
* @license https://github.com/piwik/piwik-sdk-android/blob/master/LICENSE BSD-3 Clause
*/
package org.piwik.sdk;
import android.support.annotation.NonNull;
import org.piwik.sdk.dispatcher.Dispatcher;
import java.util.HashMap;
/**
* This objects represents one query to Piwik.
* For each event send to Piwik a TrackMe gets created, either explicitly by you or implicitly by the Tracker.
*/
public class TrackMe {
private static final int DEFAULT_QUERY_CAPACITY = 14;
private final HashMap<String, String> mQueryParams = new HashMap<>(DEFAULT_QUERY_CAPACITY);
private final CustomVariables mScreenCustomVariable = new CustomVariables();
protected synchronized TrackMe set(@NonNull String key, String value) {
if (value == null)
mQueryParams.remove(key);
else if (value.length() > 0)
mQueryParams.put(key, value);
return this;
}
/**
* You can set any additional Tracking API Parameters within the SDK.
* This includes for example the local time (parameters h, m and s).
* <pre>
* set(QueryParams.HOURS, "10");
* set(QueryParams.MINUTES, "45");
* set(QueryParams.SECONDS, "30");
* </pre>
*
* @param key query params name
* @param value value
* @return tracker instance
*/
public synchronized TrackMe set(@NonNull QueryParams key, String value) {
set(key.toString(), value);
return this;
}
public synchronized TrackMe set(@NonNull QueryParams key, int value) {
set(key, Integer.toString(value));
return this;
}
public synchronized TrackMe set(@NonNull QueryParams key, float value) {
set(key, Float.toString(value));
return this;
}
public synchronized TrackMe set(@NonNull QueryParams key, long value) {
set(key, Long.toString(value));
return this;
}
public synchronized boolean has(@NonNull QueryParams queryParams) {
return mQueryParams.containsKey(queryParams.toString());
}
/**
* Only sets the value if it doesn't exist.
*
* @param key type
* @param value value
* @return this (for chaining)
*/
public synchronized TrackMe trySet(@NonNull QueryParams key, int value) {
return trySet(key, String.valueOf(value));
}
/**
* Only sets the value if it doesn't exist.
*
* @param key type
* @param value value
* @return this (for chaining)
*/
public synchronized TrackMe trySet(@NonNull QueryParams key, float value) {
return trySet(key, String.valueOf(value));
}
public synchronized TrackMe trySet(@NonNull QueryParams key, long value) {
return trySet(key, String.valueOf(value));
}
/**
* Only sets the value if it doesn't exist.
*
* @param key type
* @param value value
* @return this (for chaining)
*/
public synchronized TrackMe trySet(@NonNull QueryParams key, String value) {
if (!has(key))
set(key, value);
return this;
}
/**
* The tracker calls this to build the final query to be sent via HTTP
*
* @return the query, but without the base URL
*/
public synchronized String build() {
set(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, mScreenCustomVariable.toString());
return Dispatcher.urlEncodeUTF8(mQueryParams);
}
public synchronized String get(@NonNull QueryParams queryParams) {
return mQueryParams.get(queryParams.toString());
}
/**
* Just like {@link Tracker#setVisitCustomVariable(int, String, String)} but only valid per screen.
* Only takes effect when setting prior to tracking the screen view.
*/
public synchronized TrackMe setScreenCustomVariable(int index, String name, String value) {
mScreenCustomVariable.put(index, name, value);
return this;
}
public synchronized CustomVariables getScreenCustomVariable() {
return mScreenCustomVariable;
}
}
| seancunningham/piwik-sdk-android | piwik-sdk/src/main/java/org/piwik/sdk/TrackMe.java | Java | bsd-3-clause | 4,126 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Kabupaten;
/**
* KabupatenSearch represents the model behind the search form about `app\models\Kabupaten`.
*/
class KabupatenSearch extends Kabupaten
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['kode_kabupaten', 'nama_kabupaten', 'kode_provinsi'], 'safe'],
[['is_kota'], 'integer'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Kabupaten::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'is_kota' => $this->is_kota,
]);
$query->andFilterWhere(['like', 'kode_kabupaten', $this->kode_kabupaten])
->andFilterWhere(['like', 'nama_kabupaten', $this->nama_kabupaten])
->andFilterWhere(['like', 'kode_provinsi', $this->kode_provinsi]);
return $dataProvider;
}
}
| TutorialPemrogramanID/dekranasda | models/KabupatenSearch.php | PHP | bsd-3-clause | 1,704 |
import { AppRegistry } from "react-native-web";
import { mount } from "enzyme";
import {
addSerializers,
compose,
enzymeTreeSerializer,
justChildren,
meltNative,
minimaliseTransform,
minimalWebTransform,
print,
propsNoChildren,
replaceTransform,
rnwTransform
} from "@times-components/jest-serializer";
import shared from "./shared.base";
export default () => {
addSerializers(
expect,
enzymeTreeSerializer(),
compose(
print,
minimalWebTransform,
minimaliseTransform(
(value, key) => key === "style" || key === "className"
),
replaceTransform({
CardComponent: justChildren,
CardContent: justChildren,
Gradient: propsNoChildren,
Loading: justChildren,
TimesImage: propsNoChildren,
...meltNative
}),
rnwTransform(AppRegistry)
)
);
shared(mount);
};
| newsuk/times-components | packages/card/__tests__/shared.js | JavaScript | bsd-3-clause | 891 |
module AutoBrewster
class Screenshot
attr_accessor :server,
:path,
:url_paths,
:screen_widths,
:failed_fast
def initialize(server, path, url_paths, screen_widths)
@server = server
@path = path
@url_paths = url_paths
@screen_widths = screen_widths
end
def capture(output_directory)
@url_paths.each do |label, path|
@screen_widths.each do |width|
output_path = get_output_path(output_directory, label, width)
if File.exist?(output_path)
puts "Screenshot already exists for #{label} at #{width}. Skipping..."
else
puts `phantomjs #{snap_js_path} "#{get_url(path)}" "#{width}" "#{output_path}"`
end
end
end
end
def compare_captured_screens(failfast = false)
create_diff_dir
failures = 0
@url_paths.each do |label, path|
@screen_widths.each do |width|
check_source_compare_screens_exist(label, width)
source_path = get_output_path(:source, label, width)
compare_path = get_output_path(:compare, label, width)
diff_path = get_output_path(:diff, label, width)
output = `compare -fuzz 20% -metric AE -highlight-color blue #{source_path} #{compare_path} #{diff_path} 2>&1`
failures += get_failure_count(output, label, width)
if failfast
@failed_fast = true
exit 1
end
end
end
exit 1 if failures > 0
end
def check_source_compare_screens_exist(label, width)
[get_output_path(:source, label, width), get_output_path(:compare, label, width)].each do |path|
raise "Screenshot at #{path} does not exist" unless File.exist?(path)
end
end
def clear_source_screens
clear_screenshot_directory(:source)
end
def clear_compare_screens
clear_screenshot_directory(:compare)
end
def clear_diff_screens
clear_screenshot_directory(:diff)
end
private
def get_output_path(directory, label, width)
"#{@path}/screens/#{directory}/#{label}-#{width}.jpg"
end
def get_url(path)
"#{@server.get_host_with_protocol_and_port}#{path}"
end
def create_diff_dir
FileUtils.mkdir_p("#{@path}/screens/diff")
end
def clear_screenshot_directory(directory)
FileUtils.rm_rf Dir.glob("#{@path}/screens/#{directory}/*.jpg")
end
def snap_js_path
File.expand_path('../../../snap.js', __FILE__)
end
def get_failure_count(output, label, width)
if output.strip! != "0"
puts "#{label} at #{width} wide doesn't match source screen"
return 1
end
return 0
end
end
end
| madetech/autobrewster | lib/auto_brewster/screenshot.rb | Ruby | bsd-3-clause | 2,785 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/onc/onc_translator.h"
#include <string>
#include "base/basictypes.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/values.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/onc/onc_constants.h"
#include "chromeos/network/onc/onc_signature.h"
#include "chromeos/network/onc/onc_translation_tables.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace onc {
namespace {
// Converts |str| to a base::Value of the given |type|. If the conversion fails,
// returns NULL.
scoped_ptr<base::Value> ConvertStringToValue(const std::string& str,
base::Value::Type type) {
base::Value* value;
if (type == base::Value::TYPE_STRING) {
value = base::Value::CreateStringValue(str);
} else {
value = base::JSONReader::Read(str);
}
if (value == NULL || value->GetType() != type) {
delete value;
value = NULL;
}
return make_scoped_ptr(value);
}
// This class implements the translation of properties from the given
// |shill_dictionary| to a new ONC object of signature |onc_signature|. Using
// recursive calls to CreateTranslatedONCObject of new instances, nested objects
// are translated.
class ShillToONCTranslator {
public:
ShillToONCTranslator(const base::DictionaryValue& shill_dictionary,
const OncValueSignature& onc_signature)
: shill_dictionary_(&shill_dictionary),
onc_signature_(&onc_signature) {
field_translation_table_ = GetFieldTranslationTable(onc_signature);
}
// Translates the associated Shill dictionary and creates an ONC object of the
// given signature.
scoped_ptr<base::DictionaryValue> CreateTranslatedONCObject();
private:
void TranslateEthernet();
void TranslateOpenVPN();
void TranslateVPN();
void TranslateWiFiWithState();
void TranslateCellularWithState();
void TranslateNetworkWithState();
// Creates an ONC object from |dictionary| according to the signature
// associated to |onc_field_name| and adds it to |onc_object_| at
// |onc_field_name|.
void TranslateAndAddNestedObject(const std::string& onc_field_name,
const base::DictionaryValue& dictionary);
// Creates an ONC object from |shill_dictionary_| according to the signature
// associated to |onc_field_name| and adds it to |onc_object_| at
// |onc_field_name|.
void TranslateAndAddNestedObject(const std::string& onc_field_name);
// Applies function CopyProperty to each field of |value_signature| and its
// base signatures.
void CopyPropertiesAccordingToSignature(
const OncValueSignature* value_signature);
// Applies function CopyProperty to each field of |onc_signature_| and its
// base signatures.
void CopyPropertiesAccordingToSignature();
// If |shill_property_name| is defined in |field_signature|, copies this
// entry from |shill_dictionary_| to |onc_object_| if it exists.
void CopyProperty(const OncFieldSignature* field_signature);
// If existent, translates the entry at |shill_property_name| in
// |shill_dictionary_| using |table|. It is an error if no matching table
// entry is found. Writes the result as entry at |onc_field_name| in
// |onc_object_|.
void TranslateWithTableAndSet(const std::string& shill_property_name,
const StringTranslationEntry table[],
const std::string& onc_field_name);
const base::DictionaryValue* shill_dictionary_;
const OncValueSignature* onc_signature_;
const FieldTranslationEntry* field_translation_table_;
scoped_ptr<base::DictionaryValue> onc_object_;
DISALLOW_COPY_AND_ASSIGN(ShillToONCTranslator);
};
scoped_ptr<base::DictionaryValue>
ShillToONCTranslator::CreateTranslatedONCObject() {
onc_object_.reset(new base::DictionaryValue);
if (onc_signature_ == &kNetworkWithStateSignature) {
TranslateNetworkWithState();
} else if (onc_signature_ == &kEthernetSignature) {
TranslateEthernet();
} else if (onc_signature_ == &kVPNSignature) {
TranslateVPN();
} else if (onc_signature_ == &kOpenVPNSignature) {
TranslateOpenVPN();
} else if (onc_signature_ == &kWiFiWithStateSignature) {
TranslateWiFiWithState();
} else if (onc_signature_ == &kCellularWithStateSignature) {
TranslateCellularWithState();
} else {
CopyPropertiesAccordingToSignature();
}
return onc_object_.Pass();
}
void ShillToONCTranslator::TranslateEthernet() {
std::string shill_network_type;
shill_dictionary_->GetStringWithoutPathExpansion(flimflam::kTypeProperty,
&shill_network_type);
const char* onc_auth = ethernet::kNone;
if (shill_network_type == shill::kTypeEthernetEap)
onc_auth = ethernet::k8021X;
onc_object_->SetStringWithoutPathExpansion(ethernet::kAuthentication,
onc_auth);
}
void ShillToONCTranslator::TranslateOpenVPN() {
// Shill supports only one RemoteCertKU but ONC requires a list. If existing,
// wraps the value into a list.
std::string certKU;
if (shill_dictionary_->GetStringWithoutPathExpansion(
flimflam::kOpenVPNRemoteCertKUProperty, &certKU)) {
scoped_ptr<base::ListValue> certKUs(new base::ListValue);
certKUs->AppendString(certKU);
onc_object_->SetWithoutPathExpansion(openvpn::kRemoteCertKU,
certKUs.release());
}
for (const OncFieldSignature* field_signature = onc_signature_->fields;
field_signature->onc_field_name != NULL; ++field_signature) {
const std::string& onc_field_name = field_signature->onc_field_name;
if (onc_field_name == vpn::kSaveCredentials ||
onc_field_name == openvpn::kRemoteCertKU ||
onc_field_name == openvpn::kServerCAPEMs) {
CopyProperty(field_signature);
continue;
}
std::string shill_property_name;
const base::Value* shill_value = NULL;
if (!field_translation_table_ ||
!GetShillPropertyName(field_signature->onc_field_name,
field_translation_table_,
&shill_property_name) ||
!shill_dictionary_->GetWithoutPathExpansion(shill_property_name,
&shill_value)) {
continue;
}
scoped_ptr<base::Value> translated;
std::string shill_str;
if (shill_value->GetAsString(&shill_str)) {
// Shill wants all Provider/VPN fields to be strings. Translates these
// strings back to the correct ONC type.
translated = ConvertStringToValue(
shill_str,
field_signature->value_signature->onc_type);
if (translated.get() == NULL) {
LOG(ERROR) << "Shill property '" << shill_property_name
<< "' with value " << *shill_value
<< " couldn't be converted to base::Value::Type "
<< field_signature->value_signature->onc_type;
} else {
onc_object_->SetWithoutPathExpansion(onc_field_name,
translated.release());
}
} else {
LOG(ERROR) << "Shill property '" << shill_property_name
<< "' has value " << *shill_value
<< ", but expected a string";
}
}
}
void ShillToONCTranslator::TranslateVPN() {
TranslateWithTableAndSet(flimflam::kProviderTypeProperty, kVPNTypeTable,
vpn::kType);
CopyPropertiesAccordingToSignature();
std::string vpn_type;
if (onc_object_->GetStringWithoutPathExpansion(vpn::kType,
&vpn_type)) {
if (vpn_type == vpn::kTypeL2TP_IPsec) {
TranslateAndAddNestedObject(vpn::kIPsec);
TranslateAndAddNestedObject(vpn::kL2TP);
} else {
TranslateAndAddNestedObject(vpn_type);
}
}
}
void ShillToONCTranslator::TranslateWiFiWithState() {
TranslateWithTableAndSet(flimflam::kSecurityProperty, kWiFiSecurityTable,
wifi::kSecurity);
CopyPropertiesAccordingToSignature();
}
void ShillToONCTranslator::TranslateCellularWithState() {
CopyPropertiesAccordingToSignature();
const base::DictionaryValue* dictionary = NULL;
if (shill_dictionary_->GetDictionaryWithoutPathExpansion(
flimflam::kServingOperatorProperty, &dictionary)) {
TranslateAndAddNestedObject(cellular::kServingOperator, *dictionary);
}
if (shill_dictionary_->GetDictionaryWithoutPathExpansion(
flimflam::kCellularApnProperty, &dictionary)) {
TranslateAndAddNestedObject(cellular::kAPN, *dictionary);
}
}
void ShillToONCTranslator::TranslateNetworkWithState() {
CopyPropertiesAccordingToSignature();
std::string shill_network_type;
shill_dictionary_->GetStringWithoutPathExpansion(flimflam::kTypeProperty,
&shill_network_type);
std::string onc_network_type = network_type::kEthernet;
if (shill_network_type != flimflam::kTypeEthernet &&
shill_network_type != shill::kTypeEthernetEap) {
TranslateStringToONC(
kNetworkTypeTable, shill_network_type, &onc_network_type);
}
if (!onc_network_type.empty()) {
onc_object_->SetStringWithoutPathExpansion(network_config::kType,
onc_network_type);
TranslateAndAddNestedObject(onc_network_type);
}
// Since Name is a read only field in Shill unless it's a VPN, it is copied
// here, but not when going the other direction (if it's not a VPN).
std::string name;
shill_dictionary_->GetStringWithoutPathExpansion(flimflam::kNameProperty,
&name);
onc_object_->SetStringWithoutPathExpansion(network_config::kName, name);
std::string state;
if (shill_dictionary_->GetStringWithoutPathExpansion(flimflam::kStateProperty,
&state)) {
std::string onc_state = connection_state::kNotConnected;
if (NetworkState::StateIsConnected(state)) {
onc_state = connection_state::kConnected;
} else if (NetworkState::StateIsConnecting(state)) {
onc_state = connection_state::kConnecting;
}
onc_object_->SetStringWithoutPathExpansion(network_config::kConnectionState,
onc_state);
}
}
void ShillToONCTranslator::TranslateAndAddNestedObject(
const std::string& onc_field_name) {
TranslateAndAddNestedObject(onc_field_name, *shill_dictionary_);
}
void ShillToONCTranslator::TranslateAndAddNestedObject(
const std::string& onc_field_name,
const base::DictionaryValue& dictionary) {
const OncFieldSignature* field_signature =
GetFieldSignature(*onc_signature_, onc_field_name);
ShillToONCTranslator nested_translator(dictionary,
*field_signature->value_signature);
scoped_ptr<base::DictionaryValue> nested_object =
nested_translator.CreateTranslatedONCObject();
if (nested_object->empty())
return;
onc_object_->SetWithoutPathExpansion(onc_field_name, nested_object.release());
}
void ShillToONCTranslator::CopyPropertiesAccordingToSignature() {
CopyPropertiesAccordingToSignature(onc_signature_);
}
void ShillToONCTranslator::CopyPropertiesAccordingToSignature(
const OncValueSignature* value_signature) {
if (value_signature->base_signature)
CopyPropertiesAccordingToSignature(value_signature->base_signature);
for (const OncFieldSignature* field_signature = value_signature->fields;
field_signature->onc_field_name != NULL; ++field_signature) {
CopyProperty(field_signature);
}
}
void ShillToONCTranslator::CopyProperty(
const OncFieldSignature* field_signature) {
std::string shill_property_name;
const base::Value* shill_value = NULL;
if (!field_translation_table_ ||
!GetShillPropertyName(field_signature->onc_field_name,
field_translation_table_,
&shill_property_name) ||
!shill_dictionary_->GetWithoutPathExpansion(shill_property_name,
&shill_value)) {
return;
}
if (shill_value->GetType() != field_signature->value_signature->onc_type) {
LOG(ERROR) << "Shill property '" << shill_property_name
<< "' with value " << *shill_value
<< " has base::Value::Type " << shill_value->GetType()
<< " but ONC field '" << field_signature->onc_field_name
<< "' requires type "
<< field_signature->value_signature->onc_type << ".";
return;
}
onc_object_->SetWithoutPathExpansion(field_signature->onc_field_name,
shill_value->DeepCopy());
}
void ShillToONCTranslator::TranslateWithTableAndSet(
const std::string& shill_property_name,
const StringTranslationEntry table[],
const std::string& onc_field_name) {
std::string shill_value;
if (!shill_dictionary_->GetStringWithoutPathExpansion(shill_property_name,
&shill_value)) {
return;
}
std::string onc_value;
if (TranslateStringToONC(table, shill_value, &onc_value)) {
onc_object_->SetStringWithoutPathExpansion(onc_field_name, onc_value);
return;
}
LOG(ERROR) << "Shill property '" << shill_property_name << "' with value "
<< shill_value << " couldn't be translated to ONC";
}
} // namespace
scoped_ptr<base::DictionaryValue> TranslateShillServiceToONCPart(
const base::DictionaryValue& shill_dictionary,
const OncValueSignature* onc_signature) {
CHECK(onc_signature != NULL);
ShillToONCTranslator translator(shill_dictionary, *onc_signature);
return translator.CreateTranslatedONCObject();
}
} // namespace onc
} // namespace chromeos
| mogoweb/chromium-crosswalk | chromeos/network/onc/onc_translator_shill_to_onc.cc | C++ | bsd-3-clause | 14,135 |
package com.cjm721.overloaded.block.basic.hyperTransfer;
import com.cjm721.overloaded.block.basic.hyperTransfer.base.AbstractBlockHyperReceiver;
import com.cjm721.overloaded.tile.hyperTransfer.TileHyperEnergyReceiver;
import com.cjm721.overloaded.client.render.dynamic.ImageUtil;
import com.cjm721.overloaded.config.OverloadedConfig;
import net.minecraft.block.BlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockReader;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nonnull;
import static com.cjm721.overloaded.Overloaded.MODID;
public class BlockHyperEnergyReceiver extends AbstractBlockHyperReceiver {
public BlockHyperEnergyReceiver() {
super(getDefaultProperties());
setRegistryName("hyper_energy_receiver");
}
@Override
@Nonnull
protected String getType() {
return "Energy";
}
@Override
@Nonnull
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new TileHyperEnergyReceiver();
}
@Override
@OnlyIn(Dist.CLIENT)
public void registerModel() {
super.registerModel();
ImageUtil.registerDynamicTexture(
new ResourceLocation(MODID, "textures/block/hyper_energy_receiver.png"),
OverloadedConfig.INSTANCE.textureResolutions.blockResolution);
}
}
| CJ-MC-Mods/Overloaded | src/main/java/com/cjm721/overloaded/block/basic/hyperTransfer/BlockHyperEnergyReceiver.java | Java | bsd-3-clause | 1,407 |
from pypom import Region
from selenium.webdriver.common.by import By
from base import Base
class Collections(Base):
"""Collections page."""
_item_locator = (By.CSS_SELECTOR, '.item')
def wait_for_page_to_load(self):
self.wait.until(lambda _: len(self.collections) > 0 and
self.collections[0].name)
return self
@property
def collections(self):
collections = self.find_elements(*self._item_locator)
return [self.Collection(self, el) for el in collections]
class Collection(Region):
"""Represents an individual collection."""
_name_locator = (By.CSS_SELECTOR, '.info > h3')
@property
def name(self):
return self.find_element(*self._name_locator).text
| harikishen/addons-server | tests/ui/pages/desktop/collections.py | Python | bsd-3-clause | 779 |
<?php defined('SYSPATH') or die('No direct script access.'); ?>
2015-05-12 11:03:11 --- ERROR: Kohana_Exception [ 0 ]: The reprog_eval_beneficiarios property does not exist in the Model_Proyectosexcel class ~ MODPATH/orm/classes/kohana/orm.php [ 746 ] | sysdevbol/entidad | application/logs/2015/05/12.php | PHP | bsd-3-clause | 252 |
/*================================================================================
Copyright (c) 2012 Steve Jin. 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 VMware, Inc. 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 VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class ConfigTarget extends DynamicData {
public int numCpus;
public int numCpuCores;
public int numNumaNodes;
public Boolean smcPresent;
public VirtualMachineDatastoreInfo[] datastore;
public VirtualMachineNetworkInfo[] network;
public DistributedVirtualPortgroupInfo[] distributedVirtualPortgroup;
public DistributedVirtualSwitchInfo[] distributedVirtualSwitch;
public VirtualMachineCdromInfo[] cdRom;
public VirtualMachineSerialInfo[] serial;
public VirtualMachineParallelInfo[] parallel;
public VirtualMachineSoundInfo[] sound;
public VirtualMachineUsbInfo[] usb;
public VirtualMachineFloppyInfo[] floppy;
public VirtualMachineLegacyNetworkSwitchInfo[] legacyNetworkInfo;
public VirtualMachineScsiPassthroughInfo[] scsiPassthrough;
public VirtualMachineScsiDiskDeviceInfo[] scsiDisk;
public VirtualMachineIdeDiskDeviceInfo[] ideDisk;
public int maxMemMBOptimalPerf;
public ResourcePoolRuntimeInfo resourcePool;
public Boolean autoVmotion;
public VirtualMachinePciPassthroughInfo[] pciPassthrough;
public int getNumCpus() {
return this.numCpus;
}
public int getNumCpuCores() {
return this.numCpuCores;
}
public int getNumNumaNodes() {
return this.numNumaNodes;
}
public Boolean getSmcPresent() {
return this.smcPresent;
}
public VirtualMachineDatastoreInfo[] getDatastore() {
return this.datastore;
}
public VirtualMachineNetworkInfo[] getNetwork() {
return this.network;
}
public DistributedVirtualPortgroupInfo[] getDistributedVirtualPortgroup() {
return this.distributedVirtualPortgroup;
}
public DistributedVirtualSwitchInfo[] getDistributedVirtualSwitch() {
return this.distributedVirtualSwitch;
}
public VirtualMachineCdromInfo[] getCdRom() {
return this.cdRom;
}
public VirtualMachineSerialInfo[] getSerial() {
return this.serial;
}
public VirtualMachineParallelInfo[] getParallel() {
return this.parallel;
}
public VirtualMachineSoundInfo[] getSound() {
return this.sound;
}
public VirtualMachineUsbInfo[] getUsb() {
return this.usb;
}
public VirtualMachineFloppyInfo[] getFloppy() {
return this.floppy;
}
public VirtualMachineLegacyNetworkSwitchInfo[] getLegacyNetworkInfo() {
return this.legacyNetworkInfo;
}
public VirtualMachineScsiPassthroughInfo[] getScsiPassthrough() {
return this.scsiPassthrough;
}
public VirtualMachineScsiDiskDeviceInfo[] getScsiDisk() {
return this.scsiDisk;
}
public VirtualMachineIdeDiskDeviceInfo[] getIdeDisk() {
return this.ideDisk;
}
public int getMaxMemMBOptimalPerf() {
return this.maxMemMBOptimalPerf;
}
public ResourcePoolRuntimeInfo getResourcePool() {
return this.resourcePool;
}
public Boolean getAutoVmotion() {
return this.autoVmotion;
}
public VirtualMachinePciPassthroughInfo[] getPciPassthrough() {
return this.pciPassthrough;
}
public void setNumCpus(int numCpus) {
this.numCpus=numCpus;
}
public void setNumCpuCores(int numCpuCores) {
this.numCpuCores=numCpuCores;
}
public void setNumNumaNodes(int numNumaNodes) {
this.numNumaNodes=numNumaNodes;
}
public void setSmcPresent(Boolean smcPresent) {
this.smcPresent=smcPresent;
}
public void setDatastore(VirtualMachineDatastoreInfo[] datastore) {
this.datastore=datastore;
}
public void setNetwork(VirtualMachineNetworkInfo[] network) {
this.network=network;
}
public void setDistributedVirtualPortgroup(DistributedVirtualPortgroupInfo[] distributedVirtualPortgroup) {
this.distributedVirtualPortgroup=distributedVirtualPortgroup;
}
public void setDistributedVirtualSwitch(DistributedVirtualSwitchInfo[] distributedVirtualSwitch) {
this.distributedVirtualSwitch=distributedVirtualSwitch;
}
public void setCdRom(VirtualMachineCdromInfo[] cdRom) {
this.cdRom=cdRom;
}
public void setSerial(VirtualMachineSerialInfo[] serial) {
this.serial=serial;
}
public void setParallel(VirtualMachineParallelInfo[] parallel) {
this.parallel=parallel;
}
public void setSound(VirtualMachineSoundInfo[] sound) {
this.sound=sound;
}
public void setUsb(VirtualMachineUsbInfo[] usb) {
this.usb=usb;
}
public void setFloppy(VirtualMachineFloppyInfo[] floppy) {
this.floppy=floppy;
}
public void setLegacyNetworkInfo(VirtualMachineLegacyNetworkSwitchInfo[] legacyNetworkInfo) {
this.legacyNetworkInfo=legacyNetworkInfo;
}
public void setScsiPassthrough(VirtualMachineScsiPassthroughInfo[] scsiPassthrough) {
this.scsiPassthrough=scsiPassthrough;
}
public void setScsiDisk(VirtualMachineScsiDiskDeviceInfo[] scsiDisk) {
this.scsiDisk=scsiDisk;
}
public void setIdeDisk(VirtualMachineIdeDiskDeviceInfo[] ideDisk) {
this.ideDisk=ideDisk;
}
public void setMaxMemMBOptimalPerf(int maxMemMBOptimalPerf) {
this.maxMemMBOptimalPerf=maxMemMBOptimalPerf;
}
public void setResourcePool(ResourcePoolRuntimeInfo resourcePool) {
this.resourcePool=resourcePool;
}
public void setAutoVmotion(Boolean autoVmotion) {
this.autoVmotion=autoVmotion;
}
public void setPciPassthrough(VirtualMachinePciPassthroughInfo[] pciPassthrough) {
this.pciPassthrough=pciPassthrough;
}
} | xebialabs/vijava | src/com/vmware/vim25/ConfigTarget.java | Java | bsd-3-clause | 7,050 |
#include <ruby.h>
VALUE sm_define_const(VALUE self, VALUE klass, VALUE val) {
rb_define_const(klass, "FOO", val);
return Qnil;
}
VALUE sm_const_defined(VALUE self, VALUE klass, VALUE id) {
return (VALUE)rb_const_defined(klass, SYM2ID(id));
}
void Init_subtend_module() {
VALUE cls;
cls = rb_define_class("SubtendModule", rb_cObject);
rb_define_method(cls, "rb_define_const", sm_define_const, 2);
rb_define_method(cls, "rb_const_defined", sm_const_defined, 2);
}
| chad/rubinius | spec/subtend/ext/subtend_module.c | C | bsd-3-clause | 481 |
<patTemplate:tmpl name="menu">
<div id="topmenu">
<div id="menutitle">
<img src="images/icons/gnome/stock/generic/stock_people.png">Clients
</div>
<ul>
<li><form action="?page=clients&action=new" method="POST">New:
<input type="submit" name="Submit" value="invoice">
<input type="submit" name="Submit" value="project">
<input type="submit" name="Submit" value="quote">
<input type="submit" name="Submit" value="timesheet"></form></li>
<li><a href="?page=clients&action=list_clients"><img src="images/icons/gnome/stock/form/stock_insert-form.png">List ({CLIENTS}) Clients</a></li>
<li><a href="?page=clients&action=new_client"><img src="images/icons/gnome/stock/document/stock_new.png">Create New Client</a></li>
</ul>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="no_clients">
<div class="centered">
<fieldset>
<legend>You have no clients!</legend>
Please create a client to begin:<br>
<a href="?page=clients&action=new_client"><img src="images/icons/gnome/stock/document/stock_new.png">Create New Client</a>
</fieldset>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="list_clients">
<div class="centered">
<table class="results">
<tr>
<td colspan="9" class="heading2">
<img src="images/icons/gnome/stock/generic/stock_people.png"> {CLIENTS} Clients
</td>
</tr>
<tr>
<th class="cella"><a href="?page=clients&action=list_clients&order=Company_Name&order_direction={COMPANY_NAME}" title="Sort by name {COMPANY_NAME}">Company Name</a></th>
<th class="cellb">Invoices</th>
<th class="cella">Unpaid</th>
<th class="cellb">Quotes</th>
<th class="cella">Projects</th>
<th class="cellb"><a href="?page=clients&action=list_clients&order=Timesheets&order_direction={TIMESHEETS}" title="Sort by timesheets {TIMESHEETS}">Timesheets</a></th>
<th class="cella">Statement</th>
<th class="cellb">View</th>
<th class="cella">Delete</th>
</tr>
<patTemplate:link src="results" />
<tr>
<td colspan="2"></td>
<th class="cella">_HTML_CURENCY_SYMBOL_{GRAND_TOTAL_UNPAID}</td>
</table>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="results">
<tr>
<td class="cell{I}a"><a title="view client" href="?page=clients&action=view_client&Client_ID={ID}">{COMPANY_NAME}</a></td>
<td class="cell{I}b"><a title="view invoices" href="?page=clients&action=view_invoices&Client_ID={ID}">{INVOICES}</a></td>
<td class="cell{I}a">
_HTML_CURENCY_SYMBOL_{TOTAL_UNPAID}
<patTemplate:link src="unpaid_invoices" />
</td>
<td class="cell{I}b"><a title="view quotes" href="?page=clients&action=view_quotes&Client_ID={ID}">{QUOTES}</a></td>
<td class="cell{I}a"><a title="view projects" href="?page=clients&action=view_projects&Client_ID={ID}">{PROJECTS}</a></td>
<td class="cell{I}b"><a title="view timesheets" href="?page=clients&action=timesheet_summary&Client_ID={ID}">{TIMESHEETS}</a></td>
<td class="cell{I}a"><a title="view statement" href="?page=clients&action=view_statement&Client_ID={ID}"><img src="images/icons/16x16/spreadsheet.png"></a></td>
<td class="cell{I}b"><a title="view client" href="?page=clients&action=view_client&Client_ID={ID}"><img src="images/icons/16x16/viewmag.png"></a></td>
<td class="cell{I}a"><a title="delete client" href="?page=clients&action=delete_client&Client_ID={ID}"><img src="images/icons/gnome_small/stock/generic/stock_stop.png"></a></td>
</tr>
</patTemplate:tmpl>
<patTemplate:tmpl name="unpaid_invoices">
<a href="?page=clients&action=edit_invoice&Invoice_ID={ID}" class="red" title="{DATE} value: _HTML_CURENCY_SYMBOL_{VALUE} paid: _HTML_CURENCY_SYMBOL_{PAID} balance: _HTML_CURENCY_SYMBOL_{BALANCE} ">{REFERENCE}</a>
</patTemplate:tmpl>
<patTemplate:tmpl name="view_client">
<div class="centered">
<h3><a href="?page=clients&action=list_clients">Back to client list <img src="images/icons/32x32/undo.png" class="inlineicon"></a></h3>
{FORM}
<fieldset>
<legend>Actions</legend>
<table>
</tr>
<tr>
<td>
<ul class="menu">
<li><a href="?page=clients&action=view_statement&Client_ID={CLIENT_ID}"><img src="images/icons/gnome/stock/text/stock_insert-footer.png">Statement</a></li>
<li><a href="?page=clients&action=timesheet_summary&Client_ID={CLIENT_ID}"><img src="images/icons/gnome/stock/generic/stock_new-appointment.png"> {TIMESHEETS} Timesheets</a></li>
<li> <a href="?page=clients&action=view_invoices&Client_ID={CLIENT_ID}"><img src="images/icons/gnome/stock/chart/stock_chart-toggle-legend.png"> {INVOICES} Invoices</a> </li>
<li> <a href="?page=clients&action=view_quotes&Client_ID={CLIENT_ID}"><img src="images/icons/gnome/stock/document/stock_task.png"> {QUOTES} Quotes</a> </li>
<li> <a href="?page=clients&action=view_projects&Client_ID={CLIENT_ID}"><img src="images/icons/gnome/stock/generic/stock_dialog-info.png"> {PROJECTS} Projects</a> </li>
<li> <a href="?page=clients&action=invoice_wizard&Client_ID={CLIENT_ID}"><img src="images/icons/16x16/pdf.png">Invoice Wizard</a> </li>
</ul>
</td>
</tr>
</table>
</fieldset>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="view_statement">
<div class="centered">
<p>
<table class="results">
<tr>
<td colspan="9" class="heading">
<a href="?page=clients&action=view_statement&Client_ID={CLIENT_ID}&Start_Timestamp={LAST_START_TIMESTAMP}" title="back"><img src="images/icons/arrow-left.gif"></a>
Statement {YEAR} <a href="?page=clients&action=view_client&Client_ID={CLIENT_ID}"><span class="client">{CLIENT}</span></a> <a href="?page=clients&action=view_statement&pdf=true&Client_ID={CLIENT_ID}&Start_Timestamp={START_TIMESTAMP}"><img src="images/icons/16x16/pdf.png" title="Print PDF Statement"></a>
<a href="?page=clients&action=view_statement&Client_ID={CLIENT_ID}&Start_Timestamp={NEXT_START_TIMESTAMP}" title="back"><img src="images/icons/arrow-right.gif"></a>
</td>
</tr>
<tr>
<th class="cella">Date</th>
<th class="cellb">Invoice Ref</th>
<th class="cella">Invoice Value</th>
<th class="cellb">Payment Value</th>
<th class="cella">Balance</th>
</tr>
<patTemplate:link src="statement_results" />
<tr>
<td></td>
<td></td>
<td></td>
<th>Final Balance</th>
<th class="cella"><span class="{CLASS}">{BALANCE}</span></th>
</tr>
</table>
</p>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="statement_results">
<tr>
<td class="cell{I}a">{DATE}</td>
<td class="cell{I}b"><a title="view invoice" href="?page=clients&action=edit_invoice&Invoice_ID={INVOICE_ID}">{REFERENCE}</a></td>
<td class="cell{I}a"><a title="view invoice" href="?page=clients&action=edit_invoice&Invoice_ID={INVOICE_ID}">{INVOICE}</td>
<td class="cell{I}b">{PAYMENT}</span></td>
<td class="cell{I}a"><b class="{CLASS}">_HTML_CURENCY_SYMBOL_{BALANCE}</b></td>
</tr>
</patTemplate:tmpl>
<patTemplate:tmpl name="edit_invoice">
<div class="centered">
<form action="?page=clients&action=submit_invoice&Client_ID={CLIENT_ID}&Invoice_ID={INVOICE_ID}" method="POST">
<p>
<table class="edit">
<tr>
<td colspan="4" class="heading2">
<img src="images/icons/gnome/stock/chart/stock_chart-toggle-legend.png" class="middle">
Invoice for <a href="?page=clients&action=view_client&Client_ID={CLIENT_ID}"><span class="client">{CLIENT}</span></a>
</td>
</tr>
<tr>
<th>Client</th>
<td>{CLIENT_SELECT}</td>
<th>Date</td>
<td>{DATE_SELECT}</td>
</tr>
<tr>
<th>Payments</th>
<td>{PAYMENTS}
<b>Total Value</b>
_HTML_CURENCY_SYMBOL_{PAYMENTS_VALUE}</td>
<th>Reference:</th>
<td><input type="text" name="Reference" value="{REFERENCE}" size="8">
</tr>
<tr>
<th>Value</th>
<td>_HTML_CURENCY_SYMBOL_<input type="text" name="Value" value="{VALUE}" size="8"></td>
<th>Invoice Address</td>
<td><textarea name="Invoice_Address" rows="4" cols="40">{INVOICE_ADDRESS}</textarea></td>
</tr>
<tr>
<th>Description</td>
<td colspan="3"><textarea name="Description" rows="5" cols="80">{DESCRIPTION}</textarea></td>
</tr>
<tr>
<th>Send Reminders</th>
<td><input type="checkbox" name="Reminders" value="yes" {REMINDER}></td>
<th>Invoicing</th>
<th>[ <a title="Mail pdf invoice" href="?page=clients&action=print_invoice&Invoice_ID={INVOICE_ID}&Client_ID={CLIENT_ID}&mail=true">Mail</a> ] [ <a title="print pdf invoice" href="?page=clients&action=print_invoice&Invoice_ID={INVOICE_ID}&Client_ID={CLIENT_ID}" target="_blank"><img
src="images/icons/16x16/pdf.png" >Print</a> ]
[ <a title="print pdf invoice reminder" href="?page=clients&action=print_invoice_reminder&Invoice_ID={INVOICE_ID}&Client_ID={CLIENT_ID}" target="_blank"><img
src="images/icons/16x16/pdf.png" target="_blank">Print Reminder</a> ]
</tr>
<tr>
<th>Sent Reminders</th>
<td>
<patTemplate:link src="sent_reminders" />
<th colspan="2">
<input type="submit" name="Submit" value="Submit">
<patTemplate:link src="make_repeat_invoice_button" />
<patTemplate:link src="repeat_invoice_link" />
<input type="submit" name="Submit" value="Delete" class="delete"> </th>
</tr>
</table>
</p>
</form>
<p>
<form action="?page=clients&action=new_payment&Invoice_ID={INVOICE_ID}" method="POST">
<table class="results">
<tr>
<td colspan="5" class="heading2">Payments</td>
</tr>
<tr>
<th class="cella">Date</th>
<th class="cellb">Value</th>
<th class="cella">Mehtod</th>
<th class="cellb">Receipt</th>
<th class="cella">Delete</th>
</tr>
<patTemplate:link src="payment_results" />
<tr>
<th class="cella">{PAYMENT_DATE_SELECT}</th>
<th class="cellb"><input type="text" name="Value" value="{BALANCE}" size="8"></th>
<th class="cella">{PAYMENT_METHOD_SELECT}</th>
<th class="cellb" colspan="2"><input type="submit" value="Make New Payment"></th>
</tr>
</table>
</form>
</p>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="sent_reminders" visibility="hidden">
<a target="_blank" href="?page=clients&action=show_mail&Mail_ID={MAIL_ID}">{TYPE}</a>
</patTemplate:tmpl>
<patTemplate:tmpl name="make_repeat_invoice_button" visibility="hidden">
<input type="submit" name="Submit" value="Make Repeat Invoice">
</patTemplate:tmpl>
<patTemplate:tmpl name="repeat_invoice_link" visibility="hidden">
<a href="?page=clients&action=edit_repeat_invoice&Invoice_ID={INVOICE_ID}">view Repeat Invoice</a>
</patTemplate:tmpl>
<patTemplate:tmpl name="payment_results" visibility="hidden">
<tr>
<td class="cell{I}a">{DATE}</td>
<td class="cell{I}b">_HTML_CURENCY_SYMBOL_{VALUE}</td>
<td class="cell{I}a">{PAYMENT_METHOD}</td>
<td class="cell{I}b">[ <a title="print pdf receipt" href="?page=clients&action=print_receipt&Invoice_Payment_ID={ID}&Invoice_ID={INVOICE_ID}" target="_blank">receipt</a> ]</td>
<td class="cell{I}a"><a title="delete payment" href="?page=clients&action=delete_payment&Invoice_Payment_ID={ID}&Invoice_ID={INVOICE_ID}"><img
src="images/icons/gnome_small/stock/generic/stock_stop.png"></a></td>
</tr>
</patTemplate:tmpl>
<patTemplate:tmpl name="edit_repeat_invoice">
<div class="centered">
<form action="?page=clients&action=submit_repeat_invoice&Client_ID={CLIENT_ID}&Invoice_ID={INVOICE_ID}" method="POST">
<p>
<table class="edit">
<tr>
<td colspan="4" class="heading2">
<img src="images/icons/gnome/stock/chart/stock_chart-toggle-legend.png" class="middle">
Repeat Invoice for <a href="?page=clients&action=view_client&Client_ID={CLIENT_ID}"><span class="client">{COMPANY_NAME}</span></a>
</td>
</tr>
<tr>
<th>Original Invoice</th>
<td><a href="?page=clients&action=edit_invoice&Invoice_ID={INVOICE_ID}">{INVOICE_ID}</a></td>
<th>Start Date</td>
<td>{DATE}</td>
</tr>
<tr>
<th>Value</th>
<td>_HTML_CURENCY_SYMBOL_{VALUE}</td>
<th>Repeat</td>
<td>
On
<select name="Day">
<patTemplate:link src="day_results" />
</select>
of
<select name="Month">
<patTemplate:link src="month_results" />
</select>
</td>
</tr>
<tr>
<th>Send Reminders</th>
<td><input type="checkbox" name="Reminders" value="yes" {REMINDERS}></td>
<th colspan="2">
<select name="Active">
<option value="yes" {ACTIVE}>Active</option>
<option value="no" {INACTIVE}>Inactive</option>
</select>
<input type="submit" name="Submit" value="Submit">
<input type="submit" name="Submit" value="Delete" class="delete"></th>
</tr>
</table>
</p>
</form>
<p>
<table class="results">
<tr>
<td colspan="6" class="heading2">Invoices</td>
</tr>
<tr>
<th class="cella">Ref</th>
<th class="cellb">Date</th>
<th class="cella">Value</th>
<th class="cellb">Due</th>
<th class="cella">Payments</th>
<th class="cellb">Delete</th>
</tr>
<patTemplate:link src="repeat_invoice_results" />
</tr>
<tr>
<th class="cella"><a href="?page=clients&action=create_repeat_invoice&Invoice_ID={INVOICE_ID}"><img src="images/icons/gnome/stock/chart/stock_chart-toggle-legend.png" alt="invoice" /></a></th>
<th class="cellb" colspan="5"><a href="?page=clients&action=create_repeat_invoice&Invoice_ID={INVOICE_ID}">Manualy Add An Invoice</a></th>
</tr>
</table>
</p>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="day_results">
<option value="{I}" {SELECTED}>{DAY}</option>
</patTemplate:tmpl>
<patTemplate:tmpl name="month_results">
<option value="{I}" {SELECTED}>{MONTH}</option>
</patTemplate:tmpl>
<patTemplate:tmpl name="repeat_invoice_results" visibility="hidden">
<tr>
<td class="cell{I}a"><a href="?page=clients&action=edit_invoice&Invoice_ID={INVOICE_ID}">{REFERENCE}</a></td>
<td class="cell{I}b">{DATE}</td>
<td class="cell{I}a">_HTML_CURENCY_SYMBOL_{VALUE}</td>
<td class="cell{I}b"><span class="red">{DUE}</a></td>
<td class="cell{I}a"><span class="red">{PAYMENTS}</a></td>
<td class="cell{I}b"><a title="delete payment" href="?page=clients&action=delete_invoice&Invoice_ID={INVOICE_ID}&Client_ID={CLIENT_ID}"><img
src="images/icons/gnome_small/stock/generic/stock_stop.png"></a></td>
</tr>
</patTemplate:tmpl>
<patTemplate:tmpl name="cant_delete_invoice">
<h3 class="warning"><img src="images/icons/gnome/stock/generic/stock_stop.png"> Payments made already, <a href="?{ACTION}&Confirm=true&Double_Confirm=true" title="click here to confirm delete">CONFIRM DELETE</a></h3>
</patTemplate:tmpl>
<patTemplate:tmpl name="cant_delete_repeat_invoice">
<h3 class="warning"><img src="images/icons/gnome/stock/generic/stock_stop.png"> This is a repeat invoice, deleting this will stop any further repeats aswell, <a href="?{ACTION}&Confirm=true&Double_Confirm=true" title="click here to confirm delete">CONFIRM DELETE</a></h3>
</patTemplate:tmpl>
<patTemplate:tmpl name="invoice_sent">
<h2>Invoice Sent</h2>
</patTemplate:tmpl>
<patTemplate:tmpl name="edit_quote">
<div class="centered">
<form action="?page=clients&action=submit_quote&Client_ID={CLIENT_ID}&Quote_ID={ID}" method="POST">
<p>
<table class="edit">
<tr>
<td colspan="4" class="heading2">
<img src="images/icons/gnome/stock/document/stock_task.png" class="middle">
Quote for <a href="?page=clients&action=view_client&Client_ID={CLIENT_ID}"><span class="client">{CLIENT}</span></a>
</td>
</tr>
<tr>
<th>Client</th>
<td>{CLIENT_SELECT}</td>
<th>Date</td>
<td>{DATE_SELECT}</td>
</tr>
<tr>
<th>Title</th>
<td colspan="3"><input type="text" name="Title" value="{TITLE}"</td>
</tr>
<tr>
<th>Description</td>
<td colspan="3"><textarea name="Description" rows="9" cols="80">{DESCRIPTION}</textarea></td>
</tr>
<tr>
<th>Value</th>
<td>_HTML_CURENCY_SYMBOL_<input type="text" name="Value" value="{VALUE}" size="8"></td>
<th>Quote Address</td>
<td><textarea name="Quote_Address" rows="4" cols="40">{QUOTE_ADDRESS}</textarea></td>
</tr>
<tr>
<th>Approved By</th>
<td><input type="text" name="Approved_Name" value="{APPROVED_NAME}"></td>
<th>Date Approved</td>
<td>{APPROVED_DATE_SELECT}</td>
</tr>
<tr>
<tr>
<th colspan="4">[ <a title="print pdf quote" href="?page=clients&action=print_quote&Quote_ID={ID}&Client_ID={CLIENT_ID}"><img
src="images/icons/16x16/pdf.png" target="_blank" target="_blank">Print</a> ]
<input type="submit" name="Submit" value="Submit"> <input type="submit" name="Submit" value="Delete" class="delete"></th>
</tr>
</table>
</p>
</form>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="edit_project">
<div class="centered">
<form action="?page=clients&action=submit_project&Client_ID={CLIENT_ID}&Project_ID={ID}" method="POST">
<p>
<table class="edit">
<tr>
<td colspan="4" class="heading2">
<img src="images/icons/gnome/stock/generic/stock_dialog-info.png" class="middle">
Project for <a href="?page=clients&action=view_client&Client_ID={CLIENT_ID}"><span class="client">{CLIENT}</span></a>
</td>
</tr>
<tr>
<th>Client</th>
<td>{CLIENT_SELECT}</td>
<th>Date Opened</td>
<td>{DATE_OPENED_SELECT}</td>
</tr>
<tr>
<th>Title</th>
<td colspan="3"><input type="text" name="Title" value="{TITLE}"</td>
</tr>
<tr>
<th>Description</td>
<td colspan="3"><textarea name="Description" row="4" cols="60">{DESCRIPTION}</textarea></td>
</tr>
<tr>
<th>Closed</th>
<td><input type="checkbox" name="Closed" value="closed" {CLOSED}></td>
<th>Date Closed</td>
<td>{DATE_CLOSED_SELECT}</td>
</tr>
<tr>
<tr>
<td><a href="?page=clients&action=view_timesheet&Client_ID={CLIENT_ID}&Project_ID={ID}">view timesheets</a></td>
<th colspan="3">[ <a title="print pdf project" href="?page=clients&action=print_project&Project_ID={ID}&Client_ID={CLIENT_ID}"><img
src="images/icons/16x16/pdf.png" target="_blank" target="_blank">Print</a> ]
<input type="submit" name="Submit" value="Submit"> <input type="submit" name="Submit" value="Delete" class="delete"></th>
</tr>
</table>
</p>
</form>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="choose_client">
<div class="centered">
<fieldset>
<legend>Choose Client</legend>
<form action="?page=clients&action={ACTION}" method="post">
{CLIENT_SELECT_LIST}
<input type="submit" value="Go">
</form>
</fieldset>
</div>
</patTemplate:tmpl>
<patTemplate:tmpl name="show_mail">
<div class="centered">
<table class="edit">
<tr>
<th>Date</th>
<td>{DATE}</td>
<th>To</th>
<td>{EMAIL}</td>
<th>Subject</th>
<td>{SUBJECT}</td>
</tr>
<tr>
<th>Message</th>
<td colspan="5">
<pre>{MESSAGE}</pre>
</td>
</tr>
</table>
</div>
</patTemplate:tmpl>
| UMD-SEAM/bugbox | framework/Targets/phpaccounts_0_5_3/application/templates/clients.tmpl.html | HTML | bsd-3-clause | 18,077 |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The coordinator runs on GCE and coordinates builds in Docker containers.
package main
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"sort"
"strings"
"sync"
"time"
)
var (
masterKeyFile = flag.String("masterkey", "", "Path to builder master key. Else fetched using GCE project attribute 'builder-master-key'.")
maxBuilds = flag.Int("maxbuilds", 6, "Max concurrent builds")
// Debug flags:
addTemp = flag.Bool("temp", false, "Append -temp to all builders.")
just = flag.String("just", "", "If non-empty, run single build in the foreground. Requires rev.")
rev = flag.String("rev", "", "Revision to build.")
)
var (
startTime = time.Now()
builders = map[string]buildConfig{} // populated once at startup
donec = make(chan builderRev) // reports of finished builders
statusMu sync.Mutex
status = map[builderRev]*buildStatus{}
)
type imageInfo struct {
url string // of tar file
mu sync.Mutex
lastMod string
}
var images = map[string]*imageInfo{
"gobuilders/linux-x86-base": {url: "https://storage.googleapis.com/go-builder-data/docker-linux.base.tar.gz"},
"gobuilders/linux-x86-gccgo": {url: "https://storage.googleapis.com/go-builder-data/docker-linux.gccgo.tar.gz"},
"gobuilders/linux-x86-nacl": {url: "https://storage.googleapis.com/go-builder-data/docker-linux.nacl.tar.gz"},
}
type buildConfig struct {
name string // "linux-amd64-race"
image string // Docker image to use to build
cmd string // optional -cmd flag (relative to go/src/)
cmdTimeout time.Duration // time to wait for optional cmd to finish
env []string // extra environment ("key=value") pairs
dashURL string // url of the build dashboard
tool string // the tool this configuration is for
}
func main() {
flag.Parse()
addBuilder(buildConfig{name: "linux-386"})
addBuilder(buildConfig{name: "linux-386-387", env: []string{"GO386=387"}})
addBuilder(buildConfig{name: "linux-amd64"})
addBuilder(buildConfig{name: "linux-amd64-nocgo", env: []string{"CGO_ENABLED=0", "USER=root"}})
addBuilder(buildConfig{name: "linux-amd64-race"})
addBuilder(buildConfig{name: "nacl-386"})
addBuilder(buildConfig{name: "nacl-amd64p32"})
addBuilder(buildConfig{
name: "linux-amd64-gccgo",
image: "gobuilders/linux-x86-gccgo",
cmd: "make check-go -kj",
cmdTimeout: 60 * time.Minute,
dashURL: "https://build.golang.org/gccgo",
tool: "gccgo",
})
if (*just != "") != (*rev != "") {
log.Fatalf("--just and --rev must be used together")
}
if *just != "" {
conf, ok := builders[*just]
if !ok {
log.Fatalf("unknown builder %q", *just)
}
cmd := exec.Command("docker", append([]string{"run"}, conf.dockerRunArgs(*rev)...)...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Build failed: %v", err)
}
return
}
http.HandleFunc("/", handleStatus)
http.HandleFunc("/logs", handleLogs)
go http.ListenAndServe(":80", nil)
workc := make(chan builderRev)
for name, builder := range builders {
go findWorkLoop(name, builder.dashURL, workc)
}
ticker := time.NewTicker(1 * time.Minute)
for {
select {
case work := <-workc:
log.Printf("workc received %+v; len(status) = %v, maxBuilds = %v; cur = %p", work, len(status), *maxBuilds, status[work])
mayBuild := mayBuildRev(work)
if mayBuild {
out, _ := exec.Command("docker", "ps").Output()
numBuilds := bytes.Count(out, []byte("\n")) - 1
log.Printf("num current docker builds: %d", numBuilds)
if numBuilds > *maxBuilds {
mayBuild = false
}
}
if mayBuild {
if st, err := startBuilding(builders[work.name], work.rev); err == nil {
setStatus(work, st)
log.Printf("%v now building in %v", work, st.container)
} else {
log.Printf("Error starting to build %v: %v", work, err)
}
}
case done := <-donec:
log.Printf("%v done", done)
setStatus(done, nil)
case <-ticker.C:
if numCurrentBuilds() == 0 && time.Now().After(startTime.Add(10*time.Minute)) {
// TODO: halt the whole machine to kill the VM or something
}
}
}
}
func numCurrentBuilds() int {
statusMu.Lock()
defer statusMu.Unlock()
return len(status)
}
func mayBuildRev(work builderRev) bool {
statusMu.Lock()
defer statusMu.Unlock()
return len(status) < *maxBuilds && status[work] == nil
}
func setStatus(work builderRev, st *buildStatus) {
statusMu.Lock()
defer statusMu.Unlock()
if st == nil {
delete(status, work)
} else {
status[work] = st
}
}
func getStatus(work builderRev) *buildStatus {
statusMu.Lock()
defer statusMu.Unlock()
return status[work]
}
type byAge []*buildStatus
func (s byAge) Len() int { return len(s) }
func (s byAge) Less(i, j int) bool { return s[i].start.Before(s[j].start) }
func (s byAge) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func handleStatus(w http.ResponseWriter, r *http.Request) {
var active []*buildStatus
statusMu.Lock()
for _, st := range status {
active = append(active, st)
}
statusMu.Unlock()
fmt.Fprintf(w, "<html><body><h1>Go build coordinator</h1>%d of max %d builds running:<p><pre>", len(status), *maxBuilds)
sort.Sort(byAge(active))
for _, st := range active {
fmt.Fprintf(w, "%-22s hg %s in container <a href='/logs?name=%s&rev=%s'>%s</a>, %v ago\n", st.name, st.rev, st.name, st.rev,
st.container, time.Now().Sub(st.start))
}
fmt.Fprintf(w, "</pre></body></html>")
}
func handleLogs(w http.ResponseWriter, r *http.Request) {
st := getStatus(builderRev{r.FormValue("name"), r.FormValue("rev")})
if st == nil {
fmt.Fprintf(w, "<html><body><h1>not building</h1>")
return
}
out, err := exec.Command("docker", "logs", st.container).CombinedOutput()
if err != nil {
log.Print(err)
http.Error(w, "Error fetching logs. Already finished?", 500)
return
}
key := builderKey(st.name)
logs := strings.Replace(string(out), key, "BUILDERKEY", -1)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
io.WriteString(w, logs)
}
func findWorkLoop(builderName, dashURL string, work chan<- builderRev) {
// TODO: make this better
for {
rev, err := findWork(builderName, dashURL)
if err != nil {
log.Printf("Finding work for %s: %v", builderName, err)
} else if rev != "" {
work <- builderRev{builderName, rev}
}
time.Sleep(60 * time.Second)
}
}
func findWork(builderName, dashURL string) (rev string, err error) {
var jres struct {
Response struct {
Kind string
Data struct {
Hash string
PerfResults []string
}
}
}
res, err := http.Get(dashURL + "/todo?builder=" + builderName + "&kind=build-go-commit")
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", fmt.Errorf("unexpected http status %d", res.StatusCode)
}
err = json.NewDecoder(res.Body).Decode(&jres)
if jres.Response.Kind == "build-go-commit" {
rev = jres.Response.Data.Hash
}
return rev, err
}
type builderRev struct {
name, rev string
}
// returns the part after "docker run"
func (conf buildConfig) dockerRunArgs(rev string) (args []string) {
if key := builderKey(conf.name); key != "" {
tmpKey := "/tmp/" + conf.name + ".buildkey"
if _, err := os.Stat(tmpKey); err != nil {
if err := ioutil.WriteFile(tmpKey, []byte(key), 0600); err != nil {
log.Fatal(err)
}
}
args = append(args, "-v", tmpKey+":/.gobuildkey")
}
for _, pair := range conf.env {
args = append(args, "-e", pair)
}
args = append(args,
conf.image,
"/usr/local/bin/builder",
"-rev="+rev,
"-dashboard="+conf.dashURL,
"-tool="+conf.tool,
"-buildroot=/"+conf.tool,
"-v",
)
if conf.cmd != "" {
args = append(args, "-cmd", conf.cmd)
args = append(args, "-cmdTimeout", conf.cmdTimeout.String())
}
args = append(args, conf.name)
return
}
func addBuilder(c buildConfig) {
if c.name == "" {
panic("empty name")
}
if *addTemp {
c.name += "-temp"
}
if _, dup := builders[c.name]; dup {
panic("dup name")
}
if c.cmdTimeout == 0 {
c.cmdTimeout = 10 * time.Minute
}
if c.dashURL == "" {
c.dashURL = "https://build.golang.org"
}
if c.tool == "" {
c.tool = "go"
}
if strings.HasPrefix(c.name, "nacl-") {
if c.image == "" {
c.image = "gobuilders/linux-x86-nacl"
}
if c.cmd == "" {
c.cmd = "/usr/local/bin/build-command.pl"
}
}
if strings.HasPrefix(c.name, "linux-") && c.image == "" {
c.image = "gobuilders/linux-x86-base"
}
if c.image == "" {
panic("empty image")
}
builders[c.name] = c
}
func condUpdateImage(img string) error {
ii := images[img]
if ii == nil {
log.Fatalf("Image %q not described.", img)
}
ii.mu.Lock()
defer ii.mu.Unlock()
res, err := http.Head(ii.url)
if err != nil {
return fmt.Errorf("Error checking %s: %v", ii.url, err)
}
if res.StatusCode != 200 {
return fmt.Errorf("Error checking %s: %v", ii.url, res.Status)
}
if res.Header.Get("Last-Modified") == ii.lastMod {
return nil
}
res, err = http.Get(ii.url)
if err != nil || res.StatusCode != 200 {
return fmt.Errorf("Get after Head failed for %s: %v, %v", ii.url, err, res)
}
defer res.Body.Close()
log.Printf("Running: docker load of %s\n", ii.url)
cmd := exec.Command("docker", "load")
cmd.Stdin = res.Body
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
if cmd.Run(); err != nil {
log.Printf("Failed to pull latest %s from %s and pipe into docker load: %v, %s", img, ii.url, err, out.Bytes())
return err
}
ii.lastMod = res.Header.Get("Last-Modified")
return nil
}
func startBuilding(conf buildConfig, rev string) (*buildStatus, error) {
if err := condUpdateImage(conf.image); err != nil {
log.Printf("Failed to setup container for %v %v: %v", conf.name, rev, err)
return nil, err
}
cmd := exec.Command("docker", append([]string{"run", "-d"}, conf.dockerRunArgs(rev)...)...)
all, err := cmd.CombinedOutput()
log.Printf("Docker run for %v %v = err:%v, output:%s", conf.name, rev, err, all)
if err != nil {
return nil, err
}
container := strings.TrimSpace(string(all))
go func() {
all, err := exec.Command("docker", "wait", container).CombinedOutput()
log.Printf("docker wait %s: %v, %s", container, err, strings.TrimSpace(string(all)))
donec <- builderRev{conf.name, rev}
exec.Command("docker", "rm", container).Run()
}()
return &buildStatus{
builderRev: builderRev{
name: conf.name,
rev: rev,
},
container: container,
start: time.Now(),
}, nil
}
type buildStatus struct {
builderRev
container string
start time.Time
mu sync.Mutex
// ...
}
func builderKey(builder string) string {
master := masterKey()
if len(master) == 0 {
return ""
}
h := hmac.New(md5.New, master)
io.WriteString(h, builder)
return fmt.Sprintf("%x", h.Sum(nil))
}
func masterKey() []byte {
keyOnce.Do(loadKey)
return masterKeyCache
}
var (
keyOnce sync.Once
masterKeyCache []byte
)
func loadKey() {
if *masterKeyFile != "" {
b, err := ioutil.ReadFile(*masterKeyFile)
if err != nil {
log.Fatal(err)
}
masterKeyCache = bytes.TrimSpace(b)
return
}
req, _ := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/project/attributes/builder-master-key", nil)
req.Header.Set("Metadata-Flavor", "Google")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal("No builder master key available")
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("No builder-master-key project attribute available.")
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
masterKeyCache = bytes.TrimSpace(slurp)
}
| athom/go.tools | dashboard/coordinator/main.go | GO | bsd-3-clause | 11,840 |
from __future__ import unicode_literals
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore import fields
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.edit_handlers import InlinePanel
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
class AboutPage(Page):
content = fields.RichTextField()
picture = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
)
content_panels = Page.content_panels + [
FieldPanel('content'),
ImageChooserPanel('picture'),
]
api_fields = ('content', 'picture',)
| abirafdirp/blog-wagtail | about/models.py | Python | bsd-3-clause | 785 |
//
// Copyright 2020 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// vulkan_icd.cpp : Helper for creating vulkan instances & selecting physical device.
#include "common/vulkan/vulkan_icd.h"
#include <functional>
#include <vector>
#include "common/bitset_utils.h"
#include "common/debug.h"
#include "common/system_utils.h"
namespace angle
{
namespace vk
{
namespace
{
// This function is unused on Android/Fuschia/GGP
#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA) && \
!defined(ANGLE_PLATFORM_GGP)
const std::string WrapICDEnvironment(const char *icdEnvironment)
{
# if defined(ANGLE_PLATFORM_APPLE)
// On MacOS the libraries are bundled into the application directory
std::string ret = angle::GetHelperExecutableDir() + icdEnvironment;
return ret;
# endif // defined(ANGLE_PLATFORM_APPLE)
return icdEnvironment;
}
constexpr char kLoaderLayersPathEnv[] = "VK_LAYER_PATH";
#endif
constexpr char kLoaderICDFilenamesEnv[] = "VK_ICD_FILENAMES";
constexpr char kANGLEPreferredDeviceEnv[] = "ANGLE_PREFERRED_DEVICE";
constexpr uint32_t kMockVendorID = 0xba5eba11;
constexpr uint32_t kMockDeviceID = 0xf005ba11;
constexpr char kMockDeviceName[] = "Vulkan Mock Device";
constexpr uint32_t kGoogleVendorID = 0x1AE0;
constexpr uint32_t kSwiftShaderDeviceID = 0xC0DE;
constexpr char kSwiftShaderDeviceName[] = "SwiftShader Device";
using ICDFilterFunc = std::function<bool(const VkPhysicalDeviceProperties &)>;
ICDFilterFunc GetFilterForICD(vk::ICD preferredICD)
{
switch (preferredICD)
{
case vk::ICD::Mock:
return [](const VkPhysicalDeviceProperties &deviceProperties) {
return ((deviceProperties.vendorID == kMockVendorID) &&
(deviceProperties.deviceID == kMockDeviceID) &&
(strcmp(deviceProperties.deviceName, kMockDeviceName) == 0));
};
case vk::ICD::SwiftShader:
return [](const VkPhysicalDeviceProperties &deviceProperties) {
return ((deviceProperties.vendorID == kGoogleVendorID) &&
(deviceProperties.deviceID == kSwiftShaderDeviceID) &&
(strncmp(deviceProperties.deviceName, kSwiftShaderDeviceName,
strlen(kSwiftShaderDeviceName)) == 0));
};
default:
const std::string anglePreferredDevice =
angle::GetEnvironmentVar(kANGLEPreferredDeviceEnv);
return [anglePreferredDevice](const VkPhysicalDeviceProperties &deviceProperties) {
return (anglePreferredDevice.empty() ||
anglePreferredDevice == deviceProperties.deviceName);
};
}
}
} // namespace
// If we're loading the validation layers, we could be running from any random directory.
// Change to the executable directory so we can find the layers, then change back to the
// previous directory to be safe we don't disrupt the application.
ScopedVkLoaderEnvironment::ScopedVkLoaderEnvironment(bool enableValidationLayers, vk::ICD icd)
: mEnableValidationLayers(enableValidationLayers),
mICD(icd),
mChangedCWD(false),
mChangedICDEnv(false)
{
// Changing CWD and setting environment variables makes no sense on Android,
// since this code is a part of Java application there.
// Android Vulkan loader doesn't need this either.
#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA) && \
!defined(ANGLE_PLATFORM_GGP)
if (icd == vk::ICD::Mock)
{
if (!setICDEnvironment(WrapICDEnvironment(ANGLE_VK_MOCK_ICD_JSON).c_str()))
{
ERR() << "Error setting environment for Mock/Null Driver.";
}
}
# if defined(ANGLE_VK_SWIFTSHADER_ICD_JSON)
else if (icd == vk::ICD::SwiftShader)
{
if (!setICDEnvironment(WrapICDEnvironment(ANGLE_VK_SWIFTSHADER_ICD_JSON).c_str()))
{
ERR() << "Error setting environment for SwiftShader.";
}
}
# endif // defined(ANGLE_VK_SWIFTSHADER_ICD_JSON)
if (mEnableValidationLayers || icd != vk::ICD::Default)
{
const auto &cwd = angle::GetCWD();
if (!cwd.valid())
{
ERR() << "Error getting CWD for Vulkan layers init.";
mEnableValidationLayers = false;
mICD = vk::ICD::Default;
}
else
{
mPreviousCWD = cwd.value();
std::string exeDir = angle::GetExecutableDirectory();
mChangedCWD = angle::SetCWD(exeDir.c_str());
if (!mChangedCWD)
{
ERR() << "Error setting CWD for Vulkan layers init.";
mEnableValidationLayers = false;
mICD = vk::ICD::Default;
}
}
}
// Override environment variable to use the ANGLE layers.
if (mEnableValidationLayers)
{
if (!angle::PrependPathToEnvironmentVar(kLoaderLayersPathEnv, ANGLE_VK_LAYERS_DIR))
{
ERR() << "Error setting environment for Vulkan layers init.";
mEnableValidationLayers = false;
}
}
#endif // !defined(ANGLE_PLATFORM_ANDROID)
}
ScopedVkLoaderEnvironment::~ScopedVkLoaderEnvironment()
{
if (mChangedCWD)
{
#if !defined(ANGLE_PLATFORM_ANDROID)
ASSERT(mPreviousCWD.valid());
angle::SetCWD(mPreviousCWD.value().c_str());
#endif // !defined(ANGLE_PLATFORM_ANDROID)
}
if (mChangedICDEnv)
{
if (mPreviousICDEnv.value().empty())
{
angle::UnsetEnvironmentVar(kLoaderICDFilenamesEnv);
}
else
{
angle::SetEnvironmentVar(kLoaderICDFilenamesEnv, mPreviousICDEnv.value().c_str());
}
}
}
bool ScopedVkLoaderEnvironment::setICDEnvironment(const char *icd)
{
// Override environment variable to use built Mock ICD
// ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
mPreviousICDEnv = angle::GetEnvironmentVar(kLoaderICDFilenamesEnv);
mChangedICDEnv = angle::SetEnvironmentVar(kLoaderICDFilenamesEnv, icd);
if (!mChangedICDEnv)
{
mICD = vk::ICD::Default;
}
return mChangedICDEnv;
}
void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
vk::ICD preferredICD,
VkPhysicalDevice *physicalDeviceOut,
VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
{
ASSERT(!physicalDevices.empty());
ICDFilterFunc filter = GetFilterForICD(preferredICD);
for (const VkPhysicalDevice &physicalDevice : physicalDevices)
{
vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
if (filter(*physicalDevicePropertiesOut))
{
*physicalDeviceOut = physicalDevice;
return;
}
}
WARN() << "Preferred device ICD not found. Using default physicalDevice instead.";
// Fall back to first device.
*physicalDeviceOut = physicalDevices[0];
vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
}
} // namespace vk
} // namespace angle
| endlessm/chromium-browser | third_party/angle/src/common/vulkan/vulkan_icd.cpp | C++ | bsd-3-clause | 7,318 |
package gwlpr.protocol.gameserver.outbound;
import gwlpr.protocol.serialization.GWMessage;
/**
* Auto-generated by PacketCodeGen.
*
*/
public final class P293_GuildAnnouncement
extends GWMessage
{
private String announcement;
private String characterName;
@Override
public short getHeader() {
return 293;
}
public void setAnnouncement(String announcement) {
this.announcement = announcement;
}
public void setCharacterName(String characterName) {
this.characterName = characterName;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("P293_GuildAnnouncement[");
sb.append("announcement=").append(this.announcement.toString()).append(",characterName=").append(this.characterName.toString()).append("]");
return sb.toString();
}
}
| GameRevision/GWLP-R | protocol/src/main/java/gwlpr/protocol/gameserver/outbound/P293_GuildAnnouncement.java | Java | bsd-3-clause | 869 |
---
id: bd7123c9c549eddfaeb5bdef
title: 使用方括号查找字符串中的第一个字符
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8JwhW'
forumTopicId: 18341
dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
---
# --description--
方括号表示法(<dfn>Bracket notation</dfn>)是一种在字符串中的特定 index(索引)处获取字符的方法。
大多数现代编程语言,如 JavaScript,不同于人类从 1 开始计数。 它们是从 0 开始计数。 这被称为基于零(<dfn>Zero-based</dfn>)的索引。
例如,单词 `Charles` 的索引 0 的字符是 `C`。 所以如果 `const firstName = "Charles"`,你可以通过 `firstName[0]` 得到字符串第一个字母的值。
示例:
```js
const firstName = "Charles";
const firstLetter = firstName[0];
```
`firstLetter` 值为字符串 `C` 。
# --instructions--
使用方括号获取变量 `lastName` 中的第一个字符,并赋给变量 `firstLetterOfLastName`。
**提示:** 如果卡住了,请尝试查看上面的示例。
# --hints--
`firstLetterOfLastName` 变量值应该为 `L` 。
```js
assert(firstLetterOfLastName === 'L');
```
应该使用方括号表示法。
```js
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
```
# --seed--
## --after-user-code--
```js
(function(v){return v;})(firstLetterOfLastName);
```
## --seed-contents--
```js
// Setup
let firstLetterOfLastName = "";
const lastName = "Lovelace";
// Only change code below this line
firstLetterOfLastName = lastName; // Change this line
```
# --solutions--
```js
let firstLetterOfLastName = "";
const lastName = "Lovelace";
// Only change code below this line
firstLetterOfLastName = lastName[0];
```
| FreeCodeCamp/FreeCodeCamp | curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.md | Markdown | bsd-3-clause | 1,751 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_
#define CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_
#include "base/macros.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace extensions {
class SettingsPrivateEventRouter;
// This is a factory class used by the BrowserContextDependencyManager
// to instantiate the settingsPrivate event router per profile (since the
// extension event router is per profile).
class SettingsPrivateEventRouterFactory
: public BrowserContextKeyedServiceFactory {
public:
SettingsPrivateEventRouterFactory(const SettingsPrivateEventRouterFactory&) =
delete;
SettingsPrivateEventRouterFactory& operator=(
const SettingsPrivateEventRouterFactory&) = delete;
// Returns the SettingsPrivateEventRouter for |profile|, creating it if
// it is not yet created.
static SettingsPrivateEventRouter* GetForProfile(
content::BrowserContext* context);
// Returns the SettingsPrivateEventRouterFactory instance.
static SettingsPrivateEventRouterFactory* GetInstance();
protected:
// BrowserContextKeyedServiceFactory overrides:
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
bool ServiceIsCreatedWithBrowserContext() const override;
bool ServiceIsNULLWhileTesting() const override;
private:
friend struct base::DefaultSingletonTraits<SettingsPrivateEventRouterFactory>;
SettingsPrivateEventRouterFactory();
~SettingsPrivateEventRouterFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_
| nwjs/chromium.src | chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h | C | bsd-3-clause | 2,097 |
/*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
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 The University of Texas at Austin 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.
*/
#include "blis.h"
void bli_trmm_blk_var1f( obj_t* a,
obj_t* b,
obj_t* c,
gemm_t* cntl,
trmm_thrinfo_t* thread )
{
obj_t b_pack_s;
obj_t a1_pack_s, c1_pack_s;
obj_t a1, c1;
obj_t* a1_pack = NULL;
obj_t* b_pack = NULL;
obj_t* c1_pack = NULL;
dim_t i;
dim_t b_alg;
dim_t m_trans;
dim_t offA;
if( thread_am_ochief( thread ) ) {
// Initialize object for packing B.
bli_obj_init_pack( &b_pack_s );
bli_packm_init( b, &b_pack_s,
cntl_sub_packm_b( cntl ) );
// Scale C by beta (if instructed).
// Since scalm doesn't support multithreading yet, must be done by chief thread (ew)
bli_scalm_int( &BLIS_ONE,
c,
cntl_sub_scalm( cntl ) );
}
b_pack = thread_obroadcast( thread, &b_pack_s );
// Initialize all pack objects that are passed into packm_init().
if( thread_am_ichief( thread ) ) {
bli_obj_init_pack( &a1_pack_s );
bli_obj_init_pack( &c1_pack_s );
}
a1_pack = thread_ibroadcast( thread, &a1_pack_s );
c1_pack = thread_ibroadcast( thread, &c1_pack_s );
// Pack B (if instructed).
bli_packm_int( b, b_pack,
cntl_sub_packm_b( cntl ),
trmm_thread_sub_opackm( thread ) );
// Set the default length of and offset to the non-zero part of A.
m_trans = bli_obj_length_after_trans( *a );
offA = 0;
// If A is lower triangular, we have to adjust where the non-zero part of
// A begins. If A is upper triangular, we have to adjust the length of
// the non-zero part. If A is general/dense, then we keep the defaults.
if ( bli_obj_is_lower( *a ) )
offA = bli_abs( bli_obj_diag_offset_after_trans( *a ) );
else if ( bli_obj_is_upper( *a ) )
m_trans = bli_abs( bli_obj_diag_offset_after_trans( *a ) ) +
bli_obj_width_after_trans( *a );
dim_t start, end;
bli_get_range_weighted( thread, offA, m_trans,
bli_blksz_get_mult_for_obj( a, cntl_blocksize( cntl ) ),
bli_obj_is_upper( *c ), &start, &end );
// Partition along the m dimension.
for ( i = start; i < end; i += b_alg )
{
// Determine the current algorithmic blocksize.
b_alg = bli_determine_blocksize_f( i, end, a,
cntl_blocksize( cntl ) );
// Acquire partitions for A1 and C1.
bli_acquire_mpart_t2b( BLIS_SUBPART1,
i, b_alg, a, &a1 );
bli_acquire_mpart_t2b( BLIS_SUBPART1,
i, b_alg, c, &c1 );
// Initialize objects for packing A1 and C1.
if( thread_am_ichief( thread ) ) {
bli_packm_init( &a1, a1_pack,
cntl_sub_packm_a( cntl ) );
bli_packm_init( &c1, c1_pack,
cntl_sub_packm_c( cntl ) );
}
thread_ibarrier( thread );
// Pack A1 (if instructed).
bli_packm_int( &a1, a1_pack,
cntl_sub_packm_a( cntl ),
trmm_thread_sub_ipackm( thread ) );
// Pack C1 (if instructed).
bli_packm_int( &c1, c1_pack,
cntl_sub_packm_c( cntl ),
trmm_thread_sub_ipackm( thread ) );
// Perform trmm subproblem.
bli_trmm_int( &BLIS_ONE,
a1_pack,
b_pack,
&BLIS_ONE,
c1_pack,
cntl_sub_gemm( cntl ),
trmm_thread_sub_trmm( thread ) );
thread_ibarrier( thread );
// Unpack C1 (if C1 was packed).
bli_unpackm_int( c1_pack, &c1,
cntl_sub_unpackm_c( cntl ),
trmm_thread_sub_ipackm( thread ) );
}
// If any packing buffers were acquired within packm, release them back
// to the memory manager.
thread_obarrier( thread );
if( thread_am_ochief( thread ) )
bli_packm_release( b_pack, cntl_sub_packm_b( cntl ) );
if( thread_am_ichief( thread ) ){
bli_packm_release( a1_pack, cntl_sub_packm_a( cntl ) );
bli_packm_release( c1_pack, cntl_sub_packm_c( cntl ) );
}
}
| scibuilder/blis | frame/3/trmm/bli_trmm_blk_var1f.c | C | bsd-3-clause | 5,923 |
import eqpy
import sympy
from eqpy._utils import raises
def test_constants():
assert eqpy.nums.Catalan is sympy.Catalan
assert eqpy.nums.E is sympy.E
assert eqpy.nums.EulerGamma is sympy.EulerGamma
assert eqpy.nums.GoldenRatio is sympy.GoldenRatio
assert eqpy.nums.I is sympy.I
assert eqpy.nums.nan is sympy.nan
assert eqpy.nums.oo is sympy.oo
assert eqpy.nums.pi is sympy.pi
assert eqpy.nums.zoo is sympy.zoo
def test_sympify():
eqpy.nums.x = '1/2'
assert eqpy.nums.x == sympy.S('1/2')
assert eqpy.nums('2/3') == sympy.S('2/3')
assert raises(sympy.SympifyError, lambda: eqpy.nums('1.2.3'))
def test_dunders():
eqpy.nums.__mydunder__ = '1/2'
assert eqpy.nums.__mydunder__ == '1/2'
| eriknw/eqpy | eqpy/tests/test_nums.py | Python | bsd-3-clause | 747 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>getPieceAtRandom method - BitfieldPlus class - hetimatorrent.util library - Dart API</title>
<!-- required because all the links are pseudo-absolute -->
<base href="../..">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static-assets/prettify.css">
<link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
<link rel="stylesheet" href="static-assets/styles.css">
<meta name="description" content="API docs for the getPieceAtRandom method from the BitfieldPlus class, for the Dart programming language.">
<link rel="icon" href="static-assets/favicon.png">
<!-- Do not remove placeholder -->
<!-- Header Placeholder -->
</head>
<body>
<div id="overlay-under-drawer"></div>
<header class="container-fluid" id="title">
<nav class="navbar navbar-fixed-top">
<div class="container">
<button id="sidenav-left-toggle" type="button"> </button>
<ol class="breadcrumbs gt-separated hidden-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="hetimatorrent.util/hetimatorrent.util-library.html">hetimatorrent.util</a></li>
<li><a href="hetimatorrent.util/BitfieldPlus-class.html">BitfieldPlus</a></li>
<li class="self-crumb">getPieceAtRandom</li>
</ol>
<div class="self-name">getPieceAtRandom</div>
</div>
</nav>
<div class="container masthead">
<ol class="breadcrumbs gt-separated visible-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="hetimatorrent.util/hetimatorrent.util-library.html">hetimatorrent.util</a></li>
<li><a href="hetimatorrent.util/BitfieldPlus-class.html">BitfieldPlus</a></li>
<li class="self-crumb">getPieceAtRandom</li>
</ol>
<div class="title-description">
<h1 class="title">
<div class="kind">method</div> getPieceAtRandom
</h1>
<!-- p class="subtitle">
</p -->
</div>
<ul class="subnav">
<li><a href="hetimatorrent.util/BitfieldPlus/getPieceAtRandom.html#source">Source</a></li>
</ul>
</div>
</header>
<div class="container body">
<div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left">
<h5><a href="index.html">hetimatorrent</a></h5>
<h5><a href="hetimatorrent.util/hetimatorrent.util-library.html">hetimatorrent.util</a></h5>
<h5><a href="hetimatorrent.util/BitfieldPlus-class.html">BitfieldPlus</a></h5>
<ol>
<li class="section-title"><a href="hetimatorrent.util/BitfieldPlus-class.html#instance-properties">Properties</a></li>
<li><a href="hetimatorrent.util/BitfieldPlus/innerField.html">innerField</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/rawValue.html">rawValue</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/value.html">value</a>
</li>
<li class="section-title"><a href="hetimatorrent.util/BitfieldPlus-class.html#constructors">Constructors</a></li>
<li><a href="hetimatorrent.util/BitfieldPlus/BitfieldPlus.html">BitfieldPlus</a></li>
<li class="section-title"><a href="hetimatorrent.util/BitfieldPlus-class.html#methods">Methods</a></li>
<li><a href="hetimatorrent.util/BitfieldPlus/change.html">change</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getBinary.html">getBinary</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getIsOn.html">getIsOn</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getOffPieceAtRandom.html">getOffPieceAtRandom</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getOffPieceAtRandomPerByte.html">getOffPieceAtRandomPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getOnPieceAtRandom.html">getOnPieceAtRandom</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getOnPieceAtRandomPerByte.html">getOnPieceAtRandomPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getPieceAtRandom.html">getPieceAtRandom</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/getPieceAtRandomPerByte.html">getPieceAtRandomPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/isAllOff.html">isAllOff</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/isAllOffPerByte.html">isAllOffPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/isAllOn.html">isAllOn</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/isAllOnPerByte.html">isAllOnPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/lengthPerBit.html">lengthPerBit</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/lengthPerByte.html">lengthPerByte</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/oneClear.html">oneClear</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/setIsOn.html">setIsOn</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/update.html">update</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/writeBytes.html">writeBytes</a>
</li>
<li><a href="hetimatorrent.util/BitfieldPlus/zeroClear.html">zeroClear</a>
</li>
</ol>
</div><!--/.sidebar-offcanvas-->
<div class="col-xs-12 col-sm-9 col-md-6 main-content">
<section class="multi-line-signature">
<span class="returntype">int</span>
<span class="name ">getPieceAtRandom</span>(
<br>
<div class="parameters">
<span class="parameter" id="getPieceAtRandom-param-isOff"><span class="type-annotation">bool</span> <span class="parameter-name">isOff</span></span>
</div>
) </section>
<section class="desc markdown">
<p class="no-docs">Not documented.</p>
</section>
<section class="summary source-code" id="source">
<h2>Source</h2>
<pre><code class="prettyprint lang-dart">int getPieceAtRandom(bool isOff) {
int byteLength = innerField.lengthPerByte();
if (byteLength <= 0) {
return -1;
}
int ia = _rand.nextInt(byteLength);
bool findedAtIA = false;
for (int i = ia; i < byteLength; i++) {
if (isOff) {
if (!innerField.isAllOnPerByte(i)) {
ia = i;
findedAtIA = true;
break;
}
} else {
if (!innerField.isAllOffPerByte(i)) {
ia = i;
findedAtIA = true;
break;
}
}
}
if (!findedAtIA) {
for (int i = ia; i >= 0; i--) {
if (isOff) {
if (!innerField.isAllOnPerByte(i)) {
ia = i;
findedAtIA = true;
break;
}
} else {
if (!innerField.isAllOffPerByte(i)) {
ia = i;
findedAtIA = true;
break;
}
}
}
}
if (!findedAtIA) {
return -1;
}
if (isOff) {
return getOffPieceAtRandomPerByte(ia);
} else {
return getOnPieceAtRandomPerByte(ia);
}
}</code></pre>
</section>
</div> <!-- /.main-content -->
</div> <!-- container -->
<footer>
<div class="container-fluid">
<div class="container">
<p class="text-center">
<span class="no-break">
hetimatorrent 0.0.1 api docs
</span>
•
<span class="copyright no-break">
<a href="https://www.dartlang.org">
<img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16">
</a>
</span>
•
<span class="copyright no-break">
<a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a>
</span>
</p>
</div>
</div>
</footer>
<script src="static-assets/prettify.js"></script>
<script src="static-assets/script.js"></script>
<!-- Do not remove placeholder -->
<!-- Footer Placeholder -->
</body>
</html>
| kyorohiro/dart_hetimatorrent | doc/api/hetimatorrent.util/BitfieldPlus/getPieceAtRandom.html | HTML | bsd-3-clause | 8,297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.