answer stringlengths 15 1.25M |
|---|
#ifndef EVENTVISITOR_H_
#define EVENTVISITOR_H_
#include <einheri/utils/Visitor.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/EventWindowClose.h>
#include <einheri/common/event/EventWindowCreated.h>
#include <einheri/common/event/EventWindowResized.h>
#include <einheri/common/event/EventKeyPressed.h>
#include <einheri/common/event/EventKeyReleased.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/EventMonsterAdded.h>
#include <einheri/common/event/EventMonsterUpdated.h>
#include <einheri/common/event/EventHeroAdded.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/<API key>.h>
#include <einheri/common/event/EventKill.h>
#include <einheri/common/event/EventKilled.h>
#include <einheri/common/event/EventQuitGame.h>
namespace ein {
class EventVisitor
{
public:
virtual void Visit(const <API key>&){}
virtual void Visit(const <API key>&){}
virtual void Visit(const EventWindowClose&){}
virtual void Visit(const EventWindowCreated&){}
virtual void Visit(const EventWindowResized&){}
virtual void Visit(const EventKeyPressed&){}
virtual void Visit(const EventKeyReleased&){}
virtual void Visit(const <API key>&){}
virtual void Visit(const <API key>&){}
virtual void Visit(const EventMonsterAdded&){}
virtual void Visit(const EventMonsterUpdated&){}
virtual void Visit(const EventHeroAdded&){}
virtual void Visit(const <API key>&){}
virtual void Visit(const <API key>&){}
virtual void Visit(const EventKill&){}
virtual void Visit(const EventKilled&){}
virtual void Visit(const EventQuitGame&){}
};
} // namespace ehrCommon
#endif /* EVENTVISITOR_H_ */ |
import json
import math
import urllib.parse
import requests
from bs4 import BeautifulSoup as bSoup
from utils import utils
class DarazScraper:
# Declare URL and class names to picked
BASE_URL = 'https:
@staticmethod
def search_item(product):
# Read the page contents and get structured data using beautiful soup
encoded_url = DarazScraper.BASE_URL.format(urllib.parse.quote(product.name))
data = bSoup(requests.get(encoded_url).text, "html.parser")
# Find all the item containers
containers = data.findAll("script", {})[1]
# Extract JSON from extracted script
json_data = str(containers.text)
json_data = json_data.split("\n")
if json_data is None or len(json_data) < 2:
print("Invalid JSON in Daraz sraper: " + str(json))
return
json_data = json_data[1]
json_data = json_data.replace("jsTrackingStore.data = ", "")
json_data = json_data.replace(";", "")
json_data = json.loads(json_data)
# Get item information for each item in json
if len(json_data) > 0:
for x in json_data["products"]:
link = "-"
for div in data.findAll("div", {"class", "sku -gallery"}):
if div["data-sku"] == x:
link = div.a["href"]
key = json_data["products"][x]
title = key["name"]
brand = key["brand"]
price = key["priceLocal"]
if float(product.baseline_price) >= math.floor(float(price)) > 0:
prompt = "\"" + title.replace(",", "|") + "\" is now available in " + str(
price) + " at Daraz (Baseline: " + product.baseline_price + ")"
details = utils.get_details(brand, price, title, link)
if utils.is_similar(title, product.description):
utils.print_similarity(title, product.description)
utils.<API key>(brand, prompt)
utils.write_to_csv(details) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
import sys
import pygame
from gi.repository import Gtk
from sugar3.activity.activity import Activity
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.activity.widgets import <API key>
from sugar3.graphics.toolbutton import ToolButton
from sugar3.activity.widgets import StopButton
from sugar3.graphics.objectchooser import ObjectChooser
from gettext import gettext as _
import sugargame.canvas
import conozco
from points_list import Data
from save_util import save, fixValues
class IknowEditor(Activity):
def __init__(self, handle):
Activity.__init__(self, handle)
self.init_vars()
self.build_toolbar()
self.actividad = conozco.Conozco(self)
self.build_canvas()
self.run_canvas()
self.show_all()
def init_vars(self):
self._image = None
def build_toolbar(self):
self.max_participants = 1
toolbar_box = ToolbarBox()
self.set_toolbar_box(toolbar_box)
toolbar_box.show()
activity_button = <API key>(self)
toolbar_box.toolbar.insert(activity_button, -1)
activity_button.show()
# new pic button
new_pic = ToolButton('new-pic')
new_pic.connect('clicked', self._new_picture)
new_pic.set_tooltip(_('New picture'))
toolbar_box.toolbar.insert(new_pic, -1)
# add / remove point buttons
add_point = ToolButton("row-insert")
add_point.connect("clicked", self._add_point)
add_point.set_tooltip(_("Add a point"))
toolbar_box.toolbar.insert(add_point, -1)
rem_point = ToolButton("row-remove")
rem_point.connect("clicked", self._remove_point)
rem_point.set_tooltip(_("Remove the selected point"))
toolbar_box.toolbar.insert(rem_point, -1)
# save list button
save = ToolButton('filesave')
save.connect('clicked', self._save)
save.set_tooltip(_('Save data'))
toolbar_box.toolbar.insert(save, -1)
# separator and stop button
separator = Gtk.SeparatorToolItem()
separator.props.draw = False
separator.set_expand(True)
toolbar_box.toolbar.insert(separator, -1)
separator.show()
stop_button = StopButton(self)
toolbar_box.toolbar.insert(stop_button, -1)
stop_button.show()
def build_canvas(self):
self.table = Gtk.Table(1, 2, False)
self.box1 = Gtk.HBox()
self.box1.set_size_request(350, 350)
self.box1.show()
self.box2 = Gtk.HBox()
self.box2.set_size_request(50, 200)
self.box2.show()
self.table.attach(self.box1, 0, 1, 0, 1)
self.table.attach(self.box2, 1, 2, 0, 1)
self.labels_and_values = Data(self)
self.labels_and_values.connect("some-changed", self._some_changed)
self.box2.add(self.labels_and_values)
self.set_canvas(self.table)
def run_canvas(self):
self.actividad.canvas = sugargame.canvas.PygameCanvas(self,
main=self.actividad.run,
modules=[pygame.display, pygame.font])
self.box1.add(self.actividad.canvas)
self.actividad.canvas.grab_focus()
def _save(self, widget):
l = self.labels_and_values.get_info()
scale = self.actividad.getScale()
shiftx = self.actividad.getShiftX()
shifty = self.actividad.getShiftY()
ready = fixValues(l, scale, shiftx, shifty)
save(ready)
def _new_picture(self, widget):
try:
chooser = ObjectChooser(parent=self)
except:
chooser = None
f = None
if chooser is not None:
result = chooser.run()
if result == Gtk.ResponseType.ACCEPT:
dsobject = chooser.get_selected_object()
f = dsobject.file_path
if f is not None:
self._image = pygame.image.load(f)
self.actividad.set_background(self._image)
def _add_point(self, widget, label="", value="City", dx='0', dy='-14'):
pos = self.labels_and_values.add_value(label, value, dx, dy)
def _remove_point(self, widget):
path = self.labels_and_values.<API key>()
self._update_points()
def _add_coor(self, pos):
if self._image is not None:
self.labels_and_values.<API key>(pos)
def _some_changed(self, treeview, path, new_label):
self._update_points()
def _update_points(self):
l = self.labels_and_values.get_info()
self.actividad.update_points(l) |
/*
* @lc app=leetcode id=74 lang=c
*
* [74] Search a 2D Matrix
*
* autogenerated using scripts/convert.py
*/
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
int start = 0, end = matrixRowSize - 1, mid, *row = NULL;
if ((! (matrixRowSize && matrixColSize)) || target < matrix[0][0])
return 0;
while (start < end - 1) {
mid = (start + end) / 2;
if (matrix[mid][0] < target)
start = mid;
else if (matrix[mid][0] > target)
end = mid;
else
return 1;
}
if (target >= matrix[end][0]) {
row = matrix[end];
} else {
row = matrix[start];
}
if (target > row[matrixColSize - 1]) {
return 0;
}
start = 0;
end = matrixColSize - 1;
while (start < end - 1) {
mid = (start + end) / 2;
if (row[mid] < target)
start = mid;
else if (row[mid] > target)
end = mid;
else
return 1;
}
if (row[start] == target || row[end] == target)
return 1;
return 0;
} |
#ifndef __INC_DMX_H
#define __INC_DMX_H
#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
//#define USE_INTERBYTE_DELAY // rare cases of equipment non full DMX-512 compliant, need this
#define USE_UART0
#define USE_UART1
#define USE_UART2
#define USE_UART3
#define DMX512 (0) // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512
#define DMX1024 (1) // DMX-1024 (500 kbaud - 1024 channels) Completely non standard - TESTED ok
#define DMX2048 (2) // DMX-2048 (1000 kbaud - 2048 channels) called by manufacturers DMX1000K, DMX 4x or DMX 1M ???
// DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512
#define IBG_512 (10) // interbyte gap [us]
#define DMX_512 ((F_CPU/(250000*8))-1) // 250 kbaud
#define BREAK_512 ( F_CPU/(100000*8)) // 90.9 kbaud
// DMX-1024 (500 kbaud - 1024 channels) Completely non standard
#define IBG_1024 (5) // interbyte gap [us]
#define DMX_1024 ((F_CPU/(500000*8))-1) // 500 kbaud
#define BREAK_1024 ( F_CPU/(200000*8)) // 181.8 kbaud
// DMX-2048 (1000 kbaud - 2048 channels) Non standard, but used by manufacturers as DMX1000K or DMX-4x or DMX 1M ???
#define IBG_2048 (2) // interbyte gap [us] + nop's to reach 2.5 uS
#define DMX_2048 ((F_CPU/(1000000*8))-1) // 1000 kbaud
#define BREAK_2048 ( F_CPU/(400000*8)) // 363.6 kbaud
// Inline assembly: do nothing for one clock cycle.
#define nop() __asm__ __volatile__("nop")
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#if defined(USE_UART0)
void SIG_USART0_RECV (void) __attribute__((__always_inline__));
void SIG_USART0_TRANS (void) __attribute__((__always_inline__));
#endif
#if defined(USE_UART1)
void SIG_USART1_RECV (void) __attribute__((__always_inline__));
void SIG_USART1_TRANS (void) __attribute__((__always_inline__));
#endif
#if defined(USE_UART2)
void SIG_USART2_RECV (void) __attribute__((__always_inline__));
void SIG_USART2_TRANS (void) __attribute__((__always_inline__));
#endif
#if defined(USE_UART3)
void SIG_USART3_RECV (void) __attribute__((__always_inline__));
void SIG_USART3_TRANS (void) __attribute__((__always_inline__));
#endif
#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
#if defined(USE_UART0)
void USART_RX_vect (void) __attribute__((__always_inline__));
void USART_TX_vect (void) __attribute__((__always_inline__));
#endif
#endif
#ifdef __cplusplus
};
#endif
class CArduinoDmx
{
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#if defined(USE_UART0)
friend void SIG_USART0_RECV (void);
friend void SIG_USART0_TRANS (void);
#endif
#if defined(USE_UART1)
friend void SIG_USART1_RECV (void);
friend void SIG_USART1_TRANS (void);
#endif
#if defined(USE_UART2)
friend void SIG_USART2_RECV (void);
friend void SIG_USART2_TRANS (void);
#endif
#if defined(USE_UART3)
friend void SIG_USART3_RECV (void);
friend void SIG_USART3_TRANS (void);
#endif
#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
#if defined(USE_UART0)
friend void USART_RX_vect (void);
friend void USART_TX_vect (void);
#endif
#endif
public:
enum {IDLE, BREAK, STARTB, STARTADR}; // RX DMX states
enum {TXBREAK, TXSTARTB, TXDATA}; // TX DMX states
volatile uint8_t *RxBuffer; // array of RX DMX values
volatile uint8_t *TxBuffer; // array of TX DMX values
private:
uint8_t gRxState;
uint8_t *gRxPnt;
uint8_t IndicatorCount;
uint8_t USARTstate;
uint8_t RxByte;
uint8_t RxState;
uint8_t mUART;
uint8_t gTxState;
uint16_t RxCount;
uint16_t gCurTxCh;
uint16_t rx_channels; // rx channels number
uint16_t tx_channels; // tx channels number
uint16_t rx_address; // rx start address
uint16_t tx_address; // tx start address
int8_t rx_led; // rx indicator led pin
int8_t tx_led; // tx indicator led pin
int8_t control_pin; // max485 input/output selection pin
uint8_t dmx_mode; // Standard USITT DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2
uint8_t speed_dmx;
uint8_t speed_break;
uint16_t CurTxCh;
uint8_t TxState;
uint8_t *RxPnt;
#if defined(USE_INTERBYTE_DELAY)
void delay_gap ();
#endif
public:
void stop_dmx ();
void set_speed (uint8_t mode);
void set_control_pin (int8_t pin) { control_pin = pin; }
void init_rx (uint8_t mode); // Standard USITT DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2
void set_rx_address (uint16_t address) { rx_address = address; }
void set_rx_channels (uint16_t channels) { rx_channels = channels; }
void init_tx (uint8_t mode); // Standard USITT DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2
void set_tx_address (uint16_t address) { tx_address = address; }
void set_tx_channels (uint16_t channels) { tx_channels = channels; }
void attachTXInterrupt (void (*isr)(uint8_t uart)) { TXisrCallback = isr; } // register the user TX callback
void attachRXInterrupt (void (*isr)(uint8_t uart)) { RXisrCallback = isr; } // register the user RX callback
void (*TXisrCallback) (uint8_t uart);
void (*RXisrCallback) (uint8_t uart);
inline void Process_ISR_RX (uint8_t rx_isr_number);
inline void Process_ISR_TX (uint8_t tx_isr_number);
public:
CArduinoDmx (uint8_t uart) { rx_address = 1;
rx_channels = 8;
tx_address = 1;
tx_channels = 8;
mUART = uart; }
};
#if defined(USE_UART0)
extern CArduinoDmx ArduinoDmx0;
#endif
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#if defined(USE_UART1)
extern CArduinoDmx ArduinoDmx1;
#endif
#if defined(USE_UART2)
extern CArduinoDmx ArduinoDmx2;
#endif
#if defined(USE_UART3)
extern CArduinoDmx ArduinoDmx3;
#endif
#endif
#endif |
import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
export default class Reply extends Component {
static propTypes = {
className: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
stroke: PropTypes.string,
fill: PropTypes.string,
svgProps: PropTypes.object
};
static defaultProps = {
className: "",
size: "inherit",
stroke: "currentColor",
fill: "currentColor",
svgProps: {}
};
get defaultHeight() {
return 16;
}
get defaultWidth() {
return 16;
}
get size() {
return this.props.size;
}
get width() {
if (this.size === null || this.size === "inherit") return null;
if (this.size === "default") return this.defaultWidth;
return this.size;
}
get height() {
if (this.size === null || this.size === "inherit") return null;
if (this.size === "default") return this.defaultHeight;
return this.size;
}
get viewBox() {
return "0 0 16 16";
}
get classes() {
const { className } = this.props;
return classnames("manicon-svg", className);
}
get fill() {
return this.props.fill;
}
get stroke() {
return this.props.stroke;
}
render() {
const baseSvgProps = {
xmlns: "http:
className: this.classes,
width: this.width,
height: this.height,
viewBox: this.viewBox
};
const svgProps = Object.assign(baseSvgProps, this.props.svgProps);
return (
<svg {...svgProps}>
<g fill="none" fillRule="evenodd">
<path
fill={this.fill}
d="M8.49999995,1.5 L14.4999999,6 L8.49999995,10.5 L8.49999995,1.5 Z M8.5,5 L8.5,7 C4.47029597,7 3.5000232,8.08962773 3.5009999,11.8602778 L3.5,15.0003185 L1.5,14.9996815 L1.50099998,11.8602184 C1.49974956,7.03363911 3.31062917,5 8.5,5 Z"
/>
</g>
</svg>
);
}
} |
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
namespace test
{
template <int streamFd>
class DisableStream
{
public:
explicit DisableStream(FILE* handle)
: fileDescriptor(dup(streamFd)), fileHandle(handle)
{
fflush(fileHandle);
[[maybe_unused]] const auto rtn = freopen("NUL", "a", fileHandle);
}
DisableStream(const DisableStream&) = delete;
~DisableStream()
{
fflush(fileHandle);
dup2(fileDescriptor, streamFd);
}
DisableStream& operator=(const DisableStream&) = delete;
private:
const int fileDescriptor;
FILE* fileHandle;
};
using DisableStdout = DisableStream<STDOUT_FILENO>;
using DisableStderr = DisableStream<STDERR_FILENO>;
} |
//! # HTTP Response generation
//! The HTTP Response code converts response objects into octets and
//! writes them to a stream.
// Imports
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::borrow::Cow;
// Public Types
#[derive(Debug, Clone, Copy)]
pub enum HttpResponseStatus {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
OK = 200,
Created = 201,
Accepted = 202,
Non<API key> = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
SwitchProxy = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
Proxy<API key> = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
URITooLong = 414,
<API key> = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
IAmATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
UpgradeRequired = 426,
<API key> = 428,
TooManyRequests = 429,
<API key> = 431,
<API key> = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
<API key> = 505,
<API key> = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
Network<API key> = 511,
}
An HTTP Response.
Fully describes the HTTP response sent from the server to the client.
Because the user can create these objects, we use a Cow to allow them
to supply either an `&str` or a `std::string::String`.
#[derive(Debug)]
pub struct HttpResponse<'a> {
The HTTP result code - @todo should be an enum
pub status: HttpResponseStatus,
The protocol the client is using in the response
pub protocol: Cow<'a, str>,
Any headers supplied by the server in the response
pub headers: HashMap<Cow<'a, str>, Cow<'a, str>>,
The response body
pub body: Cow<'a, str>,
}
// Private Types
// None
// Public Functions
impl<'a> HttpResponse<'a> {
pub fn new<S>(status: HttpResponseStatus, protocol: S) -> HttpResponse<'a>
where S: Into<Cow<'a, str>>
{
HttpResponse::new_with_body(status, protocol, Cow::Borrowed(""))
}
pub fn new_with_body<S, T>(status: HttpResponseStatus, protocol: S, body: T) -> HttpResponse<'a>
where S: Into<Cow<'a, str>>,
T: Into<Cow<'a, str>>
{
HttpResponse {
status: status,
protocol: protocol.into(),
headers: HashMap::new(),
body: body.into(),
}
}
pub fn write<T: io::Write>(&self, sink: &mut T) -> io::Result<usize> {
let header: String = format!("{} {}\r\n", self.protocol, self.status);
let mut total: usize = 0;
total += try!(sink.write(header.as_bytes()));
for (k, v) in &self.headers {
let line = format!("{}: {}\r\n", k, v);
total += try!(sink.write(line.as_bytes()));
}
total += try!(sink.write(b"\r\n"));
total += try!(sink.write(self.body.as_bytes()));
return Ok(total);
}
pub fn add_header<S, T>(&mut self, key: S, value: T)
where S: Into<Cow<'a, str>>,
T: Into<Cow<'a, str>>
{
self.headers.insert(key.into(), value.into());
}
}
impl fmt::Display for HttpResponseStatus {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Write strictly the first element into the supplied output
// stream: `f`. Returns `fmt::Result` which indicates whether the
// operation succeeded or failed. Note that `write!` uses syntax which
// is very similar to `println!`.
write!(f, "{} {}", *self as u32, self.as_string())
}
}
impl HttpResponseStatus {
pub fn as_string(&self) -> &str {
match *self {
HttpResponseStatus::Continue => "Continue",
HttpResponseStatus::SwitchingProtocols => "Switching Protocols",
HttpResponseStatus::Processing => "Processing",
HttpResponseStatus::OK => "OK",
HttpResponseStatus::Created => "Created",
HttpResponseStatus::Accepted => "Accepted",
HttpResponseStatus::Non<API key> => "Non-Authoritative Information",
HttpResponseStatus::NoContent => "No Content",
HttpResponseStatus::ResetContent => "Reset Content",
HttpResponseStatus::PartialContent => "Partial Content",
HttpResponseStatus::MultiStatus => "Multi Status",
HttpResponseStatus::AlreadyReported => "Already Reported",
HttpResponseStatus::ImUsed => "IM Used",
HttpResponseStatus::MultipleChoices => "Multiple Choices",
HttpResponseStatus::MovedPermanently => "Moved Permanently",
HttpResponseStatus::Found => "Found",
HttpResponseStatus::SeeOther => "See Other",
HttpResponseStatus::NotModified => "Not Modified",
HttpResponseStatus::UseProxy => "Use Proxy",
HttpResponseStatus::SwitchProxy => "Switch Proxy",
HttpResponseStatus::TemporaryRedirect => "Temporary Redirect",
HttpResponseStatus::PermanentRedirect => "Permanent Redirect",
HttpResponseStatus::BadRequest => "Bad Request",
HttpResponseStatus::Unauthorized => "Unauthorized",
HttpResponseStatus::PaymentRequired => "Payment Required",
HttpResponseStatus::Forbidden => "Forbidden",
HttpResponseStatus::NotFound => "Not Found",
HttpResponseStatus::MethodNotAllowed => "Method Not Allowed",
HttpResponseStatus::NotAcceptable => "Not Acceptable",
HttpResponseStatus::Proxy<API key> => "Proxy Authentication Required",
HttpResponseStatus::RequestTimeout => "Request Timeout",
HttpResponseStatus::Conflict => "Conflict",
HttpResponseStatus::Gone => "Gone",
HttpResponseStatus::LengthRequired => "Length Required",
HttpResponseStatus::PreconditionFailed => "Precondition Failed",
HttpResponseStatus::PayloadTooLarge => "Payload Too Large",
HttpResponseStatus::URITooLong => "URI Too Long",
HttpResponseStatus::<API key> => "Unsupported Media Type",
HttpResponseStatus::RangeNotSatisfiable => "Range Not Satisfiable",
HttpResponseStatus::ExpectationFailed => "Expectation Failed",
HttpResponseStatus::IAmATeapot => "I'm A Teapot",
HttpResponseStatus::MisdirectedRequest => "Misdirected Request",
HttpResponseStatus::UnprocessableEntity => "Unprocessable Entity",
HttpResponseStatus::Locked => "Locked",
HttpResponseStatus::FailedDependency => "Failed Dependency",
HttpResponseStatus::UpgradeRequired => "Upgrade Required",
HttpResponseStatus::<API key> => "Precondition Required",
HttpResponseStatus::TooManyRequests => "Too Many Requests",
HttpResponseStatus::<API key> => "Request Header Fields Too Large",
HttpResponseStatus::<API key> => "Unavailable For Legal Reasons",
HttpResponseStatus::InternalServerError => "Internal Server Error",
HttpResponseStatus::NotImplemented => "Not Implemented",
HttpResponseStatus::BadGateway => "Bad Gateway",
HttpResponseStatus::ServiceUnavailable => "Service Unavailable",
HttpResponseStatus::GatewayTimeout => "Gateway Timeout",
HttpResponseStatus::<API key> => "HTTP Version Not Supported",
HttpResponseStatus::<API key> => "Variant Also Negotiates",
HttpResponseStatus::InsufficientStorage => "Insufficient Storage",
HttpResponseStatus::LoopDetected => "Loop Detected",
HttpResponseStatus::NotExtended => "Not Extended",
HttpResponseStatus::Network<API key> => "Network Authentication Required",
}
}
}
// Private Functions
// None
// End Of File |
#include <DDesktopServices>
#include <DTitlebar>
#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QProcess>
#include <QStandardPaths>
#include <daboutdialog.h>
#include "home_page.h"
#include "list_page.h"
#include "main_window.h"
#include "record_page.h"
#include "toolbar.h"
#include "utils.h"
<API key>
DCORE_USE_NAMESPACE
const int MainWindow::PAGE_TYPE_HOME = 1;
const int MainWindow::PAGE_TYPE_RECORD = 2;
const int MainWindow::PAGE_TYPE_LIST = 3;
MainWindow::MainWindow(DMainWindow *parent) : DMainWindow(parent)
{
menu = new QMenu();
newRecordAction = new QAction(tr("New recording"), this);
connect(newRecordAction, &QAction::triggered, this, &MainWindow::newRecord);
<API key> = new QAction(tr("Open saved directory"), this);
connect(<API key>, &QAction::triggered, this, &MainWindow::openSaveDirectory);
menu->addAction(newRecordAction);
menu->addSeparator();
menu->addAction(<API key>);
if (this->titlebar()) {
this->titlebar()->setMenu(menu);
Toolbar *toolbar = new Toolbar();
this->titlebar()->setCustomWidget(toolbar, Qt::AlignVCenter, false);
this->setFixedSize(440, 550);
this->titlebar()-><API key>(true);
}
layoutWidget = new QWidget();
this->setCentralWidget(layoutWidget);
stackedLayout = new QStackedLayout();
layoutWidget->setLayout(stackedLayout);
showFirstPage();
}
void MainWindow::showFirstPage()
{
QFileInfoList fileInfoList = Utils::<API key>();
if (fileInfoList.size() > 0) {
showListPage("");
} else {
showHomePage();
}
}
void MainWindow::showHomePage()
{
pageType = PAGE_TYPE_HOME;
QWidget *currentWidget = stackedLayout->currentWidget();
if (currentWidget != 0) {
currentWidget->deleteLater();
}
homePage = new HomePage();
connect(homePage->recordButton, SIGNAL(clicked()), this, SLOT(showRecordPage()));
stackedLayout->addWidget(homePage);
}
void MainWindow::showRecordPage()
{
pageType = PAGE_TYPE_RECORD;
QWidget *currentWidget = stackedLayout->currentWidget();
if (currentWidget != 0) {
currentWidget->deleteLater();
}
recordPage = new RecordPage();
connect(recordPage, &RecordPage::finishRecord, this, &MainWindow::showListPage);
connect(recordPage, &RecordPage::cancelRecord, this, &MainWindow::showFirstPage);
stackedLayout->addWidget(recordPage);
}
void MainWindow::showListPage(QString recordingPath)
{
pageType = PAGE_TYPE_LIST;
QWidget *currentWidget = stackedLayout->currentWidget();
if (currentWidget != 0) {
currentWidget->deleteLater();
}
listPage = new ListPage();
connect(listPage, SIGNAL(clickRecordButton()), this, SLOT(showRecordPage()));
connect(listPage->fileView, &FileView::listClear, this, &MainWindow::showHomePage);
if (recordingPath != "") {
listPage->selectItemWithPath(recordingPath);
}
stackedLayout->addWidget(listPage);
}
void MainWindow::newRecord()
{
if (pageType == PAGE_TYPE_RECORD) {
recordPage->stopRecord();
} else if (pageType == PAGE_TYPE_LIST) {
listPage->stopPlayer();
}
showRecordPage();
}
void MainWindow::openSaveDirectory()
{
DDesktopServices::showFolder(Utils::<API key>());
} |
package es.maltimor.genericDoc.parser;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TokenArray {
final Logger log = LoggerFactory.getLogger(TokenArray.class);
private boolean eof;
private int pos;
private List<String> listaTokens;
private String act;
private String sep;
private int savePos;
public TokenArray(String sep){
this.listaTokens = new ArrayList<String>();
this.savePos = 0;
this.pos = 0;
this.act = "";
this.eof = true;
this.sep = sep;
}
public boolean isEof() {
return eof;
}
public void setEof(boolean eof) {
this.eof = eof;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public List<String> getListaTokens() {
return listaTokens;
}
public void setListaTokens(List<String> listaTokens) {
this.listaTokens = listaTokens;
}
public String getAct() {
return act;
}
public void setAct(String act) {
this.act = act;
}
public boolean isSep(){
return sep.contains(this.act);
}
/**
* Consume un token y devuelve el token consumido
* @return
*/
public String consumeToken(){
if (eof) return "";
String res = listaTokens.get(pos);
pos++;
if (pos<listaTokens.size()) {
act = listaTokens.get(pos);
} else {
eof = true;
act = "";
}
return res;
}
public void addToken(String token) {
if (eof){
this.act = token;
this.eof = false;
}
listaTokens.add(token);
}
public String getSep() {
return sep;
}
public void setSep(String sep) {
this.sep = sep;
}
public void saveState(){
this.savePos=pos;
}
public void restoreState(){
this.pos = savePos;
this.act = listaTokens.get(pos);
this.eof = pos>=listaTokens.size();
}
} |
#include <firstinclude.h>
double add(double a,double b); |
package basic.<API key>;
public interface Calculation {
double multiplex(double result, double operand);
double add(double result, double operand);
double divide(double result, double operand);
double sub(double result, double operand);
} |
'use strict'
const mh = require('multihashes')
const assert = require('assert')
class DAGNode {
constructor (data, links, serialized, multihash) {
assert(serialized, 'DAGNode needs its serialized format')
assert(multihash, 'DAGNode needs its multihash')
if (typeof multihash === 'string') {
multihash = mh.fromB58String(multihash)
}
this._data = data || Buffer.alloc(0)
this._links = links || []
this._serialized = serialized
this._multihash = multihash
this._size = this.links.reduce((sum, l) => sum + l.size, this.serialized.length)
this._json = {
data: this.data,
links: this.links.map((l) => l.toJSON()),
multihash: mh.toB58String(this.multihash),
size: this.size
}
}
toJSON () {
return this._json
}
toString () {
const mhStr = mh.toB58String(this.multihash)
return `DAGNode <${mhStr} - data: "${this.data.toString()}", links: ${this.links.length}, size: ${this.size}>`
}
get data () {
return this._data
}
set data (data) {
throw new Error("Can't set property: 'data' is immutable")
}
get links () {
return this._links
}
set links (links) {
throw new Error("Can't set property: 'links' is immutable")
}
get serialized () {
return this._serialized
}
set serialized (serialized) {
throw new Error("Can't set property: 'serialized' is immutable")
}
get size () {
return this._size
}
set size (size) {
throw new Error("Can't set property: 'size' is immutable")
}
get multihash () {
return this._multihash
}
set multihash (multihash) {
throw new Error("Can't set property: 'multihash' is immutable")
}
}
exports = module.exports = DAGNode
exports.create = require('./create')
exports.clone = require('./clone')
exports.addLink = require('./addLink')
exports.rmLink = require('./rmLink') |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace TailBlazer.Views
{
public class VirtualScrollPanel : VirtualizingPanel, IScrollInfo
{
private const double ScrollLineAmount = 16.0;
private Size _extentSize;
private ExtentInfo _extentInfo = new ExtentInfo();
private Size _viewportSize;
private Point _offset;
private ItemsControl _itemsControl;
private readonly Dictionary<UIElement, Rect> _childLayouts = new Dictionary<UIElement, Rect>();
private <API key> _itemsGenerator;
private bool _isInMeasure;
public static readonly DependencyProperty ItemHeightProperty =
DependencyProperty.Register("ItemHeight", typeof(double), typeof(VirtualScrollPanel), new PropertyMetadata(1.0, OnRequireMeasure));
private static readonly DependencyProperty <API key> =
DependencyProperty.RegisterAttached("VirtualItemIndex", typeof(int), typeof(VirtualScrollPanel), new PropertyMetadata(-1));
public static readonly DependencyProperty TotalItemsProperty =
DependencyProperty.Register("TotalItems", typeof (int), typeof (VirtualScrollPanel), new PropertyMetadata(default(int),OnRequireMeasure));
public static readonly DependencyProperty StartIndexProperty =
DependencyProperty.Register("StartIndex", typeof(int), typeof(VirtualScrollPanel), new PropertyMetadata(default(int), OnStartIndexChanged));
public static readonly DependencyProperty <API key> = DependencyProperty.Register(
"ScrollReceiver", typeof (IScrollReceiver), typeof (VirtualScrollPanel), new PropertyMetadata(default(IScrollReceiver)));
public IScrollReceiver ScrollReceiver
{
get { return (IScrollReceiver) GetValue(<API key>); }
set { SetValue(<API key>, value); }
}
public int StartIndex
{
get { return (int) GetValue(StartIndexProperty); }
set { SetValue(StartIndexProperty, value); }
}
public int TotalItems
{
get { return (int) GetValue(TotalItemsProperty); }
set { SetValue(TotalItemsProperty, value); }
}
private static int GetVirtualItemIndex(DependencyObject obj)
{
return (int)obj.GetValue(<API key>);
}
private static void SetVirtualItemIndex(DependencyObject obj, int value)
{
obj.SetValue(<API key>, value);
}
public double ItemHeight
{
get { return (double)GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
public double ItemWidth => _extentSize.Width;
public VirtualScrollPanel()
{
if (!DesignerProperties.GetIsInDesignMode(this))
Dispatcher.BeginInvoke(new Action(Initialize));
}
private void Initialize()
{
_itemsControl = ItemsControl.GetItemsOwner(this);
_itemsGenerator = (<API key>)<API key>;
InvalidateMeasure();
}
private static void OnStartIndexChanged(DependencyObject d, <API key> e)
{
var panel = (VirtualScrollPanel)d;
panel. <API key>(Convert.ToInt32(e.NewValue));
panel.InvalidateMeasure();
}
private static void OnRequireMeasure(DependencyObject d, <API key> e)
{
var panel = (VirtualScrollPanel)d;
panel.InvalidateMeasure();
panel.<API key>();
}
protected override void OnItemsChanged(object sender, <API key> args)
{
base.OnItemsChanged(sender, args);
InvalidateMeasure();
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
if (!sizeInfo.HeightChanged) return;
var items = (int)(sizeInfo.NewSize.Height / ItemHeight) ;
InvokeSizeCommand(items);
}
protected override Size MeasureOverride(Size availableSize)
{
if (_itemsControl == null) return availableSize;
_isInMeasure = true;
_childLayouts.Clear();
_extentInfo = <API key>(availableSize);
<API key>(_extentInfo);
var layoutInfo = GetLayoutInfo(availableSize, ItemHeight, _extentInfo);
RecycleItems(layoutInfo);
// Determine where the first item is in relation to previously realized items
var <API key> = _itemsGenerator.<API key>(layoutInfo.<API key>);
var visualIndex = 0;
double widestWidth = 0;
var currentX = layoutInfo.<API key>;
var currentY = layoutInfo.<API key>;
using (_itemsGenerator.StartAt(<API key>, GeneratorDirection.Forward, true))
{
var children = new List<UIElement>();
for (var itemIndex = layoutInfo.<API key>; itemIndex <= layoutInfo.<API key>; itemIndex++, visualIndex++)
{
bool newlyRealized;
var child = (UIElement)_itemsGenerator.GenerateNext(out newlyRealized);
if (child==null) continue;
children.Add(child);
SetVirtualItemIndex(child, itemIndex);
if (newlyRealized)
{
InsertInternalChild(visualIndex, child);
}
else
{
// check if item needs to be moved into a new position in the Children collection
if (visualIndex < Children.Count)
{
if (Equals(Children[visualIndex], child)) continue;
var childCurrentIndex = Children.IndexOf(child);
if (childCurrentIndex >= 0)
{
<API key>(childCurrentIndex, 1);
}
InsertInternalChild(visualIndex, child);
}
else
{
// we know that the child can't already be in the children collection
// because we've been inserting children in correct visualIndex order,
// and this child has a visualIndex greater than the Children.Count
AddInternalChild(child);
}
}
}
//part 2: do the measure
foreach (var child in children)
{
_itemsGenerator.<API key>(child);
child.Measure(new Size(double.PositiveInfinity, ItemHeight));
widestWidth= Math.Max(widestWidth, child.DesiredSize.Width);
}
//part 3: Create the elements
foreach (var child in children)
{
_childLayouts.Add(child, new Rect(currentX, currentY, Math.Max(widestWidth,_viewportSize.Width), ItemHeight));
currentY += ItemHeight;
}
}
<API key>();
UpdateScrollInfo(availableSize, _extentInfo, widestWidth);
_isInMeasure = false;
return availableSize;
}
private void <API key>(ExtentInfo extentInfo)
{
_offset.Y = Clamp(_offset.Y, 0, extentInfo.MaxVerticalOffset);
}
private void RecycleItems(ItemLayoutInfo layoutInfo)
{
foreach (UIElement child in Children)
{
var virtualItemIndex = GetVirtualItemIndex(child);
if (virtualItemIndex < layoutInfo.<API key> || virtualItemIndex > layoutInfo.<API key>)
{
var generatorPosition = _itemsGenerator.<API key>(virtualItemIndex);
if (generatorPosition.Index >= 0)
{
_itemsGenerator.Recycle(generatorPosition, 1);
}
}
SetVirtualItemIndex(child, -1);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach (UIElement child in Children)
{
child.Arrange(_childLayouts[child]);
}
return finalSize;
}
private void UpdateScrollInfo(Size availableSize, ExtentInfo extentInfo, double actualWidth)
{
_viewportSize = availableSize;
_extentSize = new Size(actualWidth, extentInfo.Height);
<API key>();
}
private void <API key>()
{
ScrollOwner?.<API key>();
}
private void <API key>()
{
// iterate backwards through the child collection because we're going to be
// removing items from it
for (var i = Children.Count - 1; i >= 0; i
{
var child = Children[i];
// if the virtual item index is -1, this indicates
// it is a recycled item that hasn't been reused this time round
if (GetVirtualItemIndex(child) == -1)
{
<API key>(i, 1);
}
}
}
private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
{
if (_itemsControl == null)
{
return new ItemLayoutInfo();
}
// we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
// so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
// navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items
// in that row
var firstVisibleLine = (int)Math.Floor(_offset.Y / itemHeight);
var firstRealizedIndex = Math.Max(firstVisibleLine - 1, 0);
var <API key> = firstRealizedIndex * ItemWidth - HorizontalOffset;
var <API key> = (firstRealizedIndex ) * itemHeight - _offset.Y;
var <API key> = (firstVisibleLine == 0 ? <API key> : <API key> + ItemHeight);
var <API key> = (int)Math.Ceiling((availableSize.Height - <API key>) / itemHeight);
var lastRealizedIndex = Math.Min(firstRealizedIndex + <API key> + 2, _itemsControl.Items.Count - 1);
return new ItemLayoutInfo
{
<API key> = firstRealizedIndex,
<API key> = <API key>,
<API key> = <API key>,
<API key> = lastRealizedIndex
};
}
private ExtentInfo <API key>(Size viewPortSize)
{
if (_itemsControl == null)
return new ExtentInfo();
var extentHeight = Math.Max(TotalItems * ItemHeight, viewPortSize.Height);
var maxVerticalOffset = extentHeight;// extentHeight - viewPortSize.Height;
var verticalOffset = (StartIndex /(double) TotalItems)*maxVerticalOffset;
var info = new ExtentInfo
{
VirtualCount = _itemsControl.Items.Count,
TotalCount = TotalItems,
Height = extentHeight,
VerticalOffset = verticalOffset,
MaxVerticalOffset = maxVerticalOffset
};
return info;
}
public void SetHorizontalOffset(double offset)
{
offset = Clamp(offset, 0, ExtentWidth - ViewportWidth);
if (offset<0)
{
_offset.X = 0;
}
else
{
_offset = new Point(offset, _offset.Y);
}
<API key>();
InvalidateMeasure();
}
public void SetVerticalOffset(double offset)
{
if (double.IsInfinity(offset)) return;
var diff = (int)((offset - _extentInfo.VerticalOffset) / ItemHeight);
<API key>(diff);
}
private double Clamp(double value, double min, double max)
{
return Math.Min(Math.Max(value, min), max);
}
private int _firstIndex;
private int _size;
private void <API key>(int lines)
{
if (_isInMeasure) return;
var firstIndex = StartIndex + lines;
if (firstIndex<0)
{
firstIndex = 0;
}
else if (firstIndex + _extentInfo.VirtualCount >= _extentInfo.TotalCount)
{
firstIndex = _extentInfo.TotalCount - _extentInfo.VirtualCount;
}
if (firstIndex == _firstIndex) return;
if (_firstIndex == firstIndex) return;
_firstIndex = firstIndex;
OnOffsetChanged(lines > 0 ? ScrollDirection.Down : ScrollDirection.Up, lines);
ReportChanges();
}
private void ReportChanges()
{
ScrollReceiver?.ScrollBoundsChanged(new ScrollBoundsArgs(_size, _firstIndex));
}
private void OnOffsetChanged(ScrollDirection direction,int firstRow)
{
ScrollReceiver?.ScrollChanged(new ScrollChangedArgs(direction, firstRow));
}
private void <API key>(int index)
{
if (_firstIndex == index) return;
_firstIndex = index;
ReportChanges();
}
private void InvokeSizeCommand(int size)
{
if (_size == size) return;
_size = size;
ReportChanges();
}
public bool CanVerticallyScroll {get;set;}
public bool <API key> {get;set;}
public double ExtentWidth => _extentSize.Width;
public double ExtentHeight => _extentSize.Height;
public double ViewportWidth => _viewportSize.Width;
public double ViewportHeight => _viewportSize.Height;
public double HorizontalOffset => _offset.X;
public double VerticalOffset => _offset.Y + _extentInfo.VerticalOffset;
public ScrollViewer ScrollOwner {get;set;}
public void LineUp()
{
// <API key>(-1);
}
public void LineDown()
{
// <API key>(1);
}
public void LineLeft()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount);
}
public void LineRight()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount);
}
public void PageUp()
{
SetVerticalOffset(VerticalOffset - ViewportHeight);
}
public void PageDown()
{
SetVerticalOffset(VerticalOffset + ViewportHeight);
}
public void PageLeft()
{
SetHorizontalOffset(HorizontalOffset + ItemWidth);
}
public void PageRight()
{
SetHorizontalOffset(HorizontalOffset - ItemWidth);
}
public void MouseWheelUp()
{
<API key>(-SystemParameters.WheelScrollLines);
}
public void MouseWheelDown()
{
<API key>(SystemParameters.WheelScrollLines);
}
public void MouseWheelLeft()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelRight()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public Rect MakeVisible(Visual visual, Rect rectangle)
{
return new Rect();
}
private class ItemLayoutInfo
{
public int <API key>;
public double <API key>;
public double <API key>;
public int <API key>;
}
private class ExtentInfo
{
public int TotalCount;
public int VirtualCount;
public double VerticalOffset;
public double MaxVerticalOffset;
public double Height;
}
}
} |
#ifndef BACKLIGHT_H_
#define BACKLIGHT_H_
#include <stdint.h>
class Backlight
{
public:
void init();
void setValuePercent(uint8_t value);
};
#endif /* BACKLIGHT_H_ */ |
from django.contrib.auth.models import Group, User
from django.db import models
from django.utils.translation import gettext_lazy as _
class GroupContact(models.Model):
"""
Groups displayed in contact page and their informations.
"""
class Meta:
verbose_name = _("Groupe de la page de contact")
verbose_name_plural = _("Groupes de la page de contact")
group = models.OneToOneField(Group, verbose_name=_("Groupe d'utilisateur"), on_delete=models.CASCADE)
name = models.CharField(_("Nom (ex: Le staff)"), max_length=32, unique=True)
description = models.TextField(_("Description (en markdown)"), blank=True, null=True)
email = models.EmailField(_("Adresse mail du groupe"), blank=True, null=True)
persons_in_charge = models.ManyToManyField(User, verbose_name=_("Responsables"), blank=True)
position = models.<API key>(_("Position dans la page"), unique=True)
def __str__(self):
return self.name |
div.balance {
color: #65B33C;
font-size: 18px;
}
div.balance div.price {
display: inline;
color: #C74530;
padding-left: 10px;
}
/* table part */
tr.sub td.amount {
color: red;
}
tr.add td.amount {
color: green;
}
tr.status-1 {
color: blue;
}
tr.status-3 td, tr.status-4 td,tr.status-5 td,tr.status-6 td {
background-color: #FF8E8E;
color: white;
}
td.date {
min-width:70px;
} |
Game.Tile = function (properties) {
this._litGlyph = properties.litGlyph || Game.Glyph.Null;
this._darkGlyph = properties.darkGlyph || Game.Glyph.Null;
this._blocked = properties.blocked || false;
if (properties.blockSight === false) {
this._blockSight = false;
} else {
this._blockSight = properties.blockSight || this._blocked;
}
}
Game.Tile.prototype.isBlocked = function () {
return this._blocked;
}
Game.Tile.prototype.blockSight = function () {
return this._blockSight;
}
Game.Tile.Null = new Game.Tile({})
Game.Tile.Floor = new Game.Tile({
litGlyph: Game.Glyph.LitFloor,
darkGlyph: Game.Glyph.DarkFloor,
blocked: false
})
Game.Tile.Wall = new Game.Tile({
litGlyph: Game.Glyph.LitWall,
darkGlyph: Game.Glyph.DarkWall,
blocked: true,
blockSight: true
})
Game.Tile.Water = new Game.Tile({
litGlyph: Game.Glyph.LitWater,
darkGlyph: Game.Glyph.DarkWater,
blocked: true,
blockSight: false
})
Game.Tile.UpStair = new Game.Tile({
litGlyph: Game.Glyph.LitUpStair,
darkGlyph: Game.Glyph.DarkUpStair,
blocked: false,
blockSight: false
})
Game.Tile.DownStair = new Game.Tile({
litGlyph: Game.Glyph.LitDownStair,
darkGlyph: Game.Glyph.DarkDownStair,
blocked: false,
blockSight: false
})
Game.Tile.Bridge = new Game.Tile({
litGlyph: Game.Glyph.LitBridge,
darkGlyph: Game.Glyph.DarkBridge,
blocked: false,
blockSight: false
})
Game.Tile.Mud = new Game.Tile({
litGlyph: Game.Glyph.LitMud,
darkGlyph: Game.Glyph.DarkMud,
blocked: false,
blockSight: false
})
Game.Tile.SwampGrass = new Game.Tile({
litGlyph: Game.Glyph.LitSwampGrass,
darkGlyph: Game.Glyph.DarkSwampGrass,
blocked: false,
blockSight: false
})
Game.Tile.SwampWater = new Game.Tile({
litGlyph: Game.Glyph.LitSwampWater,
darkGlyph: Game.Glyph.DarkSwampWater,
blocked: true,
blockSight: false
})
Game.Tile.Marker = new Game.Tile({
litGlyph: Game.Glyph.Marker,
darkGlyph: Game.Glyph.Marker,
blocked: false,
blockSight: false
})
Game.Map = function (width, height) {
this._width = width;
this._height = height;
this._tiles = {};
var tiles = this._tiles;
this.foreachTile(function(t, x, y) {
tiles[x+','+y] = { tile: Game.Tile.Floor,
seen: false };
});
var gen = new Game.Generator(width, height);
gen.compute(function (x, y, t) {
tiles[x+','+y].tile = t;
}, Game.addEntity);
this._upStair = gen._entrance;
}
Game.Map.prototype.foreachTile = function (cb) {
for (var y = 0; y < this._height; y++) {
for (var x = y % 2; x < this._width; x+=2) {
cb(this._tiles[x+','+y], x, y);
}
}
}
Game.Map.prototype.render = function (ctx, player) {
this.foreachTile(function(t, x, y) {
t.lit = false;
if (t.seen) {
t.tile._darkGlyph.draw(ctx, x, y);
}
});
var tiles = this._tiles;
var lightPasses = function (x, y) {
var idx = x+','+y;
return (idx in tiles) && !tiles[idx].tile.blockSight();
}
var fov = new ROT.FOV.<API key>(lightPasses, {topology: 6});
fov.compute(player._x, player._y, 160, function(x, y) {
var idx = x+','+y;
if (idx in tiles) {
tiles[idx].tile._litGlyph.draw(ctx, x, y);
tiles[idx].lit = true;
tiles[idx].seen = true;
}
});
}
Game.Map.prototype.setTile = function (x, y, tile) {
this._tiles[x+','+y].tile = tile;
}
Game.Map.NullTile = {
tile: Game.Tile.Null,
}
Game.Map.prototype.getTile = function (x, y) {
var ix = x+','+y;
if (ix in this._tiles) {
return this._tiles[ix];
} else {
return Game.Map.NullTile;
}
} |
var express = require('express'),
env = require('process').env,
config = require(env.CONFIG_PATH)
var app = express()
app.use(require('body-parser').json())
app.use(require('cookie-parser')())
app.use(`${config.http.root}/`,
express.static(`${__dirname}/../public`, {
index: ['index.html'],
})
)
app.use(`${config.http.root}/api/v1`, require('./api/auth'))
app.use(`${config.http.root}/api/v1/host`, require('./api/host'))
app.use(`${config.http.root}/api/v1/service`, require('./api/service'))
app.use(`${config.http.root}/api/v1/status`, require('./api/status'))
app.use(`${config.http.root}/api/v1/metrics`, require('./api/metrics'))
app.get(`${config.http.root}/rss/:secret`, require('./api/rss'))
app.listen(config.http.port, config.http.addr) |
package org.deidentifier.arx.cli.model;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.deidentifier.arx.cli.ParseUtil;
/**
* The model for distinct l-diversity.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class DistinctLDiversity extends Criterion {
/**
* Parses the given criterion string and returns the model.
*
* @param criterion the criterion
* @return the criterion
* @throws ParseException the parse exception
*/
public static Criterion parse(String criterion) throws ParseException {
return parse(null, criterion, 'X');
}
/**
* Parses the given criterion string and returns the model.
*
* @param criterion the criterion
* @param seperatorKeyValue the seperator key value
* @return the criterion
* @throws ParseException the parse exception
*/
public static Criterion parse(String criterion, char seperatorKeyValue) throws ParseException {
String[] split = ParseUtil.<API key>(criterion, seperatorKeyValue);
if (split.length != 2) {
throw new ParseException("Failed to parse [" + criterion + "] - Syntax: attributeName=criterionDefinition.", 1);
}
String key = split[0];
String value = split[1];
return parse(key, value, seperatorKeyValue);
}
/**
* Parses the given criterion string and returns the model.
*
* @param attribute the attribute
* @param criterion the criterion
* @param seperatorKeyValue the seperator key value
* @return the criterion
*/
private static Criterion parse(String attribute, String criterion, char seperatorKeyValue) {
matcher = pattern.matcher(criterion);
if (matcher.find()) {
final int l = Integer.parseInt(matcher.group(1));
return new DistinctLDiversity(attribute, l, seperatorKeyValue);
} else {
return null;
}
}
/** The Constant name. */
private static final String name;
/** The Constant prefix. */
private static final String prefix;
/** The Constant regex. */
private static final String regex;
/** The Constant pattern. */
private static final Pattern pattern;
/** The matcher. */
private static Matcher matcher;
static {
name = "-DIVERSITY";
prefix = "DISTINCT-";
regex = prefix + "\\((.*?)\\)" + name;
pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
}
/** The l. */
private final int l;
/** The seperator key value. */
private final char seperatorKeyValue;
/** The attribute. */
private final String attribute;
/**
* Instantiates a new distinct l diversity.
*
* @param attribute the attribute
* @param l the l
* @param seperatorKeyValue the seperator key value
*/
public DistinctLDiversity(String attribute, int l, char seperatorKeyValue) {
this.attribute = attribute;
this.l = l;
this.seperatorKeyValue = seperatorKeyValue;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DistinctLDiversity other = (DistinctLDiversity) obj;
if (attribute == null) {
if (other.attribute != null) {
return false;
}
} else if (!attribute.equals(other.attribute)) {
return false;
}
if (l != other.l) {
return false;
}
return true;
}
/**
* Gets the attribute.
*
* @return the attribute
*/
public String getAttribute() {
return attribute;
}
/**
* Gets the l.
*
* @return the l
*/
public int getL() {
return l;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((attribute == null) ? 0 : attribute.hashCode());
result = (prime * result) + l;
return result;
}
/* (non-Javadoc)
* @see org.deidentifier.arx.cli.model.Criterion#toString()
*/
@Override
public String toString() {
return (attribute == null ? "" : attribute + seperatorKeyValue) + prefix + "(" + l + ")" + name;
}
} |
#include <libDruid/SerialDruid.h>
#include "MainWindow.h"
#include "App.h"
#include "Config.h"
namespace DRUID {
#ifdef PLATFORM_LINUX
#define DEF_WIN_WIDTH 750
#define DEF_WIN_HEIGHT 565
#else
#define DEF_WIN_WIDTH 770
#define DEF_WIN_HEIGHT 630
#endif
bool App::OnInit()
{
srand(time(0));
MainWindow *frame = new MainWindow(_T(<API key>), wxPoint(100, 75), wxSize(DEF_WIN_WIDTH, DEF_WIN_HEIGHT) );
frame->Show( true );
SetTopWindow( frame );
return true;
}
} /* namespace DRUID */ |
#include "../ulixlib.h"
int main () {
printf ("Press Return to end.\n");
int f1 = fork (); // 2 procs
int f2 = fork (); // 4 procs
int f3 = fork (); // 8 procs
int f4 = fork (); // 16 procs
int f5 = fork (); // 32 procs
int f6 = fork (); // 64 procs
int pid = getpid ();
int ppid = getppid ();
int tid = gettid ();
printf ("[%2d]: pid = %2d, tid = %2d, ppid = %2d, "
"forkrets = [%2d %2d %2d %2d]\n",
pid, pid, tid, ppid, f1, f2, f3, f4);
if (f1!=0 && f2!=0 && f3!=0 && f4!=0) {
char s[80];
ureadline ((char*)s, 79, false);
}
long int j; for (j = 0; j < 9999999ul; j++);
exit (0);
} |
#ifndef TOKEN_H
#define TOKEN_H
string_t* token_next(char **str);
string_t* token_getlabel(string_t *str);
int token_islabel(string_t *str);
int token_iscomment(string_t *str);
int token_isreg(string_t *str);
int token_mnem2op(string_t *str);
int token_getnum(string_t *str);
int token_getreg(string_t *str);
int token_iswhitespace(string_t *str);
#endif |
var reaction_8hpp =
[
[ "reaction_struct", "<API key>.html", "<API key>" ],
[ "integrate_reaction", "reaction_8hpp.html#<API key>", null ],
[ "<API key>", "reaction_8hpp.html#<API key>", null ],
[ "<API key>", "reaction_8hpp.html#<API key>", null ],
[ "reaction", "reaction_8hpp.html#<API key>", null ]
]; |
<?php
/**
* @see Zend_Exception
*/
require_once 'Zend/Exception.php';
class <API key> extends Zend_Exception
{
} |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wizard', '<API key>'),
]
operations = [
migrations.AddField(
model_name='globals',
name='MEAL',
field=models.IntegerField(default=500),
preserve_default=True,
),
migrations.AddField(
model_name='meattype',
name='is_gemalen',
field=models.BooleanField(default=False),
preserve_default=True,
),
migrations.AlterField(
model_name='globals',
name='REPEATS',
field=models.IntegerField(default=150),
preserve_default=True,
),
migrations.AlterField(
model_name='globals',
name='tries',
field=models.IntegerField(default=20),
preserve_default=True,
),
] |
#ifndef __prisoner_hh
#define __prisoner_hh
#include<ostream> // for std::ostream
class Prisoner {
public:
virtual void init(int imynum,int iprisnum)=0;
virtual void nullit()=0;
virtual bool wantToEnd()=0;
virtual bool doYourThing(bool)=0;
virtual void output(std::ostream& out) const=0;
};
#endif // __prisoner_hh |
package net.sf.jasperreports.charts.design;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import net.sf.jasperreports.charts.JRDataRange;
import net.sf.jasperreports.charts.JRValueDisplay;
import net.sf.jasperreports.charts.base.JRBaseMeterPlot;
import net.sf.jasperreports.charts.base.JRBaseValueDisplay;
import net.sf.jasperreports.charts.type.MeterShapeEnum;
import net.sf.jasperreports.charts.util.JRMeterInterval;
import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.JRChartPlot;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRFont;
/**
* A meter plot that displays a single value against a range of values. The
* range can be further subdivided into multiple color coded regions.
*
* @author Barry Klawans (bklawans@users.sourceforge.net)
*/
public class JRDesignMeterPlot extends JRBaseMeterPlot
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
public static final String PROPERTY_DATA_RANGE = "dataRange";
public static final String <API key> = "meterAngle";
public static final String <API key> = "<API key>";
public static final String <API key> = "needleColor";
public static final String PROPERTY_SHAPE = "shape";
public static final String PROPERTY_TICK_COLOR = "tickColor";
public static final String PROPERTY_TICK_COUNT = "tickCount";
public static final String <API key> = "tickInterval";
public static final String PROPERTY_UNITS = "units";
public static final String <API key> = "valueDisplay";
public static final String PROPERTY_INTERVALS = "intervals";
public static final String <API key> = "tickLabelFont";
/**
* Construct a new meter plot by copying an existing one.
*
* @param plot the plot to copy
*/
public JRDesignMeterPlot(JRChartPlot plot, JRChart chart)
{
super(plot, chart);
}
/**
* Sets the range of values that the meter can display. Before changing
* this for an existing meter you should clear any existing intervals to
* ensure that you don't end up with intervals that are outside of the new
* range.
*
* @param dataRange the range of values that the meter can display
*/
public void setDataRange(JRDataRange dataRange) throws JRException
{
Object old = this.dataRange;
this.dataRange = dataRange;
getEventSupport().firePropertyChange(PROPERTY_DATA_RANGE, old, this.dataRange);
}
/**
* Sets the value display formatting options.
*
* @param valueDisplay how to show the textual representation of the value
*/
public void setValueDisplay(JRValueDisplay valueDisplay)
{
Object old = this.valueDisplay;
this.valueDisplay = new JRBaseValueDisplay(valueDisplay, getChart());
getEventSupport().firePropertyChange(<API key>, old, this.valueDisplay);
}
/**
* Sets the shape of the meter.
*
* @param shape the shape of the meter
* @throws JRException invalid shape was specified
*/
public void setShape(MeterShapeEnum shape) throws JRException
{
MeterShapeEnum old = this.shapeValue;
this.shapeValue = shape;
getEventSupport().firePropertyChange(PROPERTY_SHAPE, old, this.shapeValue);
}
/**
* Adds an interval to the meter. An interval is used to indicate a
* section of the meter.
*
* @param interval the interval to add to the meter
*/
public void addInterval(JRMeterInterval interval)
{
intervals.add(interval);
getEventSupport().<API key>(PROPERTY_INTERVALS, interval, intervals.size() - 1);
}
/**
* Removes all the intervals for the meter.
*/
public void clearIntervals()
{
setIntervals(null);
}
/**
* Sets the meter intervals.
*
* @param intervals the list of meter intervals ({@link JRMeterInterval} instances)
* @see #addInterval(JRMeterInterval)
*/
public void setIntervals(Collection<JRMeterInterval> intervals)
{
Object old = new ArrayList<JRMeterInterval>(this.intervals);
this.intervals.clear();
if (intervals != null)
{
this.intervals.addAll(intervals);
}
getEventSupport().firePropertyChange(PROPERTY_INTERVALS, old, this.intervals);
}
/**
* Sets the size of the meter face in degrees.
*
* @param meterAngle the size of the meter in degrees
*/
public void setMeterAngle(Integer meterAngle)
{
Integer old = this.meterAngleInteger;
this.meterAngleInteger = meterAngle;
getEventSupport().firePropertyChange(<API key>, old, this.meterAngleInteger);
}
/**
* Sets the units string to use. This string is appended to the value
* when it is displayed.
*
* @param units the units string to use
*/
public void setUnits(String units)
{
Object old = this.units;
this.units = units;
getEventSupport().firePropertyChange(PROPERTY_UNITS, old, this.units);
}
/**
* Sets the space between tick marks on the face of the meter. The
* spacing is relative to the range of the meter. If the meter is
* displaying the range 100 to 200 and the tick interval is 20, four
* tick marks will be shown, one each at 120, 140, 160 and 180.
*
* @param tickInterval the space between tick marks on the meter
*/
public void setTickInterval(Double tickInterval)
{
Double old = this.tickIntervalDouble;
this.tickIntervalDouble = tickInterval;
getEventSupport().firePropertyChange(<API key>, old, this.tickIntervalDouble);
}
/**
* Sets the color to use for the meter face.
*
* @param <API key> the color to use for the meter face
*/
public void <API key>(Color <API key>)
{
Object old = this.<API key>;
this.<API key> = <API key>;
getEventSupport().firePropertyChange(<API key>, old, this.<API key>);
}
/**
* Sets the color to use for the meter pointer.
*
* @param needleColor the color to use for the meter pointer
*/
public void setNeedleColor(Color needleColor)
{
Object old = this.needleColor;
this.needleColor = needleColor;
getEventSupport().firePropertyChange(<API key>, old, this.needleColor);
}
/**
* Sets the color to use when drawing tick marks on the meter.
*
* @param tickColor the color to use when drawing tick marks
*/
public void setTickColor(Color tickColor)
{
Object old = this.tickColor;
this.tickColor = tickColor;
getEventSupport().firePropertyChange(PROPERTY_TICK_COLOR, old, this.tickColor);
}
/**
* Sets the number of major tick marks on the meter scale.
*
* @param tickCount the number of major tick marks
*/
public void setTickCount(Integer tickCount)
{
Object old = this.tickCount;
this.tickCount = tickCount;
getEventSupport().firePropertyChange(PROPERTY_TICK_COUNT, old, this.tickCount);
}
/**
* Sets the font to use when displaying the tick label.
*
* @param tickLabelFont the font to use when displaying the tick label
*/
public void setTickLabelFont(JRFont tickLabelFont)
{
Object old = this.tickLabelFont;
this.tickLabelFont = tickLabelFont;
getEventSupport().firePropertyChange(<API key>, old, this.tickLabelFont);
}
} |
// written by : Doug Reuter
// SPI2C is a libarary that combines both SPI calls and I2C calls into
// like methods so sensors that use both protocols can be used with minimum modfication
// may work on other arduino boards as well
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// SPI32.h
#ifndef _SPI32_h
#define _SPI32_h
#include "arduino.h"
#include <SPI.h>
#include "SPI2C.h"
class SPI32 : public SPI2C
{
protected:
public:
bool spEnabled;
// Inherited via SPI2C
SPISettings spiSettings;
SPIClass * spiP;
//void config(SPISettings &setting);
SPI32();
SPI32(SPIClass * s);
virtual void write( byte data) override;
virtual void write( byte address, byte data) override;
virtual void write( byte address, byte * data, int length) override;
virtual void write16( byte address, int16_t* data) override;
virtual void writeBit( byte adress, byte bitNum, bool val) override;
virtual byte read( byte address) override;
virtual void read( byte address, byte * buffer, int length) override;
virtual int16_t read16( byte address) override;
virtual uint8_t readBit( byte address, byte bitNum) override;
virtual int8_t readBits(uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data) override;
virtual void setSPI2CConfig(SPI2C_config * con) override;
virtual void writeBits( uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) override;
virtual void init() override;
};
#endif |
package testblas
import (
"testing"
"gonum.org/v1/gonum/blas"
)
type Dgbmver interface {
Dgbmv(tA blas.Transpose, m, n, kL, kU int, alpha float64, a []float64, lda int, x []float64, incX int, beta float64, y []float64, incY int)
}
func DgbmvTest(t *testing.T, blasser Dgbmver) {
for i, test := range []struct {
tA blas.Transpose
m, n int
kL, kU int
alpha float64
a [][]float64
lda int
x []float64
beta float64
y []float64
ans []float64
}{
{
tA: blas.NoTrans,
m: 9,
n: 6,
lda: 4,
kL: 2,
kU: 1,
alpha: 3.0,
beta: 2.0,
a: [][]float64{
{5, 3, 0, 0, 0, 0},
{-1, 2, 9, 0, 0, 0},
{4, 8, 3, 6, 0, 0},
{0, -1, 8, 2, 1, 0},
{0, 0, 9, 9, 9, 5},
{0, 0, 0, 2, -3, 2},
{0, 0, 0, 0, 1, 5},
{0, 0, 0, 0, 0, 6},
},
x: []float64{1, 2, 3, 4, 5, 6},
y: []float64{-1, -2, -3, -4, -5, -6, -7, -8, -9},
ans: []float64{31, 86, 153, 97, 404, 3, 91, 92, -18},
},
{
tA: blas.Trans,
m: 9,
n: 6,
lda: 4,
kL: 2,
kU: 1,
alpha: 3.0,
beta: 2.0,
a: [][]float64{
{5, 3, 0, 0, 0, 0},
{-1, 2, 9, 0, 0, 0},
{4, 8, 3, 6, 0, 0},
{0, -1, 8, 2, 1, 0},
{0, 0, 9, 9, 9, 5},
{0, 0, 0, 2, -3, 2},
{0, 0, 0, 0, 1, 5},
{0, 0, 0, 0, 0, 6},
},
x: []float64{1, 2, 3, 4, 5, 6, 7, 8, 9},
y: []float64{-1, -2, -3, -4, -5, -6},
ans: []float64{43, 77, 306, 241, 104, 348},
},
{
tA: blas.NoTrans,
m: 6,
n: 3,
lda: 1,
kL: 0,
kU: 0,
alpha: 2.0,
beta: 1.0,
a: [][]float64{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
},
x: []float64{1, 2, 3},
y: []float64{-1, -2, -3, -4, -5, -6},
ans: []float64{1, 2, 3, -4, -5, -6},
},
{
tA: blas.Trans,
m: 6,
n: 3,
lda: 1,
kL: 0,
kU: 0,
alpha: 2.0,
beta: 1.0,
a: [][]float64{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
{0, 0, 0},
{0, 0, 0},
{0, 0, 0},
},
x: []float64{1, 2, 3, 4, 5, 6},
y: []float64{-1, -2, -3},
ans: []float64{1, 2, 3},
},
} {
extra := 3
aFlat := flattenBanded(test.a, test.kU, test.kL)
incTest := func(incX, incY, extra int) {
xnew := makeIncremented(test.x, incX, extra)
ynew := makeIncremented(test.y, incY, extra)
ans := makeIncremented(test.ans, incY, extra)
blasser.Dgbmv(test.tA, test.m, test.n, test.kL, test.kU, test.alpha, aFlat, test.lda, xnew, incX, test.beta, ynew, incY)
if !dSliceTolEqual(ans, ynew) {
t.Errorf("Case %v: Want %v, got %v", i, ans, ynew)
}
}
incTest(1, 1, extra)
incTest(1, 3, extra)
incTest(1, -3, extra)
incTest(2, 3, extra)
incTest(2, -3, extra)
incTest(3, 2, extra)
incTest(-3, 2, extra)
}
} |
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Sys_Exportso extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model("Tpo_model", "so");
}
public function index() {
$so = $this->so->get_so();
$aout[0][0] = "Orden de gobierno";
$aout[0][1] = "Estado";
$aout[0][2] = "Tipo de sujeto obligado";
$aout[0][3] = "Nombre del sujeto obligado";
$aout[0][4] = "URL del portal";
$aout[0][5] = "Función";
$aout[0][6] = "Estatus del sujeto obligado";
$aout[0][7] = "Nombre del servidor público";
$aout[0][8] = "Cargo";
$aout[0][9] = "Correo electrónico";
$aout[0][10] = "Teléfono";
$aout[0][11] = "Estatus del servidor público";
$j = 1;
foreach ($so as $campos) {
$i = 0;
$outdetalle= array ();
foreach ($campos as &$campo) {
$campo = str_replace("'", "", $campo);
$campo = str_replace('"', "", $campo);
$campo = str_replace(',', "", $campo);
$campo = str_replace(';', "", $campo);
$aout[$j][$i] = $campo;
$i=$i+1;
}
$j=$j+1;
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=sujetos_obligados.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo generateCsvD3D( $aout );
}
}
?> |
import config
#This module is used for calling the Wolfram Alpha API
#It defines a function that constructs an URL based on the query.
#NOTE: This module returns only the URL. This URL is passed in the bot.py file. Telegram Takes care of the rest.
def query(query):
question = query.replace(" ","+") #plus encoding
return "http://api.wolframalpha.com/v1/simple?appid={}&i=".format(config.WOLFRAM) + question + "&format=image"
#returns ONLY the URL directly.
#Telegram's servers handle the requests by themselves for docs lesser than 20MB |
# Import Public Furniture listing into local database from CSV
import sys
sys.path.append('..')
from settings import *
import psycopg2
import psycopg2.extensions
import csv
class Point(object):
def __init__(self, dataString):
#clip out parenthesis, and split over comma
data = dataString[1:-1].split(', ')
self.longitude = float(data[1])
#input is in standard order (lat,long)
self.latitude = float(data[0])
def adapt_point(point):
#store in sql order (long,lat)
return psycopg2.extensions.AsIs("'(%s, %s)'" % (psycopg2.extensions.adapt(point.longitude), psycopg2.extensions.adapt(point.latitude)))
psycopg2.extensions.register_adapter(Point, adapt_point)
db_conn = psycopg2.connect(host=DB_HOST, database=DB_DATABASE,
user=DB_USER, password=DB_PASSWORD, port=DB_PORT)
db_cur = db_conn.cursor()
with open("../data/<API key>.csv") as csvfile:
reader = csv.reader(csvfile)
#skip column labels line
reader.next()
for entry in reader:
db_cur.execute("INSERT INTO pois (location, type) VALUES (%s, %s) RETURNING id",
(Point(entry[4]), 'furniture'))
newid = db_cur.fetchone()[0]
db_cur.execute("INSERT INTO furniture (id, asset_id, feature_type, division_name, location_name, location) VALUES (%s, %s, %s, %s, %s, %s)",
(newid, entry[0], entry[1], entry[2], entry[3], Point(entry[4])))
db_conn.commit()
db_cur.close()
db_conn.close() |
#!BPY
# -*- coding: utf-8 -*-
"""
Name: 'Glome Mesh Exporter'
Blender: 259
Group: 'Export'
Tooltip: 'Export meshes to Binary file format for Glome Game Renega Desruga'
"""
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# FILE FORMAT:
# (The header elements - unsigned integer(I) (4 bytes))
# (The amount of items - unsigned short(H) (2 bytes))
# (< list > represents a list of values (coordenates) - float(f) (4 bytes))
#[BEGIN]
# # HEADER #
# mesh guns engines (uint ea)
# # BODY #
# nvertices (ushort)
# nvertices lines contaning vertex coordenates and colors attributes: <x, y, z, w> <r, g, b, a> (8*float ea)
# nedges (ushort)
# nedges lines contaning 2 vertex index: <v_in0 , v_in1> (2*ushort ea)
# nguns (ushort)
# nguns * <guns Matrix4d positions> (16*float ea)
# nengines (ushort)
# nengines * <engines Matrix4d positions> (16*float ea)
#[END]
try:
import bpy
from bpy import *
import mathutils
except ImportError:
sys.exit('Only works from within Blender!\n')
import os
import re
import struct
from struct import calcsize
import math
from math import *
fsize = struct.calcsize('f')
usize = struct.calcsize('H')
isize = struct.calcsize('I')
# Object scale
scale = 0.0005
gscale = 0.001
# Math Utils #
def xw_matrix(angle):
c = cos(angle)
s = sin(angle)
return mathutils.Matrix(((c, 0, 0, -s),
(0, 1, 0, 0),
(0, 0, 1, 0),
(s, 0, 0, c)))
def yw_matrix(angle):
c = cos(angle)
s = sin(angle)
return mathutils.Matrix(((1, 0, 0, 0),
(0, c, 0, -s),
(0, 0, 1, 0),
(0, s, 0, c)))
def zw_matrix(angle):
c = cos(angle)
s = sin(angle)
return mathutils.Matrix(((1, 0, 0, 0),
(0, 1, 0, 0),
(0, 0, c, -s),
(0, 0, s, c)))
def matrix_gen(v):
return xw_matrix(v[0] * gscale) * yw_matrix(v[2] * gscale) * zw_matrix(v[1] * gscale)
def write_matrix(mat, bfile):
if(bpy.app.version >= (2,62,0)):
row_len = len(mat.row)
col_len = len(mat.col)
else:
row_len = mat.row_size
col_len = mat.col_size
for i in range(0, row_len):
for j in range(0, col_len):
# t[col][row] because this is how OpenGL represents matrices
bfile.write(struct.pack('<f', mat[j][i]))
# Objects #
class SpaceShip:
def __init__(self, objs, listAllScenes):
self.data = objs.get(ssname).to_mesh(listAllScenes.get('mesh'),True,'PREVIEW')
self.ssMesh = Mesh(self.data)
#TODO: work for n guns and engines
self.lguns = listAllScenes.get('gun').objects.values()
self.ssGuns = Guns(objs.get(ssname),self.lguns)
self.lengines = listAllScenes.get('engine').objects.values()
self.ssEngines = Engines(objs.get(ssname),self.lengines)
def export(self):
self.ssMesh.export()
self.ssGuns.export()
self.ssEngines.export()
def create_header(self):
# calc initial positions
self.mesh_pos = header_size = 3 * isize
mesh_size = (len(self.data.vertices) * 7 * fsize) + (len(self.data.edges) * 2 * usize) + (2 * usize)
self.gun_pos = header_size + mesh_size
gun_size = (len(self.lguns) * 16 * fsize) + usize
self.engine_pos = header_size + mesh_size + gun_size
engine_size = (len(self.lengines) * 16 * fsize) + usize
# write header
bfile.write(struct.pack('<I', self.mesh_pos))
bfile.write(struct.pack('<I', self.gun_pos))
bfile.write(struct.pack('<I', self.engine_pos))
def read(self):
bfile = open(filename, 'rb')
print('Reading mesh of ' + ssname)
print('
m = bfile.read(isize)
g = bfile.read(isize)
e = bfile.read(isize)
print('Mesh position: ' + str(struct.unpack('<I', m)[0]) + ' Gun position: ' + str(struct.unpack('<I', g)[0]) + ' Engine position: ' + str(struct.unpack('<I', e)[0]))
print('
nv = bfile.read(usize)
print(struct.unpack('<H', nv)[0])
for v in self.data.vertices:
x = bfile.read(fsize)
y = bfile.read(fsize)
z = bfile.read(fsize)
# w = bfile.read(fsize)
r = bfile.read(fsize)
g = bfile.read(fsize)
b = bfile.read(fsize)
a = bfile.read(fsize)
# print(struct.unpack('<f', x)[0], struct.unpack('<f', y)[0], struct.unpack('<f', z)[0], struct.unpack('<f', w)[0], struct.unpack('<f', r)[0], struct.unpack('<f', g)[0], struct.unpack('<f', b)[0], struct.unpack('<f', a)[0])
print(struct.unpack('<f', x)[0], struct.unpack('<f', y)[0], struct.unpack('<f', z)[0], struct.unpack('<f', r)[0], struct.unpack('<f', g)[0], struct.unpack('<f', b)[0], struct.unpack('<f', a)[0])
ne = bfile.read(usize)
print(struct.unpack('<H', ne)[0])
for e in self.data.edges:
e0 = bfile.read(usize)
e1 = bfile.read(usize)
print(struct.unpack('<H', e0)[0], struct.unpack('<H', e1)[0])
print('Guns of ' + ssname + ':')
ng = bfile.read(usize)
print(struct.unpack('<H', ng)[0])
c = 1
for g in self.lguns:
print('gun' + str(c) + ':')
for i in range(0, 4):
for j in range(0, 4):
a = bfile.read(fsize)
print(struct.unpack('<f', a)[0])
c = c + 1
print('Engines of ' + ssname + ':')
ne = bfile.read(usize)
print(struct.unpack('<H', ne)[0])
c = 1
for e in self.lengines:
print('engine' + str(c) + ':')
for i in range(0, 4):
for j in range(0, 4):
a = bfile.read(fsize)
print(struct.unpack('<f', a)[0])
c = c + 1
bfile.close()
#Export SpaceShip coordenates
class Mesh:
def __init__(self, data):
self.data = data
# Material vertex colour data
#TODO: work for more than one material
self.diffuse_color = self.data.materials[0].diffuse_color
self.alpha = self.data.materials[0].alpha
#specular_color = self.data.materials[0].specular_color
def export(self):
bfile.write(struct.pack('<H', len(self.data.vertices)))
for v in self.data.vertices:
out = v.co * scale
bfile.write(struct.pack('<f', out[0]))
bfile.write(struct.pack('<f', out[1]))
bfile.write(struct.pack('<f', out[2]))
bfile.write(struct.pack('<f', self.diffuse_color[0]))
bfile.write(struct.pack('<f', self.diffuse_color[1]))
bfile.write(struct.pack('<f', self.diffuse_color[2]))
bfile.write(struct.pack('<f', self.alpha))
bfile.write(struct.pack('<H', len(self.data.edges)))
for e in self.data.edges.values():
bfile.write(struct.pack('<H', e.key[0]))
bfile.write(struct.pack('<H', e.key[1]))
#Export guns positions
class Guns:
def __init__(self, objMesh, lguns):
self.lguns = lguns
self.objMesh = objMesh
def export(self):
bfile.write(struct.pack('<H', len(self.lguns)))
for g in self.lguns:
t = matrix_gen(g.location - self.objMesh.location)
write_matrix(t, bfile)
#Export Engines positions
class Engines:
def __init__(self, objMesh, lengines):
self.lengines = lengines
self.objMesh = objMesh
def export(self):
bfile.write(struct.pack('<H', len(self.lengines)))
for e in self.lengines:
t = matrix_gen(e.location - self.objMesh.location)
write_matrix(t, bfile)
# Main #
bfile = None
ssname = ''
if __name__ == "__main__":
# objects in blender need be separeted per scenes
#FIXME: In scenes engine and gun, cameras and lamps objects should be deleted
listAllScenes = bpy.data.scenes
objs = bpy.data.objects
for o in objs:
if(o.type == 'MESH'):
filename = o.name + '.wire'
ssname = o.name
bfile = open(filename, 'wb')
#FIXME: spaceship name(ssname) is global
ss = SpaceShip(objs, listAllScenes)
ss.create_header()
ss.export()
bfile.close()
ss.read() |
var express = require('express');
var router = express.Router();
var ce = require('./commandExecutor');
var config = require('./config');
var winston = require('./log.js');
/* GET home page. */
router.get('/', function (req, res, next) {
winston.info("Rendering downloader main page");
res.render('index', {
title: 'UNICEF monitoring station',
moduleId: GLOBAL_CONFIG.moduleId,
serverTime: new Date().getTime()
});
});
/* GET closeSession. */
router.get('/closeSession', function (req, res, next) {
winston.info("closing session");
ce.shellExecutor(config.shellCommands.closeSession, function (error, stdout, stderr) {
if (!error) {
winston.info("closing session OK");
res.send('closeSession: ' + stdout);
} else {
winston.error("closing session ERROR\n" + error + "\n" + stdout + "\n" + stderr);
res.send('error ' + error);
}
});
});
var packagesPath = (process.env.MODULE_PACKAGES_DIR || "/tmp" );
/* GET downloadPackages. */
var serveIndex = require('serve-index');
router.use(express.static(__dirname + "/"));
router.use('/download', express.static(packagesPath));
router.use('/download', serveIndex(packagesPath, {
'icons': true,
'view': 'details',
template: __dirname + "/views/download.template.html"
}));
/* GET syncTime. */
router.get('/syncTime', function (req, res, next) {
ce.shellExecutor(config.shellCommands.syncTime + req.query.newTime,
function (error, stdout, stderr) {
if (!error) {
winston.info("Time synchronized\n" + stdout, req.query);
res.send('Time synchronized.');
} else {
winston.error("error time sync " + error + stderr + stdout);
res.send('error ' + error);
}
});
});
/* GET syncTime. */
router.get('/execute', function (req, res, next) {
ce.shellExecutor(req.query.command,
function (error, stdout, stderr) {
if (error) {
winston.error("Error when executing command " + req.query.command + "\n" + error + stdout + stderr);
}
winston.info("Command executed successfully " + req.query.command + "\n" + stdout);
res.send({stdout: stdout, stderr: stderr, error: error});
});
});
/* GET hardwareStatus. */
router.get('/status', function (req, res, next) {
winston.info("hardware status page");
res.render('hardwareStatus', {
title: 'UNICEF monitoring station - hardwareStatus',
camera: "N/A",
voltage: "N/A",
storage: "N/A",
motion: "N/A",
touch: "N/A"
});
});
module.exports = router; |
package org.ju2ender.x.types;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* JodaTime
*/
public final class DateTimeUtil
{
private static final String <API key> = "yyyy-MM-dd'T'HH:mm:ss";
private static final String <API key> = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZ";
private static final String <API key> = "<API key>";
private static DateTimeFormatter <API key> = DateTimeFormat.forPattern(<API key>);
private static DateTimeFormatter <API key> = DateTimeFormat.forPattern(<API key>);
private static DateTimeFormatter <API key> = DateTimeFormat.forPattern(<API key>);
public static DateTime fromDateTime(String dateTimeStr)
{
return <API key>.parseDateTime(dateTimeStr);
}
public static DateTime fromDateTimeMillis(String dateTimeStr)
{
return <API key>.parseDateTime(dateTimeStr);
}
public static String getNow()
{
return <API key>.print(new DateTime());
}
public static String getTimestamp()
{
return <API key>.print(new DateTime());
}
} |
#!/usr/bin/python
__author__ = 'joaci'
try:
import time
from pyfase import MicroService
except Exception as e:
print('require module exception: %s' % e)
exit(0)
class Pong(MicroService):
def __init__(self):
super(Pong, self).__init__(self, sender_endpoint='ipc:///tmp/sender', receiver_endpoint='ipc:///tmp/receiver')
def on_connect(self):
print('
self.request_action('ping', {})
@MicroService.action
def pong(self, service, data):
print('
time.sleep(2)
self.request_action('ping', {})
Pong().execute() |
#ifndef MEAN_EIGEN_H_
#define MEAN_EIGEN_H_
#include <shogun/lib/config.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/mathematics/linalg/internal/implementation/Sum.h>
#include <shogun/mathematics/eigen3.h>
#include <numeric>
namespace shogun
{
namespace linalg
{
namespace implementation
{
/**
* @brief Generic class int2float which converts different types of integer
* into float64 type.
*/
template <typename inputType>
struct int2float
{
using floatType = inputType;
};
/**
* @brief Specialization of generic class int2float which converts int32 into float64.
*/
template <>
struct int2float<int32_t>
{
using floatType = float64_t;
};
/**
* @brief Specialization of generic class int2float which converts int64 into float64.
*/
template <>
struct int2float<int64_t>
{
using floatType = float64_t;
};
/**
* @brief Generic class mean which provides a static compute method.
*/
template <enum Backend, class Matrix>
struct mean
{
/** Scalar type */
typedef typename Matrix::Scalar T;
/** int2float type */
typedef typename int2float<T>::floatType ReturnType;
/**
* Method that computes the vector mean
*
* @param a vector whose mean has to be computed
* @return the vector mean \f$\bar a_i\f$
*/
static ReturnType compute(Matrix a);
/**
* Method that computes the matrix mean
*
* @param a matrix whose mean has to be computed
* @param no_diag if true, diagonal entries are excluded from the mean (default - false)
* @return the matrix mean \f$\1/N^2\sum_{i,j=1}^N m_{i,j}\f$
*/
static ReturnType compute(Matrix a, bool no_diag=false);
};
/**
* @brief Generic class rowwise_mean which provides a static compute method.
*/
template <enum Backend, class Matrix>
struct rowwise_mean
{
/** Scalar type */
typedef typename Matrix::Scalar T;
/** int2float type */
typedef typename int2float<T>::floatType ReturnDataType;
/**
* Method that computes the row wise sum of co-efficients of SGMatrix using Eigen3
*
* @param m the matrix whose rowwise sum of co-efficients has to be computed
* @param no_diag if true, diagonal entries are excluded from the sum
* @return the rowwise sum of co-efficients computed as \f$s_i=\sum_{j}m_{i,j}\f$
*/
static SGVector<ReturnDataType> compute(SGMatrix<T> m, bool no_diag);
/**
* Method that computes the row wise sum of co-efficients of SGMatrix using Eigen3
*
* @param m the matrix whose rowwise sum of co-efficients has to be computed
* @param no_diag if true, diagonal entries are excluded from the sum
* @param result Pre-allocated vector for the result of the computation
*/
static void compute(SGMatrix<T> mat, SGVector<ReturnDataType> result, bool no_diag);
};
/**
* @brief Specialization of generic mean which works with SGVector and
* SGMatrix and uses Eigen3 as backend for computing mean.
*/
template <class Matrix>
struct mean<Backend::EIGEN3, Matrix>
{
/** Scalar type */
typedef typename Matrix::Scalar T;
/** int2float type */
typedef typename int2float<T>::floatType ReturnType;
/**
* Method that computes the mean of SGVectors using Eigen3
*
* @param a vector whose mean has to be computed
* @return the vector mean \f\bar a_i\f$
*/
static ReturnType compute(SGVector<T> vec)
{
REQUIRE(vec.vlen > 0, "Vector cannot be empty!\n");
return (vector_sum<Backend::EIGEN3, SGVector<T> >::compute(vec)
/ ReturnType(vec.vlen));
}
/**
* Method that computes the mean of SGMatrix using Eigen3
*
* @param a matrix whose mean has to be computed
* @param no_diag if true, diagonal entries are excluded from the mean (default - false)
* @return the matrix mean \f$\1/N^2 \sum_{i,j=1}^N m_{i,j}\f$
*/
static ReturnType compute(SGMatrix<T> mat, bool no_diag=false)
{
REQUIRE(mat.num_rows > 0, "Matrix row number cannot be zero!\n");
if (no_diag)
{
if (mat.num_rows > mat.num_cols)
{
return (sum<Backend::EIGEN3, SGMatrix<T> >::compute(mat, no_diag)
/ ReturnType(mat.num_rows * mat.num_cols - mat.num_cols));
}
else
{
return (sum<Backend::EIGEN3, SGMatrix<T> >::compute(mat, no_diag)
/ ReturnType(mat.num_rows * mat.num_cols - mat.num_rows));
}
}
else
{
return (sum<Backend::EIGEN3, SGMatrix<T> >::compute(mat, no_diag)
/ ReturnType(mat.num_rows * mat.num_cols));
}
}
};
/**
* @brief Specialization of generic mean which works with SGMatrix
* and uses Eigen3 as backend for computing rowwise mean.
*/
template <class Matrix>
struct rowwise_mean<Backend::EIGEN3, Matrix>
{
/** Scalar type */
typedef typename Matrix::Scalar T;
/** int2float type */
typedef typename int2float<T>::floatType ReturnDataType;
/** Eigen matrix type */
typedef Eigen::Matrix<T,Eigen::Dynamic, Eigen::Dynamic> MatrixXt;
/**
* Method that computes the rowwise mean of SGMatrix using Eigen3
*
* @param m the matrix whose rowwise mean has to be computed
* @param no_diag if true, diagonal entries are excluded from the mean
* @return the rowwise mean computed as \f$\1/N \sum_{j=1}^N m_{i,j}\f$
*/
static SGVector<ReturnDataType> compute(SGMatrix<T> m, bool no_diag)
{
SGVector<ReturnDataType> result(m.num_rows);
compute(m, result, no_diag);
return result;
}
/**
* Method that computes the rowwise mean of SGMatrix using Eigen3
*
* @param m the matrix whose rowwise mean has to be computed
* @param no_diag if true, diagonal entries are excluded from the mean
* @param result Pre-allocated vector for the result of the computation
*/
static void compute(SGMatrix<T> mat, SGVector<ReturnDataType> result, bool no_diag)
{
REQUIRE(mat.num_cols > 0, "Matrix column number cannot be zero!\n");
Eigen::Map<MatrixXt> m = mat;
SGVector<T> temp(m.rows());
temp = rowwise_sum<Backend::EIGEN3, SGMatrix<T> >::compute(mat, no_diag);
if (!no_diag)
for (index_t i = 0; i < m.rows(); ++i)
result[i] = temp[i] / ReturnDataType(m.cols());
else if (m.rows() <= m.cols())
for (index_t i = 0; i < m.rows(); ++i)
result[i] = temp[i] / ReturnDataType(m.cols() - 1);
else
{
for (index_t i = 0; i < m.cols(); ++i)
result[i] = temp[i] / ReturnDataType(m.cols() - 1);
for (index_t i = m.cols(); i < m.rows(); ++i)
result[i] = temp[i] / ReturnDataType(m.cols());
}
}
};
}
}
}
#endif |
package org.thehellnet.shab.protocol.line;
import org.thehellnet.shab.protocol.exception.<API key>;
import org.thehellnet.shab.protocol.exception.ParseLineException;
import java.util.Locale;
public class ServerPingLine extends Line {
private static final Command COMMAND = Command.SERVER_PING;
public static final String COMMAND_TAG = "SP";
private long timestamp;
public ServerPingLine() {
super(COMMAND);
}
public ServerPingLine(String rawLine) throws <API key> {
super(COMMAND, rawLine);
}
@Override
protected String serializeLine() {
return String.format(Locale.US, "%s|%d", COMMAND_TAG, timestamp);
}
@Override
protected void parse(String[] items) throws <API key> {
if (!items[1].equals(COMMAND_TAG) || items.length != 3) {
throw new ParseLineException();
}
timestamp = Long.parseLong(items[2]);
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
} |
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.08.11 at 01:51:42 PM MSK
package org.smpte_ra.reg._395._2014._13._1.aaf;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.smpte_ra.reg._2003._2012.<API key>;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "<API key>")
public class <API key> {
@XmlElement(name = "StereoscopicEyeID", namespace = "http:
@XmlSchemaType(name = "anyURI")
protected String stereoscopicEyeID;
@XmlElement(name = "<API key>", namespace = "http:
@XmlSchemaType(name = "anyURI")
protected String <API key>;
@XmlElement(name = "InstanceID", namespace = "http:
@XmlSchemaType(name = "anyURI")
protected String instanceID;
@XmlElement(name = "ObjectClass", namespace = "http:
@XmlSchemaType(name = "anySimpleType")
protected String objectClass;
@XmlElement(name = "<API key>", namespace = "http:
protected <API key> <API key>;
@XmlElement(name = "LinkedGenerationID", namespace = "http:
@XmlSchemaType(name = "anyURI")
protected String linkedGenerationID;
@XmlAttribute(name = "path", namespace = "http://sandflow.com/ns/SMPTEST2001-1/baseline")
protected String path;
/**
* Gets the value of the stereoscopicEyeID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String <API key>() {
return stereoscopicEyeID;
}
/**
* Sets the value of the stereoscopicEyeID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.stereoscopicEyeID = value;
}
/**
* Gets the value of the <API key> property.
*
* @return
* possible object is
* {@link String }
*
*/
public String <API key>() {
return <API key>;
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.<API key> = value;
}
/**
* Gets the value of the instanceID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInstanceID() {
return instanceID;
}
/**
* Sets the value of the instanceID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInstanceID(String value) {
this.instanceID = value;
}
/**
* Gets the value of the objectClass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getObjectClass() {
return objectClass;
}
/**
* Sets the value of the objectClass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setObjectClass(String value) {
this.objectClass = value;
}
/**
* Gets the value of the <API key> property.
*
* @return
* possible object is
* {@link <API key> }
*
*/
public <API key> <API key>() {
return <API key>;
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link <API key> }
*
*/
public void <API key>(<API key> value) {
this.<API key> = value;
}
/**
* Gets the value of the linkedGenerationID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String <API key>() {
return linkedGenerationID;
}
/**
* Sets the value of the linkedGenerationID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.linkedGenerationID = value;
}
/**
* Gets the value of the path property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPath() {
return path;
}
/**
* Sets the value of the path property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPath(String value) {
this.path = value;
}
} |
#include "Cog.hh"
namespace ai {
namespace becca {
Cog::Cog() {
mZipTie = new CogZipTie;
mDaisyChain = new CogDaisyChain;
}
Cog::~Cog() {
delete mZipTie;
delete mDaisyChain;
}
} /* namespace becca */
} /* namespace ai */ |
<?php
/**
* Includes the Convert Class.
*
* @filesource
* @author Stefan Herndler
* @since 1.5.0 12.09.14 10:56
*/
/**
* Converts data types and Footnotes specific values.
*
* @author Stefan Herndler
* @since 1.5.0
*/
class <API key> {
/**
* Converts a integer into the user-defined counter style for the footnotes.
*
* @author Stefan Herndler
* @since 1.5.0
* @param int $p_int_Index Index to be converted.
* @param string $p_str_ConvertStyle Style of the new/converted Index.
* @return string Converted Index as string in the defined counter style.
*/
public static function Index($p_int_Index, $p_str_ConvertStyle = "arabic_plain") {
switch ($p_str_ConvertStyle) {
case "romanic":
return self::toRomanic($p_int_Index);
case "latin_high":
return self::toLatin($p_int_Index, true);
case "latin_low":
return self::toLatin($p_int_Index, false);
case "arabic_leading":
return self::toArabicLeading($p_int_Index);
case "arabic_plain":
default:
return $p_int_Index;
}
}
/**
* Converts an integer into latin ascii characters, either lower or upper-case.
* Function available from A to ZZ ( means 676 footnotes at 1 page possible).
*
* @author Stefan Herndler
* @since 1.0-gamma
* @param int $p_int_Value Value/Index to be converted.
* @param bool $p_bool_UpperCase True to convert the value to upper case letter, otherwise to lower case.
* @return string
*/
private static function toLatin($p_int_Value, $p_bool_UpperCase) {
// output string
$l_str_Return = "";
$l_int_Offset = 0;
// check if the value is higher then 26 = Z
while ($p_int_Value > 26) {
// increase offset and reduce counter
$l_int_Offset++;
$p_int_Value -= 26;
}
// if offset set (more then Z), then add a new letter in front
if ($l_int_Offset > 0) {
$l_str_Return = chr($l_int_Offset + 64);
}
// add the origin letter
$l_str_Return .= chr($p_int_Value + 64);
// return the latin character representing the integer
if ($p_bool_UpperCase) {
return strtoupper($l_str_Return);
}
return strtolower($l_str_Return);
}
/**
* Converts an integer to a leading-0 integer.
*
* @author Stefan Herndler
* @since 1.0-gamma
* @param int $p_int_Value Value/Index to be converted.
* @return string Value with a leading zero.
*/
private static function toArabicLeading($p_int_Value) {
// add a leading 0 if number lower then 10
if ($p_int_Value < 10) {
return "0" . $p_int_Value;
}
return $p_int_Value;
}
/**
* Converts an integer to a romanic letter.
*
* @author Stefan Herndler
* @since 1.0-gamma
* @param int $p_int_Value Value/Index to be converted.
* @return string
*/
private static function toRomanic($p_int_Value) {
// table containing all necessary romanic letters
$<API key> = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1
);
// return value
$l_str_Return = '';
// iterate through integer value until it is reduced to 0
while ($p_int_Value > 0) {
foreach ($<API key> as $l_str_Romanic => $l_int_Arabic) {
if ($p_int_Value >= $l_int_Arabic) {
$p_int_Value -= $l_int_Arabic;
$l_str_Return .= $l_str_Romanic;
break;
}
}
}
// return romanic letters as string
return $l_str_Return;
}
/**
* Converts a string depending on its value to a boolean.
*
* @author Stefan Herndler
* @since 1.0-beta
* @param string $p_str_Value String to be converted to boolean.
* @return bool Boolean representing the string.
*/
public static function toBool($p_str_Value) {
// convert string to lower-case to make it easier
$p_str_Value = strtolower($p_str_Value);
// check if string seems to contain a "true" value
switch ($p_str_Value) {
case "checked":
case "yes":
case "true":
case "on":
case "1":
return true;
}
// nothing found that says "true", so we return false
return false;
}
/**
* Get a html Array short code depending on Arrow-Array key index.
*
* @author Stefan Herndler
* @since 1.3.2
* @param int $p_int_Index Index representing the Arrow. If empty all Arrows are specified.
* @return array|string Array of all Arrows if Index is empty otherwise html tag of a specific arrow.
*/
public static function getArrow($p_int_Index = -1) {
// define all possible arrows
$l_arr_Arrows = array("↑", "↥", "↟", "↩", "↲", "↵", "⇑", "⇡", "⇧", "↑");
// convert index to an integer
if (!is_int($p_int_Index)) {
$p_int_Index = intval($p_int_Index);
}
// return the whole arrow array
if ($p_int_Index < 0 || $p_int_Index > count($l_arr_Arrows)) {
return $l_arr_Arrows;
}
// return a single arrow
return $l_arr_Arrows[$p_int_Index];
}
/**
* Displays a Variable.
*
* @author Stefan Herndler
* @since 1.5.0
* @param mixed $p_mixed_Value
*/
public static function debug($p_mixed_Value) {
if (empty($p_mixed_Value)) {
var_dump($p_mixed_Value);
} else if (is_array($p_mixed_Value)) {
printf("<pre>");
print_r($p_mixed_Value);
printf("</pre>");
} else if (is_object($p_mixed_Value)) {
printf("<pre>");
print_r($p_mixed_Value);
printf("</pre>");
} else if (is_numeric($p_mixed_Value) || is_int($p_mixed_Value)) {
var_dump($p_mixed_Value);
} else if (is_date($p_mixed_Value)) {
var_dump($p_mixed_Value);
} else {
var_dump($p_mixed_Value);
}
echo "<br/>";
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using CameraControl.Devices.Classes;
using WIA;
using System.Runtime.InteropServices;
namespace CameraControl.Devices.Others
{
public class WiaCameraDevice : BaseCameraDevice
{
Dictionary<int,string> ShutterTable = new Dictionary<int, string>
{
{1, "1/6400"},
{2, "1/4000"},
{3, "1/3200"},
{4, "1/2500"},
{5, "1/2000"},
{6, "1/1600"},
{8, "1/1250"},
{10, "1/1000"},
{12, "1/800"},
{15, "1/640"},
{20, "1/500"},
{25, "1/400"},
{31, "1/320"},
{40, "1/250"},
{50, "1/200"},
{62, "1/160"},
{80, "1/125"},
{100, "1/100"},
{125, "1/80"},
{166, "1/60"},
{200, "1/50"},
{250, "1/40"},
{333, "1/30"},
{400, "1/25"},
{500, "1/20"},
{666, "1/15"},
{769, "1/13"},
{1000, "1/10"},
{1250, "1/8"},
{1666, "1/6"},
{2000, "1/5"},
{2500, "1/4"},
{3333, "1/3"},
{4000, "1/2.5"},
{5000, "1/2"},
{6250, "1/1.6"},
{7692, "1/1.3"},
{10000, "1s"},
{13000, "1.3s"},
{16000, "1.6s"},
{20000, "2s"},
{25000, "2.5s"},
{30000, "3s"},
{40000, "4s"},
{50000, "5s"},
{60000, "6s"},
{80000, "8s"},
{100000, "10s"},
{130000, "13s"},
{150000, "15s"},
{200000, "20s"},
{250000, "25s"},
{300000, "30s"},
{-1, "Bulb"},
};
Dictionary<int,string> ExposureModeTable = new Dictionary<int, string>()
{
{1, "M"},
{2, "P"},
{3, "A"},
{4, "S"},
{0x8010, "[Scene mode] AUTO"},
{0x8011, "[Scene mode] Portrait"},
{0x8012, "[Scene mode] Landscape"},
{0x8013, "[Scene mode] Close up"},
{0x8014, "[Scene mode] Sports"},
{0x8016, "[Scene mode] Flash prohibition AUTO"},
{0x8017, "[Scene mode] Child"},
{0x8018, "[Scene mode] SCENE"},
{0x8019, "[EffectMode] EFFECTS"},
};
Dictionary<int, string> WbTable = new Dictionary<int, string>()
{
{2, "Auto"},
{4, "Daylight"},
{5, "Fluorescent "},
{6, "Incandescent"},
{7, "Flash"},
{32784, "Cloudy"},
{32785, "Shade"},
{32786, "Kelvin"},
{32787, "Custom"}
};
private Dictionary<int, string> CSTable = new Dictionary<int, string>()
{
{0, "JPEG (BASIC)"},
{1, "JPEG (NORMAL)"},
{2, "JPEG (FINE)"},
{3, "TIFF (RGB)"},
{4, "RAW"},
{5, "RAW + JPEG (BASIC)"},
{6, "RAW + JPEG (NORMAL)"},
{7, "RAW + JPEG (FINE)"}
};
private Dictionary<int,string> EMMTable=new Dictionary<int, string>
{
{2, "Center-weighted metering"},
{3, "Multi-pattern metering"},
{4, "Spot metering"}
};
private Dictionary<uint, string> FMTable=new Dictionary<uint, string>()
{
{1, "[M] Manual focus"},
{0x8010, "[S] Single AF servo"},
{0x8011, "[C] Continuous AF servo"},
{0x8012, "[A] AF servo mode automatic switching"},
{0x8013, "[F] Constant AF servo"},
};
#region Implementation of ICameraDevice
private string _displayName;
public override string DisplayName
{
get
{
if (string.IsNullOrEmpty(_displayName))
return DeviceName + " (" + SerialNumber + ")" + "(WIA)";
return _displayName;
}
set
{
_displayName = value;
<API key>("DisplayName");
}
}
//public override bool GetCapability(CapabilityEnum capabilityEnum)
// return false;
private Device Device { get; set; }
internal object Locker = new object(); // object used to lock multi
public DeviceManager DeviceManager { get; set; }
public override bool Init(DeviceDescriptor deviceDescriptor)
{
IsBusy = false;
//the device not connected
try
{
ConnectToWiaDevice(deviceDescriptor);
}
catch (Exception exception)
{
Log.Error("Unable to connect camera using wia driver", exception);
return false;
}
DeviceManager = new DeviceManager();
DeviceManager.RegisterEvent(Conts.wiaEventItemCreated, deviceDescriptor.WiaId);
DeviceManager.OnEvent += <API key>;
try
{
Device = deviceDescriptor.WiaDevice;
DeviceName = Device.Properties["Description"].get_Value();
Manufacturer = Device.Properties["Manufacturer"].get_Value();
SerialNumber = StaticHelper.GetSerial(Device.Properties["PnP ID String"].get_Value());
}
catch (Exception ex)
{
Log.Debug("Init error",ex);
}
IsConnected = true;
try
{
try
{
Property apertureProperty = Device.Properties[Conts.CONST_PROP_F_Number];
if (apertureProperty != null)
{
foreach (var subTypeValue in apertureProperty.SubTypeValues)
{
double d = (int) subTypeValue;
string s = "f/" + (d/100).ToString("0.0");
FNumber.AddValues(s, (int) d);
if ((int) subTypeValue == (int) apertureProperty.get_Value())
FNumber.SetValue((int) d);
}
}
}
catch (COMException)
{
FNumber.IsEnabled = false;
}
try
{
Property isoProperty = Device.Properties[Conts.<API key>];
if (isoProperty != null)
{
foreach (var subTypeValue in isoProperty.SubTypeValues)
{
IsoNumber.AddValues(subTypeValue.ToString(), (int) subTypeValue);
if ((int) subTypeValue == (int) isoProperty.get_Value())
IsoNumber.SetValue((int) subTypeValue);
}
}
}
catch (COMException)
{
IsoNumber.IsEnabled = false;
}
try
{
Property shutterProperty = Device.Properties[Conts.<API key>];
if (shutterProperty != null)
{
foreach (int subTypeValue in shutterProperty.SubTypeValues)
{
if (ShutterTable.ContainsKey((int) subTypeValue))
ShutterSpeed.AddValues(ShutterTable[(int) subTypeValue], (int) subTypeValue);
}
ShutterSpeed.SetValue(shutterProperty.get_Value());
}
}
catch (COMException)
{
ShutterSpeed.IsEnabled = false;
}
try
{
Property wbProperty = Device.Properties[Conts.<API key>];
if (wbProperty != null)
{
foreach (var subTypeValue in wbProperty.SubTypeValues)
{
if (WbTable.ContainsKey((int) subTypeValue))
WhiteBalance.AddValues(WbTable[(int) subTypeValue], (int) subTypeValue);
}
WhiteBalance.SetValue(wbProperty.get_Value());
}
}
catch (COMException)
{
WhiteBalance.IsEnabled = false;
}
try
{
Property modeProperty = Device.Properties[Conts.<API key>];
if (modeProperty != null)
{
foreach (var subTypeValue in modeProperty.SubTypeValues)
{
if (ExposureModeTable.ContainsKey((int) subTypeValue))
Mode.AddValues(ExposureModeTable[(int) subTypeValue], Convert.ToUInt32(subTypeValue));
}
Mode.SetValue(Convert.ToUInt32(modeProperty.get_Value()));
}
Mode.IsEnabled = false;
}
catch (COMException)
{
Mode.IsEnabled = false;
}
try
{
Property ecProperty = Device.Properties[Conts.<API key>];
if (ecProperty != null)
{
foreach (var subTypeValue in ecProperty.SubTypeValues)
{
decimal d = (int) subTypeValue;
string s = decimal.Round(d/1000, 1).ToString();
if (d > 0)
s = "+" + s;
<API key>.AddValues(s, (int) subTypeValue);
}
<API key>.SetValue(ecProperty.get_Value());
}
}
catch (COMException)
{
<API key>.IsEnabled = false;
}
try
{
Property csProperty = Device.Properties[Conts.<API key>];
if (csProperty != null)
{
foreach (var subTypeValue in csProperty.SubTypeValues)
{
if (CSTable.ContainsKey((int) subTypeValue))
CompressionSetting.AddValues(CSTable[(int) subTypeValue], (int) subTypeValue);
}
CompressionSetting.SetValue(csProperty.get_Value());
}
}
catch (COMException)
{
CompressionSetting.IsEnabled = false;
}
try
{
Property emmProperty = Device.Properties[Conts.<API key>];
if (emmProperty != null)
{
foreach (var subTypeValue in emmProperty.SubTypeValues)
{
if (EMMTable.ContainsKey((int) subTypeValue))
<API key>.AddValues(EMMTable[(int) subTypeValue], (int) subTypeValue);
}
CompressionSetting.SetValue(emmProperty.get_Value());
}
}
catch (COMException)
{
CompressionSetting.IsEnabled = false;
}
try
{
Property fmProperty = Device.Properties[Conts.<API key>];
if (fmProperty != null)
{
foreach (int subTypeValue in fmProperty.SubTypeValues)
{
uint subval = Convert.ToUInt16(subTypeValue);
if (FMTable.ContainsKey(subval))
FocusMode.AddValues(FMTable[subval], subval);
}
FocusMode.SetValue(Convert.ToUInt16((int) fmProperty.get_Value()));
}
}
catch (COMException)
{
FocusMode.IsEnabled = false;
}
try
{
Battery = Device.Properties[Conts.<API key>].get_Value();
}
catch (COMException)
{
Battery = 0;
}
IsConnected = true;
}
catch (Exception exception)
{
Log.Error(exception);
IsConnected = false;
}
HaveLiveView = true;
//Capabilities.Add(CapabilityEnum.LiveView);
return true;
}
private void ConnectToWiaDevice(DeviceDescriptor deviceDescriptor, int retries_left = 6)
{
if (deviceDescriptor.WiaDevice == null)
{
Thread.Sleep(500);
try
{
deviceDescriptor.WiaDevice = deviceDescriptor.WiaDeviceInfo.Connect();
deviceDescriptor.CameraDevice = this;
Thread.Sleep(250);
}
catch (COMException e)
{
if ((uint)e.ErrorCode == ErrorCodes.WIA_ERROR_BUSY && retries_left > 0)
{
int retry_in_secs = 2 * (7 - retries_left) ;
Thread.Sleep(1000 * retry_in_secs);
Log.Debug("Connection to wia failed, Retrying to connect in " + retry_in_secs + " seconds");
ConnectToWiaDevice(deviceDescriptor, retries_left - 1);
}
else
{
Log.Error("Could not connect to wia device.", e);
throw e;
}
}
}
}
void <API key>(string eventId, string deviceId, string itemId)
{
Item tem = Device.GetItem(itemId);
ImageFile imageFile = (ImageFile)tem.Transfer("{<API key>}");
<API key> args = new <API key>
{
EventArgs = imageFile,
CameraDevice = this,
FileName = "00000." + imageFile.FileExtension,
Handle = imageFile
};
OnPhotoCapture(this, args);
OnCaptureCompleted(this, new EventArgs());
}
public WiaCameraDevice()
{
FNumber = new PropertyValue<int>();
FNumber.ValueChanged += <API key>;
IsoNumber = new PropertyValue<int>();
IsoNumber.ValueChanged += <API key>;
ShutterSpeed = new PropertyValue<long>();
ShutterSpeed.ValueChanged += <API key>;
WhiteBalance = new PropertyValue<long>();
WhiteBalance.ValueChanged += <API key>;
Mode = new PropertyValue<uint>();
Mode.ValueChanged += Mode_ValueChanged;
CompressionSetting = new PropertyValue<int>();
CompressionSetting.ValueChanged += <API key>;
<API key> = new PropertyValue<int>();
<API key>.ValueChanged += <API key>;
<API key> = new PropertyValue<int>();
<API key>.ValueChanged += <API key>;
FocusMode = new PropertyValue<uint>();
FocusMode.IsEnabled = false;
}
void <API key>(object sender, string key, int val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void <API key>(object sender, string key, int val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void <API key>(object sender, string key, int val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void Mode_ValueChanged(object sender, string key, uint val)
{
lock (Locker)
{
switch (key)
{
case "M":
ShutterSpeed.IsEnabled = true;
FNumber.IsEnabled = true;
break;
case "P":
ShutterSpeed.IsEnabled = false;
FNumber.IsEnabled = false;
break;
case "A":
ShutterSpeed.IsEnabled = false;
FNumber.IsEnabled = true;
break;
case "S":
ShutterSpeed.IsEnabled = true;
FNumber.IsEnabled = false;
break;
default:
ShutterSpeed.IsEnabled = false;
FNumber.IsEnabled = false;
break;
}
Device.Properties[Conts.<API key>].set_Value(val);
}
}
void <API key>(object sender, string key, long val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void <API key>(object sender, string key, long val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void <API key>(object sender, string key, int val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.<API key>].set_Value(val);
}
catch (Exception)
{
}
}
}
void <API key>(object sender, string key, int val)
{
lock (Locker)
{
try
{
Device.Properties[Conts.CONST_PROP_F_Number].set_Value(val);
}
catch (Exception)
{
}
}
}
public override void StartLiveView()
{
//throw new <API key>();
}
public override void StopLiveView()
{
//throw new <API key>();
}
public override LiveViewData GetLiveViewImage()
{
//throw new <API key>();
return new LiveViewData();
}
public override void AutoFocus()
{
//throw new <API key>();
}
public override void Focus(int step)
{
//throw new <API key>();
}
public override void Focus(int x, int y)
{
//throw new <API key>();
}
public override void CapturePhotoNoAf()
{
lock (Locker)
{
CapturePhoto();
}
}
public override void CapturePhoto()
{
Monitor.Enter(Locker);
try
{
IsBusy = true;
Device.ExecuteCommand(Conts.<API key>);
}
catch (COMException comException)
{
IsBusy = false;
ErrorCodes.GetException(comException);
}
catch
{
IsBusy = false;
throw;
}
finally
{
Monitor.Exit(Locker);
}
}
public override void Close()
{
if (Device != null)
Marshal.ReleaseComObject(Device);
Device = null;
HaveLiveView = false;
if (DeviceName != null)
DeviceManager.OnEvent -= <API key>;
}
public override void <API key>(int o)
{
HaveLiveView = true;
}
public override void TransferFile(object o, string filename)
{
ImageFile deviceEventArgs = o as ImageFile;
if (deviceEventArgs != null)
{
deviceEventArgs.SaveFile(filename);
}
}
//public override event <API key> PhotoCaptured;
#endregion
}
} |
# Utility functions
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import logging
import ntpath
import os
import pathlib
import posixpath
def nt2posixpath(path):
return path.replace(ntpath.sep, posixpath.sep)
def open_read(filename, encoding="latin-1"):
path = lookup_path_icase(filename)
if path:
return open(path, "rt", encoding=encoding)
else:
# this will fail, but it gives us a nice FileNotFoundError
return open(filename, "rt", encoding=encoding)
def in_directory(path, directory):
"""Check if ``path`` is within ``directory`` or is ``directory`` itself"""
path = pathlib.Path(os.path.abspath(path)).parts
directory = pathlib.Path(os.path.abspath(directory)).parts
if len(path) < len(directory):
return False
else:
for lhs, rhs in zip(path, directory):
if lhs.lower() != rhs.lower():
return False
return True
def find_files(directory, ext=None):
"""Traverses a directory and returns all files contained within, if
``ext`` is given, only files ending with ``ext`` are returned"""
results = []
for path, dirs, files in os.walk(directory):
for fname in files:
if ext and os.path.splitext(fname)[1].lower() == ext:
results.append(os.path.join(path, fname))
elif ext is None:
results.append(os.path.join(path, fname))
return results
def find_file(directory, name):
for path, dirs, files in os.walk(directory):
for fname in files:
if fname.lower() == name.lower():
return os.path.join(path, fname)
return None
def _lookup_path_icase(root, rest):
"""
Given a root directory and a list of directory parts, find all
path that match root + rest, while ignoring the case of the filenames.
"""
if not rest:
return [os.path.normpath(root)]
else:
results = []
if os.path.isdir(root):
for f in os.listdir(root):
if f.lower() == rest[0].lower():
p = os.path.join(root, f)
results += _lookup_path_icase(p, rest[1:])
return results
def <API key>(filename):
"""Returns list of files matching filename in a case insensitive manner"""
if os.name == 'nt':
if os.path.exists(filename):
return [filename]
else:
return []
else:
assert filename, "filename must not be empty: %s" % filename
filename = os.path.normpath(filename)
path = pathlib.Path(filename)
parts = path.parts
if not path.is_absolute():
return _lookup_path_icase(os.curdir, parts)
else:
return _lookup_path_icase(parts[0], parts[1:])
def lookup_path_icase(filename):
"""Returns single filename matching filename in a case insensitive"""
results = <API key>(filename)
if not results:
return None
else:
if len(results) > 1:
logging.warning("%s: filename not unique, returning first match:\n", "\n".join(results))
return results[0]
def path_exists(filename):
return lookup_path_icase(filename) is not None
def file_exists(filename):
p = lookup_path_icase(filename)
if p is not None:
return bool(os.path.isfile(p))
else:
return False
def directory_exists(filename):
p = lookup_path_icase(filename)
if p is not None:
return bool(os.path.isdir(p))
else:
return False
# EOF # |
package bc
import (
"fmt"
"math/big"
"github.com/immesys/bw2/util/bwe"
"github.com/immesys/bw2bc/common"
"github.com/immesys/bw2bc/common/math"
)
/*
This is the API for a 32 byte Universal Function Identifier.
The first 20 bytes are a contract address. The next 4 bytes are the
function selector. The remaining 8 bytes are broken into 16 nibbles
that contain type information for up to 15 arguments or return values
depending on how complex their types are.
//0 - break between args and return value or padding at end
//1 - uint
//2 - int
//3 - string
//4 - dynamic bytes
//5 - static bytes (pad right whereas uint pads left)
//6 - fixed, next nibble is shift
//7 - ufixed, next nibble is shift
//8 - array, next nibble is length, nibble after is type
//9-15 reserved
*/
const (
TBreak = 0
TUInt = 1
TInt = 2
TString = 3
TBytes = 4
TDBytes = 5
TFixed = 6
TUFixed = 7
TArray = 8
)
/*
completely incorrect usage of the digest btw
func MakeUFI(contract common.Address, fsig string, tokens ...int) UFI {
ufi := UFI{}
copy(ufi[:20], contract[:])
d := sha3.NewKeccak256()
copy(ufi[20:24], d.Sum([]byte(fsig))[:8])
for i, t := range tokens {
ufi[24+i] = byte(t)
}
return ufi
}
*/
func StringToUFI(ufi string) UFI {
return UFI(common.HexToHash(ufi))
}
//Bytes are in hex, strings are just strings, ints are in decimal, fixed are
//in decimal with a point. Anything past tbytes is unsupported
func EncodeABICall(ufi UFI, argvaluesi ...interface{}) (contract common.Address, data []byte, err error) {
var fsig []byte
var args []int
argvalues := make([]string, len(argvaluesi))
for idx, ifc := range argvaluesi {
switch ifc := ifc.(type) {
case string:
argvalues[idx] = ifc
case []byte:
argvalues[idx] = common.Bytes2Hex(ifc)
case Bytes32:
argvalues[idx] = common.Bytes2Hex(ifc[:])
case int64:
argvalues[idx] = big.NewInt(ifc).Text(16)
case *big.Int:
argvalues[idx] = ifc.Text(16)
default:
panic(ifc)
}
}
contract, fsig, args, _, err = DecodeUFI(ufi)
if err != nil {
return
}
data = make([]byte, 4)
copy(data, fsig)
num_args := len(args)
extra := make([]byte, 0)
endloc := num_args * 32
if num_args != len(argvalues) {
err = bwe.M(bwe.InvalidUFI, "Incorrect number of arguments for UFI")
return
}
for idx, arg := range args {
switch arg {
case TUInt:
v, ok := big.NewInt(0).SetString(argvalues[idx], 16)
if !ok {
err = bwe.M(bwe.InvalidUFI, "Could not parse argument")
}
v = math.U256(v)
data = append(data, math.PaddedBigBytes(v, 32)...)
case TInt:
v, ok := big.NewInt(0).SetString(argvalues[idx], 16)
if !ok {
err = bwe.M(bwe.InvalidUFI, "Could not parse argument")
}
v = math.S256(v)
data = append(data, math.PaddedBigBytes(v, 32)...)
case TString:
offset := math.PaddedBigBytes(big.NewInt(int64(endloc+len(extra))), 32)
data = append(data, offset...)
extra = append(extra, math.PaddedBigBytes(big.NewInt(int64(len(argvalues[idx]))), 32)...)
strPadLen := len(argvalues[idx])
if strPadLen%32 != 0 {
strPadLen += 32 - (strPadLen % 32)
}
extra = append(extra, common.RightPadBytes([]byte(argvalues[idx]), strPadLen)...)
case TDBytes:
offset := math.PaddedBigBytes(big.NewInt(int64(endloc+len(extra))), 32)
argv := common.FromHex(argvalues[idx])
origlen := len(argv)
if len(argv)%32 != 0 {
argv = common.RightPadBytes(argv, len(argv)+(32-len(argv)%32))
}
data = append(data, offset...)
extra = append(extra, math.PaddedBigBytes(big.NewInt(int64(origlen)), 32)...)
extra = append(extra, argv...)
case TBytes:
argv := common.FromHex(argvalues[idx])
if len(argv) > 32 {
argv = argv[:32]
}
data = append(data, common.RightPadBytes(argv, 32)...)
default:
panic(arg)
}
}
data = append(data, extra...)
return
}
func DecodeABIReturn(ufi UFI, data []byte) (retvalues []interface{}, err error) {
var rets []int
_, _, _, rets, err = DecodeUFI(ufi)
if err != nil {
return
}
if len(data) < 32*len(rets) {
err = fmt.Errorf("Data is too short for UFI")
return
}
retvalues = make([]interface{}, len(rets))
for idx, arg := range rets {
datv := data[idx*32 : (idx+1)*32]
switch arg {
case TUInt:
i := big.NewInt(0).SetBytes(datv)
i = math.U256(i)
retvalues[idx] = i
case TInt:
i := big.NewInt(0).SetBytes(datv)
i = math.S256(i)
retvalues[idx] = i
case TBytes:
cp := make([]byte, len(datv))
copy(cp, datv)
retvalues[idx] = cp
case TDBytes:
offset := big.NewInt(0).SetBytes(datv).Int64()
length := big.NewInt(0).SetBytes(data[offset : offset+32]).Int64()
cp := make([]byte, length)
copy(cp, data[offset+32:offset+32+length])
retvalues[idx] = cp
default:
panic(arg)
}
}
return
}
func DecodeUFI(ufi UFI) (contract common.Address, fsig []byte, args []int, rets []int, err error) {
contract = common.BytesToAddress(ufi[:20])
fsig = ufi[20:24]
args = make([]int, 0, 16)
rets = make([]int, 0, 16)
i := 0
//Args
for ; i < 16; i++ {
token := int(ufi[24+(i/2)])
if i%2 == 0 {
token >>= 4
} else {
token &= 0xF
}
if token == TBreak {
break
}
if token > TDBytes {
err = fmt.Errorf("Unsupported UFI token")
return
}
//In future more support for arrays
args = append(args, token)
}
i++
//Rets
for ; i < 16; i++ {
token := int(ufi[24+(i/2)])
if i%2 == 0 {
token >>= 4
} else {
token &= 0xF
}
if token == TBreak {
break
}
if token > TDBytes {
err = fmt.Errorf("Unsupported UFI token %d", token)
return
}
//In future more support for arrays
rets = append(rets, token)
}
return
} |
using System.Windows;
using System.Windows.Media;
using Hurricane.PluginAPI.AudioVisualisation;
namespace Hurricane.Settings.Themes.AudioVisualisation.<API key>
{
public class <API key> : <API key>
{
private <API key> _loadedPlugin;
public override <API key> Visualisation
{
get { return _loadedPlugin ?? (_loadedPlugin = new <API key>()); }
}
public override string Name
{
get { return Application.Current.Resources["Rectangles"].ToString(); }
}
public class <API key> : <API key>
{
private IAudioVisualisation <API key>;
public IAudioVisualisation <API key>
{
get
{
return <API key> ??
(<API key> = new <API key>());
}
}
private IAudioVisualisation <API key>;
public IAudioVisualisation <API key>
{
get
{
return <API key> ??
(<API key> = new <API key>());
}
}
public string Creator
{
get { return "Akaline"; }
}
private GeometryGroup _thumbnail;
public GeometryGroup Thumbnail
{
get
{
if (_thumbnail == null)
{
var values = new[]
{
"F1 M 6.367,16.715 L 0.974,16.715 C 0.436,16.715 0.000,17.151 0.000,17.689 C 0.000,18.226 0.436,18.662 0.974,18.662 L 6.367,18.662 C 6.905,18.662 7.341,18.226 7.341,17.689 C 7.341,17.151 6.905,16.715 6.367,16.715 Z",
"F1 M 6.367,13.372 L 0.974,13.372 C 0.436,13.372 0.000,13.808 0.000,14.346 C 0.000,14.883 0.436,15.319 0.974,15.319 L 6.367,15.319 C 6.905,15.319 7.341,14.883 7.341,14.346 C 7.341,13.808 6.905,13.372 6.367,13.372 Z",
"F1 M 6.367,10.029 L 0.974,10.029 C 0.436,10.029 0.000,10.465 0.000,11.003 C 0.000,11.540 0.436,11.976 0.974,11.976 L 6.367,11.976 C 6.905,11.976 7.341,11.540 7.341,11.003 C 7.341,10.465 6.905,10.029 6.367,10.029 Z",
"F1 M 6.367,20.023 L 0.974,20.023 C 0.436,20.023 0.000,20.459 0.000,20.997 C 0.000,21.535 0.436,21.970 0.974,21.970 L 6.367,21.970 C 6.905,21.970 7.341,21.535 7.341,20.997 C 7.341,20.459 6.905,20.023 6.367,20.023 Z",
"F1 M 14.587,16.715 L 9.193,16.715 C 8.656,16.715 8.220,17.151 8.220,17.689 C 8.220,18.226 8.656,18.662 9.193,18.662 L 14.587,18.662 C 15.125,18.662 15.561,18.226 15.561,17.689 C 15.561,17.151 15.125,16.715 14.587,16.715 Z",
"F1 M 14.587,13.372 L 9.193,13.372 C 8.656,13.372 8.220,13.808 8.220,14.346 C 8.220,14.883 8.656,15.319 9.193,15.319 L 14.587,15.319 C 15.125,15.319 15.561,14.883 15.561,14.346 C 15.561,13.808 15.125,13.372 14.587,13.372 Z",
"F1 M 14.587,6.686 L 9.193,6.686 C 8.656,6.686 8.220,7.122 8.220,7.660 C 8.220,8.197 8.656,8.633 9.193,8.633 L 14.587,8.633 C 15.125,8.633 15.561,8.197 15.561,7.660 C 15.561,7.122 15.125,6.686 14.587,6.686 Z",
"F1 M 14.587,3.343 L 9.193,3.343 C 8.656,3.343 8.220,3.779 8.220,4.316 C 8.220,4.854 8.656,5.290 9.193,5.290 L 14.587,5.290 C 15.125,5.290 15.561,4.854 15.561,4.316 C 15.561,3.779 15.125,3.343 14.587,3.343 Z",
"F1 M 14.587,0.000 L 9.193,0.000 C 8.656,0.000 8.220,0.436 8.220,0.974 C 8.220,1.511 8.656,1.947 9.193,1.947 L 14.587,1.947 C 15.125,1.947 15.561,1.511 15.561,0.974 C 15.561,0.436 15.125,0.000 14.587,0.000 Z",
"F1 M 14.587,10.029 L 9.193,10.029 C 8.656,10.029 8.220,10.465 8.220,11.003 C 8.220,11.540 8.656,11.976 9.193,11.976 L 14.587,11.976 C 15.125,11.976 15.561,11.540 15.561,11.003 C 15.561,10.465 15.125,10.029 14.587,10.029 Z",
"F1 M 14.587,20.023 L 9.193,20.023 C 8.656,20.023 8.220,20.459 8.220,20.997 C 8.220,21.535 8.656,21.970 9.193,21.970 L 14.587,21.970 C 15.125,21.970 15.561,21.535 15.561,20.997 C 15.561,20.459 15.125,20.023 14.587,20.023 Z",
"F1 M 22.807,16.715 L 17.413,16.715 C 16.875,16.715 16.440,17.151 16.440,17.689 C 16.440,18.226 16.875,18.662 17.413,18.662 L 22.807,18.662 C 23.345,18.662 23.780,18.226 23.780,17.689 C 23.780,17.151 23.344,16.715 22.807,16.715 Z",
"F1 M 22.807,13.372 L 17.413,13.372 C 16.875,13.372 16.440,13.808 16.440,14.346 C 16.440,14.883 16.875,15.319 17.413,15.319 L 22.807,15.319 C 23.345,15.319 23.780,14.883 23.780,14.346 C 23.780,13.808 23.344,13.372 22.807,13.372 Z",
"F1 M 22.807,6.686 L 17.413,6.686 C 16.875,6.686 16.440,7.122 16.440,7.660 C 16.440,8.197 16.875,8.633 17.413,8.633 L 22.807,8.633 C 23.345,8.633 23.780,8.197 23.780,7.660 C 23.780,7.122 23.344,6.686 22.807,6.686 Z",
"F1 M 22.807,10.029 L 17.413,10.029 C 16.875,10.029 16.440,10.465 16.440,11.003 C 16.440,11.540 16.875,11.976 17.413,11.976 L 22.807,11.976 C 23.345,11.976 23.780,11.540 23.780,11.003 C 23.780,10.465 23.344,10.029 22.807,10.029 Z",
"F1 M 22.807,20.023 L 17.413,20.023 C 16.875,20.023 16.440,20.459 16.440,20.997 C 16.440,21.535 16.875,21.970 17.413,21.970 L 22.807,21.970 C 23.345,21.970 23.780,21.535 23.780,20.997 C 23.780,20.459 23.344,20.023 22.807,20.023 Z",
"F1 M 31.026,16.715 L 25.633,16.715 C 25.095,16.715 24.659,17.151 24.659,17.689 C 24.659,18.226 25.095,18.662 25.633,18.662 L 31.026,18.662 C 31.564,18.662 32.000,18.226 32.000,17.689 C 32.000,17.151 31.564,16.715 31.026,16.715 Z",
"F1 M 31.026,20.023 L 25.633,20.023 C 25.095,20.023 24.659,20.459 24.659,20.997 C 24.659,21.535 25.095,21.970 25.633,21.970 L 31.026,21.970 C 31.564,21.970 32.000,21.535 32.000,20.997 C 32.000,20.459 31.564,20.023 31.026,20.023 Z",
"F1 M 6.367,23.268 L 0.974,23.268 C 0.436,23.268 0.000,23.704 0.000,24.242 C 0.000,24.780 0.436,25.215 0.974,25.215 L 6.367,25.215 C 6.905,25.215 7.341,24.780 7.341,24.242 C 7.341,23.704 6.905,23.268 6.367,23.268 Z",
"F1 M 14.587,23.268 L 9.193,23.268 C 8.656,23.268 8.220,23.704 8.220,24.242 C 8.220,24.780 8.656,25.215 9.193,25.215 L 14.587,25.215 C 15.125,25.215 15.561,24.780 15.561,24.242 C 15.561,23.704 15.125,23.268 14.587,23.268 Z",
"F1 M 22.807,23.268 L 17.413,23.268 C 16.875,23.268 16.440,23.704 16.440,24.242 C 16.440,24.780 16.875,25.215 17.413,25.215 L 22.807,25.215 C 23.345,25.215 23.780,24.780 23.780,24.242 C 23.780,23.704 23.344,23.268 22.807,23.268 Z",
"F1 M 31.026,23.268 L 25.633,23.268 C 25.095,23.268 24.659,23.704 24.659,24.242 C 24.659,24.780 25.095,25.215 25.633,25.215 L 31.026,25.215 C 31.564,25.215 32.000,24.780 32.000,24.242 C 32.000,23.704 31.564,23.268 31.026,23.268 Z",
"F1 M 31.026,13.372 L 25.633,13.372 C 25.095,13.372 24.659,13.808 24.659,14.346 C 24.659,14.883 25.095,15.319 25.633,15.319 L 31.026,15.319 C 31.564,15.319 32.000,14.883 32.000,14.346 C 32.000,13.808 31.564,13.372 31.026,13.372 Z",
"F1 M 31.026,6.686 L 25.633,6.686 C 25.095,6.686 24.659,7.122 24.659,7.660 C 24.659,8.197 25.095,8.633 25.633,8.633 L 31.026,8.633 C 31.564,8.633 32.000,8.197 32.000,7.660 C 32.000,7.122 31.564,6.686 31.026,6.686 Z",
"F1 M 25.633,5.290 L 31.027,5.290 C 31.564,5.290 32.000,4.854 32.000,4.316 C 32.000,3.779 31.564,3.343 31.027,3.343 L 25.633,3.343 C 25.095,3.343 24.659,3.779 24.659,4.316 C 24.659,4.854 25.095,5.290 25.633,5.290 Z",
"F1 M 31.026,10.029 L 25.633,10.029 C 25.095,10.029 24.659,10.465 24.659,11.003 C 24.659,11.540 25.095,11.976 25.633,11.976 L 31.026,11.976 C 31.564,11.976 32.000,11.540 32.000,11.003 C 32.000,10.465 31.564,10.029 31.026,10.029 Z"
};
_thumbnail = new GeometryGroup();
foreach (var value in values)
{
_thumbnail.Children.Add(Geometry.Parse(value));
}
_thumbnail.Freeze();
}
return _thumbnail;
}
}
public void Refresh()
{
if (<API key> != null) <API key>.Dispose();
if (<API key> != null) <API key>.Disable();
<API key> = null;
<API key> = null;
}
}
}
} |
'use strict';
/**
* Serverless Module: Lambda Handler
* - Your lambda functions should be a thin wrapper around your own separate
* modules, to keep your code testable, reusable and AWS independent
* - '<API key>' module is required for Serverless ENV var support. Hopefully, AWS will add ENV support to Lambda soon :)
*/
// Require Serverless ENV vars
var ServerlessHelpers = require('<API key>').loadEnv();
// Require Logic
var lib = require('../../lib/biddings');
// Lambda Handler
module.exports.handler = function(event, context) {
lib.<API key>(event, function(error, response) {
return context.done(error, response);
});
}; |
from channels.auth import <API key>,<API key>,http_session
from channels.routing import route, route_class
from channels.sessions import <API key>,channel_session
import datetime
import json
import copy
import pprint as pp
from django.http import HttpResponse
from django.http import <API key>
from Crypto.Hash import MD5
from hashlib import md5
from Crypto import Random
from Crypto.Cipher import AES
from random import choice
from base64 import b64encode,b64decode
from models import user
from models import plan
from mongoengine.queryset import Q
def derive_key_and_iv(password, salt, key_length, iv_length):
d = d_i = ''
while len(d) < key_length + iv_length:
d_i = md5(d_i + password + salt).digest()
d += d_i
return d[:key_length], d[key_length:key_length+iv_length]
def encrypt(data, password, key_length=32):
if len(data)%2 == 0:
data=data+" "
bs = AES.block_size
salt = Random.new().read(bs - len('Salted__'))
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
ch1='Salted__' + salt
#print ch1
if len(data) == 0 or len(data) % bs != 0:
padding_length = bs - (len(data) % bs)
data += padding_length * chr(padding_length)
return ch1+cipher.encrypt(data)
def decrypt(data, password, key_length=32):
bs = AES.block_size
salt = data[:bs][len('Salted__'):]
#print len(salt)
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
chunk=data[bs:]
unpadded_text=cipher.decrypt(chunk)
padding_length=ord(unpadded_text[-1])
#print ("padding Length {}".format(padding_length))
padded_text=unpadded_text[:-padding_length]
return padded_text
@<API key>
def connectedChannel(message):
encKey=MD5.new(str(message.reply_channel)).hexdigest()
decryptedJSON=decrypt(b64decode(message['text']),encKey)
messageJSON=json.loads(decryptedJSON)
pp.pprint(messageJSON)
pp.pprint(message)
pp.pprint("ConnectedChannel")
if message.http_session is None:
print("Session type None")
redirectPage="/"
redirectParam="InvalidSession=true"
<API key>=b64encode(encrypt(redirectParam,encKey))
message.reply_channel.send({
'text':json.dumps({'verdict':<API key>,'redirect':redirectPage})
})
if messageJSON['target'] == 'CU':
# need to get the CurrentUser Logged In.
CU=user.objects(pk=messageJSON['id'])
if CU.count() == 1:
encryptedCUJsonStr=b64encode(encrypt(CU[0].to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'CU':encryptedCUJsonStr})
})
else :
redirectPage="/LogOut"
message.reply_channel.send({
'text':json.dumps({'redirect':redirectPage})
})
if messageJSON['target'] == 'CHK' :
if message.http_session is None:
redirectPage="/"
redirectParam="InvalidSession=true"
<API key>=b64encode(encrypt(redirectParam,encKey))
message.reply_channel.send({
'text':json.dumps({'verdict':<API key>,'redirect':redirectPage})
})
if messageJSON['target'] == 'CNTS':
QAll=Q(isDealer=True)
QEnabled=Q(isDealer=True) & Q(Enabled=True)
QDeleted=Q(isDealer=True) & Q(Deleted=True)
QDisabled=Q(isDealer=True) & Q(Enabled=False)
AllCount=user.objects(QAll).count()
EnabledCount=user.objects(QEnabled).count()
DeletedCount=user.objects(QDeleted).count()
DisabledCount=user.objects(QDisabled).count()
CountsObj={
'All':AllCount,
'Ena':EnabledCount,
'Dis':DisabledCount,
'Del':DeletedCount
}
encryptedMSG=b64encode(encrypt(json.dumps(CountsObj),encKey))
message.reply_channel.send({
'text':json.dumps({'CNTS':encryptedMSG})
})
if messageJSON['target'] == 'DLRS':
QQuery=Q(isDealer=True)
if messageJSON['type']=='All':
QQuery=Q(isDealer=True)
elif messageJSON['type']=='Ena':
QQuery=Q(isDealer=True) & Q(Enabled=True)
elif messageJSON['type'] == 'Dis' :
QQuery=Q(isDealer=True) & Q(Enabled=False)
elif messageJSON['type']=='Del':
QQuery=Q(isDealer=True) & Q(Deleted=True)
theList=user.objects(QQuery)
encryptedMSG=b64encode(encrypt(theList.to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'DLRS':encryptedMSG})
})
if messageJSON['target'] == 'USR':
#pp.pprint(messageJSON['Who'])
QQuery=Q(isDealer=True) & Q(id=messageJSON['Who'])
theUser=user.objects(QQuery)
#pp.pprint(theUser[0].to_json())
encryptedMSG=b64encode(encrypt(theUser[0].to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'EUSR':encryptedMSG})
})
if messageJSON['target'] == 'AllPlans':
print("Getting All Plans Here As Should be returned ")
QQuery=Q(Enabled=True) & Q(Deleted=False)
thePlans=plan.objects(QQuery)
encryptedMSG=b64encode(encrypt(thePlans.to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'AllPlans':encryptedMSG})
})
if messageJSON['target'] == 'USRUPT' :
print(" Updating A User Of ID :({})".format(messageJSON['Who']))
currentDealer=copy.deepcopy(messageJSON['data'])
#get the currentDealerID to change
dealerID=messageJSON['Who']
#check for lgnName if exists.
lgnNameQuery=Q(lgnName=currentDealer['lgnName'])
idQuery=Q(_id=dealerID)
lgnNameFetch=user.objects(lgnNameQuery)
if lgnNameFetch.count() > 0 :
# if we have a lgnNameFetch Count >0 then we check for associated _id
theID=lgnNameFetch[0]['id']
if str(theID) == str(dealerID) :
# we proceed with Updates
#print("Matched ID continue")
if currentDealer.has_key('_id') :
del currentDealer['_id']
currentDealer['updatedAt']=datetime.datetime.now()
if currentDealer.has_key('InternalId') :
del currentDealer['InternalId']
if currentDealer.has_key('createdAt') :
del currentDealer['createdAt']
theDBDealer=user.objects(idQuery)
user.objects(id=dealerID).update(**currentDealer)
encryptedMSG=b64encode(encrypt(json.dumps({'Success':True}),encKey))
message.reply_channel.send({
'text':json.dumps({'dealerUPDT':encryptedMSG})
})
else:
# we should issue an error back
print("duplicate lgnName Error")
# ToDo
# Continue submitting Error from the server to the web browser.
if messageJSON['target'] == 'USRUPDTPLAN':
# ToDo Allow Updating Plans Here
#print("The Data {}".format(messageJSON['data']))
dealerID=messageJSON['Who']
#print("The ID To Be Fetched is {}".format(dealerID))
idQuery=Q(id=dealerID)
idFetch=user.objects(idQuery)
#print(" The ID Fetched is {} {}".format(idFetch[0],messageJSON['data']))
if idFetch.count() > 0:
currentUpdate=copy.deepcopy(messageJSON['data'])
user.objects(id=dealerID).update(**currentUpdate)
if messageJSON['target'] == 'USRUPDTCLIENT':
# ToDo
clientID=messageJSON['Who']
idQuery=Q(id=clientID)
idFetch=user.objects(idQuery)
if idFetch.count() > 0:
currentUpdate=copy.deepcopy(messageJSON['data'])
del currentUpdate['_id']
currentUpdate['updatedAt']=datetime.datetime.now()
if currentUpdate.has_key('InternalId'):
del currentUpdate['InternalId']
if currentUpdate.has_key('createdAt'):
del currentUpdate['createdAt']
if currentUpdate.has_key('Expires'):
del currentUpdate['Expires']
user.objects(id=clientID).update(**currentUpdate)
if messageJSON['target'] == 'USRGETCLIENTS':
'''
Done Pick clients of Owner= 'Who'
'''
dealerID=messageJSON['Who']
clientsQuery=(Q(Owner=dealerID) &Q(isClient=True))
TheClients=user.objects(clientsQuery)
#print("No. Of Clients For the User is {}".format(TheClients.count()))
'''
Check if count is > 0
'''
if TheClients.count() > 0:
'''
if > 0 then we return the to_json back to the page.
'''
encryptedMSG=b64encode(encrypt(TheClients.to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'USRGOTCLIENTS':encryptedMSG})
})
else :
encryptedMSG=b64encode(encrypt(json.dumps({'NoOfClients':0}),encKey))
message.reply_channel.send({
'text':json.dumps({'USRGOTNOCLIENTS':encryptedMSG})
})
if messageJSON['target'] == 'USRGETCLIENT':
'''
Done Pick Client of ID
'''
clientID=messageJSON['Who']
ClientQuery=(Q(pk=clientID) & Q(isClient=True))
theClient=user.objects(ClientQuery)
if theClient.count() == 1:
encryptedMSG=b64encode(encrypt(theClient[0].to_json(),encKey))
message.reply_channel.send({
'text':json.dumps({'USRGOTCLIENT':encryptedMSG})
})
else :
encryptedMSG=b64encode(encrypt(json.dumps({'NoOfClients':theClient.count()}),encKey))
message.reply_channel.send({
'text':json.dumps({'USRGOTNoCLIENT':encryptedMSG})
})
@<API key>
def connectChannelid(message):
pp.pprint(message)
pp.pprint("Connecting CHannel")
message.reply_channel.send({'accept':True,
'text':json.dumps({'enc':MD5.new(str(message.reply_channel)).hexdigest()})
})
channel_routing = [
#route('http.request',processRequest),
route('websocket.connect',connectChannelid),
route('websocket.receive',connectedChannel)
] |
#!/usr/bin/env python
from time import sleep
class ButtonListener():
"""
Service that polls the button status device and calls a
callback funtion for each button pressed.
Callback function should return a boolean to show whether
or not the listening should continue.
"""
def __init__(self, button_callback, device_filename="/dev/buttons", num_buttons=8, *args, **kw):
self.button_callback = button_callback
self.button_device = open(device_filename, "r")
self.num_buttons = num_buttons
self.last_state = {"0": 0}
def listen(self):
while True:
raw_state = [ord(ch) for ch in self.button_device.read(self.num_buttons)]
state = dict(zip(range(0, len(raw_state)), raw_state))
for (button, isup) in state.iteritems():
if isup:
state[button] = 1
else:
state[button] = 0
if not isup and button in self.last_state and self.last_state[button]:
if not self.button_callback(button):
return
self.last_state = state
sleep(0.2)
if __name__ == "__main__":
def print_button(button):
print("Button %s pressed" % button)
return True
service = ButtonListener(print_button)
service.listen() |
#ifndef <API key>
#define <API key>
#include "<API key>.h"
#include <vector>
#include "<API key>.h"
#include <vector>
#include "podio/ObjectID.h"
//forward declarations
namespace ex {
class <API key>;
class <API key>;
}
#include "<API key>.h"
#include "<API key>.h"
namespace ex {
class <API key>;
class <API key>;
class <API key>;
class <API key> {
friend <API key>;
friend <API key>;
friend <API key>;
public:
default constructor
<API key>();
<API key>(float number);
constructor from existing <API key>
<API key>(<API key>* obj);
copy constructor
<API key>(const <API key>& other);
copy-assignment operator
<API key>& operator=(const <API key>& other);
support cloning (deep-copy)
<API key> clone() const;
destructor
~<API key>();
conversion to const object
operator <API key> () const;
public:
Access the just a number
const float& number() const;
Access the a ref in a namespace
const ex::<API key> ref() const;
Set the just a number
void number(float value);
Set the a ref in a namespace
void ref(ex::<API key> value);
void addrefs(ex::<API key>);
unsigned int refs_size() const;
ex::<API key> refs(unsigned int) const;
std::vector<ex::<API key>>::const_iterator refs_begin() const;
std::vector<ex::<API key>>::const_iterator refs_end() const;
check whether the object is actually available
bool isAvailable() const;
disconnect from <API key> instance
void unlink(){m_obj = nullptr;}
bool operator==(const <API key>& other) const {
return (m_obj==other.m_obj);
}
bool operator==(const <API key>& other) const;
// less comparison operator, so that objects can be e.g. stored in sets.
// friend bool operator< (const <API key>& p1,
// const <API key>& p2 );
bool operator<(const <API key>& other) const { return m_obj < other.m_obj ; }
const podio::ObjectID getObjectID() const;
private:
<API key>* m_obj;
};
} // namespace ex
#endif |
#include "storm/storage/expressions/BinaryExpression.h"
#include "storm/exceptions/<API key>.h"
#include "storm/utility/macros.h"
namespace storm {
namespace expressions {
BinaryExpression::BinaryExpression(ExpressionManager const& manager, Type const& type, std::shared_ptr<BaseExpression const> const& firstOperand,
std::shared_ptr<BaseExpression const> const& secondOperand)
: BaseExpression(manager, type), firstOperand(firstOperand), secondOperand(secondOperand) {
// Intentionally left empty.
}
bool BinaryExpression::<API key>() const {
return true;
}
bool BinaryExpression::containsVariables() const {
return this->getFirstOperand()->containsVariables() || this->getSecondOperand()->containsVariables();
}
void BinaryExpression::gatherVariables(std::set<storm::expressions::Variable>& variables) const {
this->getFirstOperand()->gatherVariables(variables);
this->getSecondOperand()->gatherVariables(variables);
}
std::shared_ptr<BaseExpression const> const& BinaryExpression::getFirstOperand() const {
return this->firstOperand;
}
std::shared_ptr<BaseExpression const> const& BinaryExpression::getSecondOperand() const {
return this->secondOperand;
}
uint_fast64_t BinaryExpression::getArity() const {
return 2;
}
std::shared_ptr<BaseExpression const> BinaryExpression::getOperand(uint_fast64_t operandIndex) const {
STORM_LOG_THROW(operandIndex < 2, storm::exceptions::<API key>, "Unable to access operand " << operandIndex << " in expression of arity 2.");
if (operandIndex == 0) {
return this->getFirstOperand();
} else {
return this->getSecondOperand();
}
}
} // namespace expressions
} // namespace storm |
#include <iostream>
using namespace std;
int main() {
cout << "char: " << sizeof(char) << endl;
cout << "int: " << sizeof(int) << endl;
cout << "long: " << sizeof(long) << endl;
cout << "short :" << sizeof(short) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "double: " << sizeof(double) << endl;
cout << "bool: " << sizeof(bool) << endl;
return 0;
} |
package io.getgauge.spec;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Table</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link io.getgauge.spec.Table#getHeading <em>Heading</em>}</li>
* <li>{@link io.getgauge.spec.Table#getRows <em>Rows</em>}</li>
* </ul>
* </p>
*
* @see io.getgauge.spec.SpecPackage#getTable()
* @model
* @generated
*/
public interface Table extends EObject
{
/**
* Returns the value of the '<em><b>Heading</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Heading</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Heading</em>' containment reference.
* @see #setHeading(TableRow)
* @see io.getgauge.spec.SpecPackage#getTable_Heading()
* @model containment="true"
* @generated
*/
TableRow getHeading();
/**
* Sets the value of the '{@link io.getgauge.spec.Table#getHeading <em>Heading</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Heading</em>' containment reference.
* @see #getHeading()
* @generated
*/
void setHeading(TableRow value);
/**
* Returns the value of the '<em><b>Rows</b></em>' containment reference list.
* The list contents are of type {@link io.getgauge.spec.TableRow}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rows</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rows</em>' containment reference list.
* @see io.getgauge.spec.SpecPackage#getTable_Rows()
* @model containment="true"
* @generated
*/
EList<TableRow> getRows();
} // Table |
<html lang="en">
<head>
<title>FAQ 1-7 - Frequently Asked Questions</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Frequently Asked Questions">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="<API key>.html#<API key>" title="FAQ 1 - Installation FAQ">
<link rel="prev" href="FAQ-1_002d6.html#FAQ-1_002d6" title="FAQ 1-6">
<link href="http:
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<a name="FAQ-1-7"></a>
<a name="FAQ-1_002d7"></a>
<p>
Previous: <a rel="previous" accesskey="p" href="FAQ-1_002d6.html#FAQ-1_002d6">FAQ 1-6</a>,
Up: <a rel="up" accesskey="u" href="<API key>.html#<API key>">FAQ 1 - Installation FAQ</a>
<hr>
</div>
<h5 class="subsubheading">Question 1.7</h5>
<p>How do I run Gnus on both Emacs and XEmacs?
<h5 class="subsubheading">Answer</h5>
<p>You can't use the same copy of Gnus in both as the Lisp
files are byte-compiled to a format which is different
depending on which Emacs did the compilation. Get one copy
of Gnus for Emacs and one for XEmacs.
</body></html> |
<div ng-mouseup="stopDrag($event)" ng-mousemove="drag($event)" style="padding: 3px 0;">
<div style="width: 0; height: 0; overflow: visible; z-index: 2;">
<div style="width: 5px; height: 10px; border-radius: 5px; background-color: rgb(40, 40, 40); position: relative; cursor: ew-resize;"
ng-style="{'left': (position + 2) + 'px'}"
ng-mousedown="startDrag($event)" ng-mouseup="stopDrag($event)" ng-mousemove="drag($event)">
<div ng-show="dragging"
style="position: relative; top: 10px; left: -25px; background-color: rgba(40, 40, 40, 0.9); color: rgb(200, 200, 200); border-radius: 2px; padding: 4px 2px; font-family: monospace; font-size: 12px; text-align: center; width: 50px; line-height: 12px;">
{{ displayValue | number : 1 }}
</div>
</div>
</div>
<div style="width: calc(100% - 4px); height: 4px; border-radius: 2px; background-color: rgba(98, 98, 98, 0.3); margin: 3px 2px; z-index: 1;"
ng-mousedown="startDrag($event)"></div>
</div> |
'
' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
'
'
' *
' *
' *
' *
' *
' * Written by Doug Lea with assistance from members of JCP JSR-166
' * Expert Group and released to the public domain, as explained at
' * http://creativecommons.org/publicdomain/zero/1.0/
'
Namespace java.util.concurrent.atomic
''' <summary>
''' An {@code <API key>} maintains an object reference
''' along with a mark bit, that can be updated atomically.
'''
''' <p>Implementation note: This implementation maintains markable
''' references by creating internal objects representing "boxed"
''' [reference, boolean] pairs.
'''
''' @since 1.5
''' @author Doug Lea </summary>
''' @param <V> The type of object referred to by this reference </param>
Public Class <API key>(Of V)
Private Class Pair(Of T)
Friend ReadOnly reference As T
Friend ReadOnly mark As Boolean
Private Sub New( reference As T, mark As Boolean)
Me.reference = reference
Me.mark = mark
End Sub
Shared Function [of](Of T)( reference As T, mark As Boolean) As Pair(Of T)
Return New Pair(Of T)(reference, mark)
End Function
End Class
'JAVA TO VB CONVERTER TODO TASK: There is no VB equivalent to 'volatile':
Private pair_Renamed As Pair(Of V)
''' <summary>
''' Creates a new {@code <API key>} with the given
''' initial values.
''' </summary>
''' <param name="initialRef"> the initial reference </param>
''' <param name="initialMark"> the initial mark </param>
Public Sub New( initialRef As V, initialMark As Boolean)
pair_Renamed = Pair.of(initialRef, initialMark)
End Sub
''' <summary>
''' Returns the current value of the reference.
''' </summary>
''' <returns> the current value of the reference </returns>
Public Overridable Property reference As V
Get
Return pair_Renamed.reference
End Get
End Property
''' <summary>
''' Returns the current value of the mark.
''' </summary>
''' <returns> the current value of the mark </returns>
Public Overridable Property marked As Boolean
Get
Return pair_Renamed.mark
End Get
End Property
''' <summary>
''' Returns the current values of both the reference and the mark.
''' Typical usage is {@code boolean[1] holder; ref = v.get(holder); }.
''' </summary>
''' <param name="markHolder"> an array of size of at least one. On return,
''' {@code markholder[0]} will hold the value of the mark. </param>
''' <returns> the current value of the reference </returns>
Public Overridable Function [get]( markHolder As Boolean()) As V
Dim pair_Renamed As Pair(Of V) = Me.pair_Renamed
markHolder(0) = pair_Renamed.mark
Return pair_Renamed.reference
End Function
''' <summary>
''' Atomically sets the value of both the reference and mark
''' to the given update values if the
''' current reference is {@code ==} to the expected reference
''' and the current mark is equal to the expected mark.
'''
''' <p><a href="package-summary.html#weakCompareAndSet">May fail
''' spuriously and does not provide ordering guarantees</a>, so is
''' only rarely an appropriate alternative to {@code compareAndSet}.
''' </summary>
''' <param name="expectedReference"> the expected value of the reference </param>
''' <param name="newReference"> the new value for the reference </param>
''' <param name="expectedMark"> the expected value of the mark </param>
''' <param name="newMark"> the new value for the mark </param>
''' <returns> {@code true} if successful </returns>
Public Overridable Function weakCompareAndSet( expectedReference As V, newReference As V, expectedMark As Boolean, newMark As Boolean) As Boolean
Return compareAndSet(expectedReference, newReference, expectedMark, newMark)
End Function
''' <summary>
''' Atomically sets the value of both the reference and mark
''' to the given update values if the
''' current reference is {@code ==} to the expected reference
''' and the current mark is equal to the expected mark.
''' </summary>
''' <param name="expectedReference"> the expected value of the reference </param>
''' <param name="newReference"> the new value for the reference </param>
''' <param name="expectedMark"> the expected value of the mark </param>
''' <param name="newMark"> the new value for the mark </param>
''' <returns> {@code true} if successful </returns>
Public Overridable Function compareAndSet( expectedReference As V, newReference As V, expectedMark As Boolean, newMark As Boolean) As Boolean
Dim current As Pair(Of V) = pair_Renamed
Return expectedReference Is current.reference AndAlso expectedMark = current.mark AndAlso ((newReference Is current.reference AndAlso newMark = current.mark) OrElse casPair(current, Pair.of(newReference, newMark)))
End Function
''' <summary>
''' Unconditionally sets the value of both the reference and mark.
''' </summary>
''' <param name="newReference"> the new value for the reference </param>
''' <param name="newMark"> the new value for the mark </param>
Public Overridable Sub [set]( newReference As V, newMark As Boolean)
Dim current As Pair(Of V) = pair_Renamed
If newReference IsNot current.reference OrElse newMark <> current.mark Then Me.pair_Renamed = Pair.of(newReference, newMark)
End Sub
''' <summary>
''' Atomically sets the value of the mark to the given update value
''' if the current reference is {@code ==} to the expected
''' reference. Any given invocation of this operation may fail
''' (return {@code false}) spuriously, but repeated invocation
''' when the current value holds the expected value and no other
''' thread is also attempting to set the value will eventually
''' succeed.
''' </summary>
''' <param name="expectedReference"> the expected value of the reference </param>
''' <param name="newMark"> the new value for the mark </param> |
#ifndef PF_PCAP
#define PF_PCAP
#define PCAP_MAGIC 0xa1b2c3d4 /* the magic of the pcap global header (non swapped) */
#define PCAP_MAGIC_SWAPPED 0xd4c3b2a1 /* the magic of the pcap global header (non swapped) */
#define PCAPNG_MAGIC 0x0a0d0d0a /* the magic of the pcap global header (non swapped) */
#define PCAP_NSEC_MAGIC 0xa1b23c4d /* the magic of the pcap global header (nanoseconds - non swapped) */
#define PCAP_MAX_SNAPLEN 262144 /* the maximum snap length, should be 256K instead of 64K nowadays */
struct global_hdr_s {
u_int32_t magic_number; /* magic number */
u_int16_t version_major; /* major version number */
u_int16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
u_int32_t sigfigs; /* accuracy of timestamps */
u_int32_t snaplen; /* max length of captured packets, in octets */
u_int32_t network; /* data link type */
};
struct packet_hdr_s {
u_int32_t ts_sec; /* timestamp seconds */
u_int32_t ts_usec; /* timestamp microseconds */
u_int32_t incl_len; /* number of octets of packet saved in file */
u_int32_t orig_len; /* actual length of packet */
};
int is_plausible(struct global_hdr_s global_hdr, struct packet_hdr_s hdr, unsigned int prior_ts);
int check_header(char *buffer, unsigned int size, unsigned int prior_ts, struct global_hdr_s *global_hdr, struct packet_hdr_s *hdr);
int fix_pcap(FILE *pcap, FILE *pcap_fix);
int fix_pcap_packets(FILE *pcap, FILE *pcap_fix, off_t filesize, struct global_hdr_s global_hdr, unsigned short hdr_integ, char **writebuffer, off_t writepos);
#endif |
package com.berka.multiplanner.Models.Trips;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class From{
private List<Location> location;
public From(JSONObject object) throws JSONException
{
location = new ArrayList<Location>();
try
{
JSONArray array = object.getJSONArray("location");
for(int i = 0,q=0; i < array.length(); i++)
{
if(q > 7)
break;
try{
location.add(new Location(array.getJSONObject(i)));
q++;
}catch(Exception e)
{
//continue
}
}
}catch(JSONException e)
{
//object not array
location.add(new Location(object.getJSONObject("location")));
}
}
public List<Location> getLocation(){
return this.location;
}
public void setLocation(List<Location> location){
this.location = location;
}
} |
package org.patientview.radar.web.components;
import org.apache.wicket.Component;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.<API key>;
import org.apache.wicket.validation.IValidator;
import java.util.List;
// package private - use <API key> to access
class Radar<API key> extends PasswordTextField {
public Radar<API key>(String id, IValidator validator, boolean required,
WebMarkupContainer container, List<Component> componentsToUpdate) {
super(id);
init(id, container, validator, required, componentsToUpdate);
}
private void init(String id, WebMarkupContainer form, IValidator validator, boolean required,
List<Component> componentsToUpdate) {
if (validator != null) {
add(validator);
}
final <API key> feedbackPanel = new <API key>(id + "Feedback", this) {
@Override
public boolean isVisible() {
List<FeedbackMessage> feedbackMessages = getCurrentMessages();
for (FeedbackMessage feedbackMessage : feedbackMessages) {
if (feedbackMessage.getMessage().toString().contains("required")) {
return false;
}
}
return super.isVisible();
}
};
feedbackPanel.setOutputMarkupId(true);
feedbackPanel.<API key>(true);
form.add(feedbackPanel);
componentsToUpdate.add(feedbackPanel);
if (required) {
setRequired(true);
<API key> <API key> =
new <API key>(getId() + "FeedbackIndicator", this) {
@Override
public boolean isVisible() {
if (feedbackPanel.isVisible()) {
return false;
}
return super.isVisible();
}
};
form.add(<API key>);
<API key>.setOutputMarkupId(true);
<API key>.<API key>(true);
componentsToUpdate.add(<API key>);
}
}
} |
#include "fitz.h"
/* TODO: check if this works with 16bpp images */
enum { MAXC = 32 };
typedef struct fz_predict_s fz_predict;
struct fz_predict_s
{
fz_stream *chain;
int predictor;
int columns;
int colors;
int bpc;
int stride;
int bpp;
unsigned char *in;
unsigned char *out;
unsigned char *ref;
unsigned char *rp, *wp;
};
static inline int
getcomponent(unsigned char *buf, int x, int bpc)
{
switch (bpc)
{
case 1: return buf[x / 8] >> (7 - (x % 8)) & 0x01;
case 2: return buf[x / 4] >> ((3 - (x % 4)) * 2) & 0x03;
case 4: return buf[x / 2] >> ((1 - (x % 2)) * 4) & 0x0f;
case 8: return buf[x];
}
return 0;
}
static inline void
putcomponent(unsigned char *buf, int x, int bpc, int value)
{
switch (bpc)
{
case 1: buf[x / 8] |= value << (7 - (x % 8)); break;
case 2: buf[x / 4] |= value << ((3 - (x % 4)) * 2); break;
case 4: buf[x / 2] |= value << ((1 - (x % 2)) * 4); break;
case 8: buf[x] = value; break;
}
}
static inline int
paeth(int a, int b, int c)
{
/* The definitions of ac and bc are correct, not a typo. */
int ac = b - c, bc = a - c, abcc = ac + bc;
int pa = ABS(ac);
int pb = ABS(bc);
int pc = ABS(abcc);
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}
static void
fz_predicttiff(fz_predict *state, unsigned char *out, unsigned char *in, int len)
{
int left[MAXC];
int i, k;
for (k = 0; k < state->colors; k++)
left[k] = 0;
for (i = 0; i < state->columns; i++)
{
for (k = 0; k < state->colors; k++)
{
int a = getcomponent(in, i * state->colors + k, state->bpc);
int b = a + left[k];
int c = b % (1 << state->bpc);
putcomponent(out, i * state->colors + k, state->bpc, c);
left[k] = c;
}
}
}
static void
fz_predictpng(fz_predict *state, unsigned char *out, unsigned char *in, int len, int predictor)
{
int bpp = state->bpp;
int i;
unsigned char *ref = state->ref;
switch (predictor)
{
case 0:
memcpy(out, in, len);
break;
case 1:
for (i = bpp; i > 0; i
{
*out++ = *in++;
}
for (i = len - bpp; i > 0; i
{
*out = *in++ + out[-bpp];
out++;
}
break;
case 2:
for (i = bpp; i > 0; i
{
*out++ = *in++ + *ref++;
}
for (i = len - bpp; i > 0; i
{
*out++ = *in++ + *ref++;
}
break;
case 3:
for (i = bpp; i > 0; i
{
*out++ = *in++ + (*ref++) / 2;
}
for (i = len - bpp; i > 0; i
{
*out = *in++ + (out[-bpp] + *ref++) / 2;
out++;
}
break;
case 4:
for (i = bpp; i > 0; i
{
*out++ = *in++ + paeth(0, *ref++, 0);
}
for (i = len - bpp; i > 0; i
{
*out = *in++ + paeth(out[-bpp], *ref, ref[-bpp]);
ref++;
out++;
}
break;
}
}
static int
readpredict(fz_stream *stm, unsigned char *buf, int len)
{
fz_predict *state = stm->state;
unsigned char *p = buf;
unsigned char *ep = buf + len;
int ispng = state->predictor >= 10;
int n;
while (state->rp < state->wp && p < ep)
*p++ = *state->rp++;
while (p < ep)
{
n = fz_read(state->chain, state->in, state->stride + ispng);
if (n < 0)
return fz_rethrow(n, "read error in prediction filter");
if (n == 0)
return p - buf;
if (state->predictor == 1)
memcpy(state->out, state->in, n);
else if (state->predictor == 2)
fz_predicttiff(state, state->out, state->in, n);
else
{
fz_predictpng(state, state->out, state->in + 1, n - 1, state->in[0]);
memcpy(state->ref, state->out, state->stride);
}
state->rp = state->out;
state->wp = state->out + n - ispng;
while (state->rp < state->wp && p < ep)
*p++ = *state->rp++;
}
return p - buf;
}
static void
closepredict(fz_stream *stm)
{
fz_predict *state = stm->state;
fz_close(state->chain);
fz_free(state->in);
fz_free(state->out);
fz_free(state->ref);
fz_free(state);
}
fz_stream *
fz_openpredict(fz_stream *chain, fz_obj *params)
{
fz_predict *state;
fz_obj *obj;
state = fz_malloc(sizeof(fz_predict));
state->chain = chain;
state->predictor = 1;
state->columns = 1;
state->colors = 1;
state->bpc = 8;
obj = fz_dictgets(params, "Predictor");
if (obj)
state->predictor = fz_toint(obj);
if (state->predictor != 1 && state->predictor != 2 &&
state->predictor != 10 && state->predictor != 11 &&
state->predictor != 12 && state->predictor != 13 &&
state->predictor != 14 && state->predictor != 15)
{
fz_warn("invalid predictor: %d", state->predictor);
state->predictor = 1;
}
obj = fz_dictgets(params, "Columns");
if (obj)
state->columns = fz_toint(obj);
obj = fz_dictgets(params, "Colors");
if (obj)
state->colors = fz_toint(obj);
obj = fz_dictgets(params, "BitsPerComponent");
if (obj)
state->bpc = fz_toint(obj);
state->stride = (state->bpc * state->colors * state->columns + 7) / 8;
state->bpp = (state->bpc * state->colors + 7) / 8;
state->in = fz_malloc(state->stride + 1);
state->out = fz_malloc(state->stride);
state->ref = fz_malloc(state->stride);
state->rp = state->out;
state->wp = state->out;
memset(state->ref, 0, state->stride);
return fz_newstream(state, readpredict, closepredict);
} |
define(["myorder_view"], function(myorder_view) {
'use strict';
var MyOrderMatrixView = App.Views.FactoryView.extend({
name: 'myorder',
mod: 'matrix',
bindings: {
'.action_button': 'classes: {disabled: not(attributesSelected)}, text: select(ui_isAddMode, <API key>, <API key>)',
'.right-side': 'classes: {"no-images": <API key>}',
'.<API key>': 'updateContent: attrsViewData',
'.product_images': 'updateContent: imagesViewData',
'.product_title': 'updateContent: titleViewData',
'.product_desc': 'updateContent: descViewData',
'.quantity_info': 'updateContent: qtyViewData',
'.<API key>': 'updateContent: <API key>'
},
computeds: {
'attributesSelected': {
deps: ['<API key>', '<API key>'],
get: function() {
return this.getBinding('$product').check_selected();
}
},
imagesViewData: {
deps: ['<API key>', 'attributesSelected'],
get: function(hide_images) {
if (!hide_images) {
return {
name: 'Product',
mod: 'Images',
model: this.model.get_product(),
subViewIndex: 0
};
}
}
},
titleViewData: {
deps: ['attributesSelected'],
get: function() {
return {
name: 'Product',
mod: 'Title',
model: this.model,
product: this.model.get_product(),
subViewIndex: 1
};
}
},
attrsViewData: {
get: function() {
var product = this.model.get('product');
if(product && product.isParent()) {
return {
name: 'ModifiersClasses',
mod: 'Matrixes',
model: this.model,
subViewIndex: 2,
modifiersEl: this.$('.modifiers_info')
};
}
}
},
qtyViewData: {
deps: ['attributesSelected'],
get: function() {
return {
name: 'Quantity',
mod: this.model.get_product().get("sold_by_weight") ? 'Weight' : 'Main',
model: this.model,
subViewIndex: 3
};
}
},
descViewData: {
deps: ['<API key>', 'attributesSelected'],
get: function(<API key>) {
var product = this.model.get_product(),
index = 4;
if (!<API key> && product.get('description')) {
return {
name: 'Product',
mod: 'Description',
model: product,
subViewIndex: index
};
} else if (this.subViews[index]) {
this.subViews[index].remove();
}
}
},
<API key>: {
deps: ['<API key>'],
get: function(<API key>) {
if (<API key>) {
return {
name: 'Instructions',
mod: 'Modifiers',
model: this.model,
subViewIndex: 5
}
}
}
}
},
events: {
'click .action_button:not(.disabled)': addCb('action')
},
onEnterListeners: {
'.action_button:not(.disabled)': addCb('action')
}
});
var MyOrderItemView = App.Views.CoreMyOrderView.CoreMyOrderItemView.extend({
bindings: {
':el': 'classes: {"order-item": not(isServiceFee), "service-fee-item": isServiceFee}',
'.sub-box': 'classes: {"left-offset": not(<API key>)}',
'.name': 'classes: {"left-offset": select(isServiceFee, false, not(<API key>))}'
},
render: function() {
App.Views.CoreMyOrderView.CoreMyOrderItemView.prototype.render.apply(this, arguments);
var product = this.model.get_product(),
sold_by_weight = product.get('sold_by_weight'),
element = this.$('.qty-box');
if (sold_by_weight) {
element.addClass('weight-box');
}
var view = App.Views.GeneratorView.create('Quantity', {
el: element,
mod: sold_by_weight ? 'Weight' : 'Main',
model: this.model,
className: 'inline-block'
});
this.subViews.push(view);
this.applyBindings();
return this;
},
editItem: function() {
this.model.trigger('onItemEdit', this.model);
}
});
var MyOrderDiscountView = App.Views.CoreMyOrderView.<API key>.extend({
bindings: {
':el': 'classes: {"discount-item": true}'
}
});
var <API key> = App.Views.FactoryView.extend({
name: 'myorder',
mod: 'item_gift_card',
bindings: {
':el': 'classes: {"order-item": true, "giftcard-item": true, "primary-border": true}',
'.item-sum': 'text: format("+$1", currencyFormat(initial_price))',
'.logo': 'attr: {style: showLogo(<API key>)}',
'.card-type': 'text: product_name',
'.card-number': 'text: cardNumber'
},
bindingFilters: {
showLogo: function(url) {
if (typeof url != 'string') {
return '';
}
return 'background-image: url(%s);'.replace('%s', url);
}
},
computeds: {
cardNumber: {
deps: ['<API key>'],
get: function(card_number) {
return _loc.<API key> + ' ' + card_number;
}
}
},
events: {
'click .remove': "removeItem",
'click .edit': "editItem"
},
onEnterListeners: {
'.remove': "removeItem",
'.edit': "editItem"
},
initialize: function() {
_.extend(this.bindingSources, {
product: this.model.get_product()
});
App.Views.FactoryView.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'change', this.applyBindings, this);
},
editItem: function() {
this.model.trigger('onItemEdit', this.model);
},
removeItem: function() {
this.collection.remove(this.model);
}
});
var <API key> = <API key>.extend({
name: 'myorder',
mod: 'item_gift_card',
bindings: {
'.logo': 'classes: {"stanford-item": true}',
'.card-number': 'text: stanford_number'
},
initialize: function() {
_.extend(this.bindingSources, {
stanford: this.model.get('stanfordCard')
});
<API key>.prototype.initialize.apply(this, arguments);
}
});
var MyOrderListView = App.Views.CoreMyOrderView.CoreMyOrderListView.extend({
resolveItemMod: function(model) {
if (model.is_gift()) {
return App.Data.is_stanford_mode ? 'ItemStanfordCard' : 'ItemGiftCard';
} else {
return App.Views.CoreMyOrderView.CoreMyOrderListView.prototype.resolveItemMod.apply(this, arguments);
}
}
});
var <API key> = App.Views.FactoryView.extend({
name: 'myorder',
mod: 'stanford_reload',
bindings: {
'.card-view': 'updateContent: cardView',
'.stanford-plans-box': 'updateContent: plansView',
// initial_price can be only integer according Stanford card reload service limitation (Bug 30983)
'.initial-price': 'value: integer(int_price), events: ["input"], restrictInput: "0123456789.,", kbdSwitcher: "numeric", pattern: /^\\d*$/',
'.action_button': 'classes: {disabled: any(not(planId), not(int_price))}, text: select(ui_isAddMode, <API key>, <API key>)'
},
computeds: {
cardView: function() {
return {
name: 'StanfordCard',
mod: 'Reload',
model: this.options.stanford,
myorder: this.options.myorder
};
},
plansView: function() {
return {
name: 'StanfordCard',
mod: 'Plans',
collection: this.options.plans
};
},
// used in an input element because we need to change price in product to keep a correct item restoring from a storage during payment process
int_price: {
deps: ['product_price'],
get: function(price) {
return price;
},
set: function(value) {
value = parseInt(value) || 0;
this.setBinding('product_price', value);
}
}
},
events: {
'click .action_button:not(.disabled)': addCb('action')
},
onEnterListeners: {
'.action_button:not(.disabled)': addCb('action')
},
// override parent's update method to avoid re-rendering
update: new Function()
});
var <API key> = App.Views.FactoryView.extend({
name: 'myorder',
mod: 'item_customization',
bindings: {
':el': 'updateContent: viewData'
},
computeds: {
viewData: {
get: function() {
var product = this.model.get_product(),
data = _.extend({
subViewIndex: 0
}, this.options);
if (product.get('is_gift')) {
if (App.Data.is_stanford_mode) {
var stanford = this.model.get('stanfordCard');
return _.extend(data, {
name: 'MyOrder',
mod: 'StanfordReload',
model: this.model,
stanford: stanford,
plans: stanford.get('plans'),
product: this.model.get_product(),
className: '<API key> gift-card-reload'
});
} else {
return _.extend(data, {
name: 'Product',
mod: 'GiftCardReload',
model: product,
className: 'gift-card-reload'
});
}
} else {
return _.extend(data, {
name: 'MyOrder',
mod: 'Matrix',
model: this.model,
product: this.model.get('product')
});
}
}
}
},
events: {
'click .<API key>': addCb('back')
},
onEnterListeners: {
'.<API key>': addCb('back')
}
});
function addCb(prop) {
return function() {
var cb = this.options[prop];
typeof cb == 'function' && cb();
};
}
return new (require('factory'))(myorder_view.initViews.bind(myorder_view), function() {
App.Views.MyOrderView.MyOrderMatrixView = MyOrderMatrixView;
App.Views.MyOrderView.MyOrderItemView = MyOrderItemView;
App.Views.MyOrderView.<API key> = <API key>;
App.Views.MyOrderView.MyOrderDiscountView = MyOrderDiscountView;
App.Views.MyOrderView.<API key> = <API key>;
App.Views.MyOrderView.<API key> = <API key>;
App.Views.MyOrderView.MyOrderListView = MyOrderListView;
App.Views.MyOrderView.<API key> = <API key>;
});
}); |
.avatar {
border: 1px solid alpha (#000, 0.35);
border-radius: 50%;
box-shadow: inset 0 0 0 1px alpha (#fff, 0.05),
inset 0 1px 0 0 alpha (#fff, 0.45),
inset 0 -1px 0 0 alpha (#fff, 0.15),
0 1px 3px alpha (#000, 0.12),
0 1px 2px alpha (#000, 0.24);
}
<API key> {
border-radius: 0 0 4px 4px;
}
<API key>.window-frame {
border-radius: 4px;
}
.deck {
background-color: shade (@bg_color, 0.92);
}
.card {
background-color: #fff;
box-shadow: 0 1px 3px alpha (#000, 0.12),
0 1px 2px alpha (#000, 0.24);
}
.pathbar:focus {
box-shadow: inset 0 0 0 1px alpha (@colorAccent, 0.23),
0 1px 0 alpha (@bg_highlight_color, 0.30);
border-color: alpha (@colorAccent, 0.80);
}
.pathbar:active {
background-image: none;
background-color: transparent;
border-color: alpha (@colorAccent, 0.80);
box-shadow: inset 0 0 0 1px alpha (@colorAccent, 0.23);
}
.pathbar image,
.pathbar.image {
color: @<API key>;
}
.pathbar image:hover,
.pathbar.image:hover {
color: @<API key>;
}
dialog entry.pathbar,
<API key> .entry.pathbar {
background-image: linear-gradient(to bottom,
shade (@base_color, 0.93),
shade (@base_color, 0.97)
);
border-color: @border_color;
box-shadow: inset 0 1px 0 0 alpha (@inset_dark_color, 0.7),
inset 0 0 0 1px alpha (@inset_dark_color, 0.3),
0 1px 0 0 alpha (shade (@colorPrimary, 1.4), 0.50);
}
dialog entry.pathbar:focus,
<API key> .entry.pathbar:focus {
border-color: alpha (@colorAccent, 0.80);
box-shadow: inset 0 0 0 1px alpha (@colorAccent, 0.23),
0 1px 0 0 alpha (shade (@colorPrimary, 1.4), 0.50);
}
.gala-notification {
border: none;
border-radius: 4px;
background-color: transparent;
background-image: linear-gradient(to bottom,
@bg_color,
@bg_color 80%,
shade (@bg_color, 0.94)
);
box-shadow: inset 0 0 0 1px alpha (@bg_highlight_color, 0.10),
inset 0 1px 0 0 alpha (@bg_highlight_color, 0.90),
inset 0 -1px 0 0 alpha (@bg_highlight_color, 0.30),
0 0 0 1px alpha (#000, 0.20),
0 3px 6px alpha (#000, 0.16),
0 5px 5px -3px alpha (#000, 0.4);
}
.gala-notification .title,
.gala-notification .label {
color: @text_color;
}
.gala-notification GtkImage {
color: alpha (@text_color, 0.8);
}
.gala-button {
padding: 3px;
color: #fff;
border: none;
border-radius: 100px;
background-image: linear-gradient(to bottom,
#7e7e7e,
#3e3e3e
);
box-shadow: inset 0 0 0 1px alpha (#fff, 0.02),
inset 0 1px 0 0 alpha (#fff, 0.07),
inset 0 -1px 0 0 alpha (#fff, 0.01),
0 0 0 1px alpha (#000, 0.40),
0 3px 6px alpha (#000, 0.16),
0 3px 6px alpha (#000, 0.23);
text-shadow: 0 1px 1px alpha (#000, 0.6);
}
<API key> {
-<API key>: 1px;
-<API key>: 0;
}
<API key>.view.cell {
border-style: solid;
border-width: 0 0 1px 0;
border-color: alpha (#000, 0.2);
}
<API key>.view.cell:selected:focus {
border-style: solid;
border-width: 0 0 1px 0;
border-color: shade (@colorAccent, 0.8);
}
PantheonGreeter .avatar {
border-color: alpha (#000, 0.25);
box-shadow: inset 0 0 0 1px alpha (#fff, 0.05),
inset 0 1px 0 0 alpha (#fff, 0.45),
inset 0 -1px 0 0 alpha (#fff, 0.15),
0 1px 2px alpha (#000, 0.15),
0 2px 6px alpha (#000, 0.10);
}
PantheonGreeter .entry,
PantheonGreeter .entry:focus {
border-radius: 3.5px;
padding: 6px 3px;
background-image: linear-gradient(to bottom,
shade (@base_color, 0.93),
@base_color
);
border-color: alpha (@border_color, 0.75);
box-shadow: inset 0 1px 1px 0 alpha (#000, 0.20),
0 1px 0 alpha (#fff, 0.15);
}
PantheonGreeter .button.flat {
color: #fff;
text-shadow: 0 0 2px alpha (#000, 0.3),
0 1px 2px alpha (#000, 0.6);
icon-shadow: 0 0 2px alpha (#000, 0.3),
0 1px 2px alpha (#000, 0.6);
}
PantheonGreeter .button.text-button.suggested-action {
padding: 6px 32px;
border-radius: 3.5px;
border-color: rgba(0, 0, 0, 0.10);
box-shadow: inset 0 0 0 1px alpha (#fff, 0.05),
inset 0 1px 0 0 alpha (#fff, 0.45),
inset 0 -1px 0 0 alpha (#fff, 0.15),
0 1px 0 0 alpha (#fff, 0.15);
}
PantheonGreeter .button.text-button.suggested-action:active {
box-shadow: inset 0 0 0 1px alpha (#000, 0.05),
0 1px 0 0 alpha (#fff, 0.15);
}
NoiseLibraryWindow,
NoiseLibraryWindow .action-bar {
border-radius: 0 0 4px 4px;
}
NoiseLibraryWindow.window-frame {
border-radius: 3px;
}
.panel {
background-color: @panel_bg_color;
box-shadow: inset 0 1px 0 0 alpha (#fff, 0.20),
inset 0 -1px 0 0 alpha (#fff, 0.10),
0 0 1px 1px alpha (#000, 0.15);
border-bottom: 1px solid alpha (#000, 0.5);
transition: all 100ms ease-in-out;
}
.panel.maximized {
background-color: @panel_bg_color;
box-shadow: inset 0 -1px 2px 0 alpha (#000, 0.20),
inset 0 -1px 0 0 alpha (#000, 0.10);
border: none;
transition: all 100ms ease-in-out;
}
.<API key> > revealer label,
.<API key> > revealer image,
.<API key> > GtkRevealer {
font-family: 'Open Sans';
color: @panel_fg_color;
font-weight: bold;
text-shadow: none;
icon-shadow: none;
}
.panel.color-light .<API key> > revealer label,
.panel.color-light .<API key> > revealer image,
.panel.color-light .<API key> > GtkRevealer {
color: alpha (#000, 0.65);
text-shadow: 0 0 2px alpha (#fff, 0.3),
0 1px 0 alpha (#fff, 0.25);
icon-shadow: 0 0 2px alpha (#fff, 0.3),
0 1px 0 alpha (#fff, 0.25);
}
.checkerboard-layout {
background-color: #383e41;
}
.checkboard-layout .item {
background-color: #eee;
background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%, black),
linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%, black);
background-size:60px 60px;
background-position:0 0, 30px 30px
}
<API key> GtkIconView.cell:selected,
<API key> GtkIconView.cell:selected:focus {
background-color: alpha (#000, 0.20);
border-radius: 6px;
color: @text_color;
}
.hotcorner-display {
border-radius: 2px;
icon-shadow: 0 3px 4px alpha (#000, 0.20),
0 2px 2px alpha (#000, 0.30);
}
<API key>.background {
background-color: transparent;
} |
package net.sf.laja.template;
import net.sf.laja.SyntaxPrintable;
import net.sf.laja.SyntaxPrinter;
import net.sf.laja.TemplateParser.IBlock;
import net.sf.laja.TemplateParser.IElse;
public class Else implements IElse, SyntaxPrintable {
private Block block;
public void setBlock(IBlock iblock) {
this.block = (Block)iblock;
}
public Block getBlock() {
return block;
}
public void print(SyntaxPrinter printer) {
printer.printlnWithTabs("#else");
if (block != null) {
printer.tabForward();
block.print(printer);
printer.tabBackward();
}
}
} |
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
import warnings
warnings.warn("This module is deprecated and will go away in Zope 3.5. ",
DeprecationWarning, 2)
import sys
import warnings
from types import ClassType
from zope.component.interfaces import IRegistry, <API key>
from zope.component.bbb.interfaces import IAdapterService
from zope.component.bbb.service import GlobalService
from zope.component.registry import AdapterRegistration, <API key>
from zope.interface import implements, providedBy, Interface, implementedBy
from zope.interface.interfaces import IInterface
class <API key>(IAdapterService, IRegistry):
def register(required, provided, name, factory, info=''):
"""Register an adapter factory
:Parameters:
- `required`: a sequence of specifications for objects to be
adapted.
- `provided`: The interface provided by the adapter
- `name`: The adapter name
- `factory`: The object used to compute the adapter
- `info`: Provide some info about this particular adapter.
"""
def subscribe(required, provided, factory, info=''):
"""Register a subscriber factory
:Parameters:
- `required`: a sequence of specifications for objects to be
adapted.
- `provided`: The interface provided by the adapter
- `name`: The adapter name
- `factory`: The object used to compute the subscriber
- `info`: Provide some info about this particular adapter.
"""
class AdapterService(object):
"""Base implementation of an adapter service, implementing only the
`IAdapterService` interface.
No write-methods were implemented.
"""
implements(IAdapterService)
def __init__(self, sitemanager=None):
if sitemanager is None:
from zope.component.globalregistry import <API key>
sitemanager = <API key>()
self.sm = sitemanager
def __getattr__(self, name):
attr = getattr(self.sm.adapters, name)
if attr is not None:
return attr
raise AttributeError(name)
class <API key>(AdapterService, GlobalService):
"""Global Adapter Service implementation."""
implements(<API key>)
def __init__(self, sitemanager=None):
super(<API key>, self).__init__(sitemanager)
def register(self, required, provided, name, factory, info=''):
"""Register an adapter
registry = <API key>()
class R1(Interface):
pass
class R2(R1):
pass
class P1(Interface):
pass
class P2(P1):
pass
registry.register((R1, ), P2, 'bob', 'c1', 'd1')
registry.register((R1, ), P2, '', 'c2', 'd2')
registry.lookup((R2, ), P1, '')
'c2'
registrations = map(repr, registry.registrations())
registrations.sort()
for registration in registrations:
print registration
AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2')
AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1')
Let's make sure that we can also register regular classes for
adaptation.
class O1(object):
pass
class O2(object):
pass
class O3(object):
def __init__(self, obj1, obj2=None):
pass
registry.register((O1, ), R1, '', O3)
registry.queryAdapter(O1(), R1, '').__class__
<class 'zope.component.bbb.adapter.O3'>
registry.register((O1, O2), R1, '', O3)
registry.queryMultiAdapter((O1(), O2()), R1, '').__class__
<class 'zope.component.bbb.adapter.O3'>
"""
self.sm.provideAdapter(required, provided, name, factory, info)
def subscribe(self, required, provided, factory, info=''):
"""Register an subscriptions adapter
registry = <API key>()
class R1(Interface):
pass
class R2(R1):
pass
class P1(Interface):
pass
class P2(P1):
pass
registry.subscribe((R1, ), P2, 'c1', 'd1')
registry.subscribe((R1, ), P2, 'c2', 'd2')
subscriptions = map(str, registry.subscriptions((R2, ), P1))
subscriptions.sort()
subscriptions
['c1', 'c2']
registrations = map(repr, registry.registrations())
registrations.sort()
for registration in registrations:
print registration
<API key>(('R1',), 'P2', 'c1', 'd1')
<API key>(('R1',), 'P2', 'c2', 'd2')
"""
self.sm.subscribe(required, provided, factory, info)
def registrations(self):
for registration in self.sm.registrations():
if isinstance(registration,
(AdapterRegistration, <API key>)):
yield registration |
# Our friend Monk has an exam that has quite weird rules. Each question has a difficulty level in the form of an
# Integer. Now, Monk can only solve the problems that have difficulty level less than X . Now the rules are-
# Score of the student is equal to the maximum number of answers he/she has attempted without skipping a question.
# Student is allowed to skip just "one" question that will not be counted in the continuity of the questions.
# Note- Assume the student knows the solution to the problem he/she attempts and always starts the paper from first
# question.
# Given the number of Questions, N ,the maximum difficulty level of the problem Monk can solve , X ,and the difficulty
# level of each question, Ai can you help him determine his maximum score?
# Input Format
# First Line contains Integer N , the number of questions and the maximum difficulty X Monk can solve.
# Next line contains N integers, Ai denoting the difficulty level of each question.
# Output Format
# Maximum score Monk can achieve in the exam.
# Constraints
# SAMPLE INPUT
# 7 6
# 4 3 7 6 7 2 2
# SAMPLE OUTPUT
n, x = map(int, input().split())
questions = input().split()
count = 0
skip = 0
for i in range(n):
if int(questions[i]) > x:
skip += 1
else:
if skip == 2:
break
count += 1
print(count) |
<?php
defined('_JEXEC') or die;
/**
* View class for a list of documents.
*
* @package Projectlog.Administrator
* @subpackage com_projectlog
* @since 3.3.1
*/
class ProjectlogViewDocs extends JViewLegacy
{
protected $items;
protected $pagination;
protected $state;
/**
* Display the view
*
* @return void
*
* @since 3.3.1
*/
public function display($tpl = null)
{
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
ProjectlogHelper::addSubmenu('docs');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode("\n", $errors));
return false;
}
// Preprocess the list of items to find ordering divisions.
// TODO: Complete the ordering stuff with nested sets
foreach ($this->items as &$item)
{
$item->order_up = true;
$item->order_dn = true;
}
$this->addToolbar();
$this->sidebar = JHtmlSidebar::render();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @since 3.3.1
*/
protected function addToolbar()
{
require_once JPATH_COMPONENT .'/models/fields/modal/project.php';
$this->projectfield = new <API key>();
$canDo = ProjectlogHelper::getActions('com_projectlog', 'project', $this->state->get('filter.project_id'));
$user = JFactory::getUser();
// Get the toolbar object instance
$bar = JToolBar::getInstance('toolbar');
JToolbarHelper::title(JText::_('<API key>'), 'list doc');
if ($canDo->get('projectlog.createdoc') || (count($user->get<API key>('com_projectlog', 'core.create'))) > 0)
{
JToolbarHelper::addNew('doc.add');
}
if (($canDo->get('projectlog.editdoc')) || ($canDo->get('projectlog.editdoc.own')))
{
JToolbarHelper::editList('doc.edit');
}
if ($canDo->get('projectlog.editdoc.state'))
{
JToolbarHelper::publish('docs.publish', 'JTOOLBAR_PUBLISH', true);
JToolbarHelper::unpublish('docs.unpublish', 'JTOOLBAR_UNPUBLISH', true);
JToolbarHelper::archiveList('docs.archive');
JToolbarHelper::checkin('docs.checkin');
}
if ($this->state->get('filter.published') == -2 && $canDo->get('projectlog.deletedoc'))
{
JToolbarHelper::deleteList('', 'docs.delete', '<API key>');
}
elseif ($canDo->get('projectlog.editdoc.state'))
{
JToolbarHelper::trash('docs.trash');
}
// Add a batch button
if ($user->authorise('core.create', 'com_projectlog') && $user->authorise('core.edit', 'com_projectlog') && $user->authorise('core.edit.state', 'com_projectlog'))
{
JHtml::_('bootstrap.modal', 'collapseModal');
$title = JText::_('JTOOLBAR_BATCH');
// Instantiate a new JLayoutFile instance and render the batch button
$layout = new JLayoutFile('joomla.toolbar.batch');
$dhtml = $layout->render(array('title' => $title));
$bar->appendButton('Custom', $dhtml, 'batch');
}
if ($user->authorise('core.admin', 'com_projectlog'))
{
JToolbarHelper::preferences('com_projectlog');
}
JHtmlSidebar::setAction('index.php?option=com_projectlog');
JHtmlSidebar::addFilter(
JText::_('<API key>'),
'filter_published',
JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), 'value', 'text', $this->state->get('filter.published'), true)
);
JHtmlSidebar::addFilter(
JText::_('<API key>'),
'filter_language',
JHtml::_('select.options', JHtml::_('contentlanguage.existing', true, true), 'value', 'text', $this->state->get('filter.language'))
);
}
/**
* Returns an array of fields the table can be sorted by
*
* @return array Array containing the field name to sort by as the key and display text as value
*
* @since 3.3.1
*/
protected function getSortFields()
{
return array(
'a.ordering' => JText::_('<API key>'),
'a.published' => JText::_('JSTATUS'),
'a.title' => JText::_('JGLOBAL_TITLE'),
'project_name' => JText::_('<API key>'),
'a.language' => JText::_('<API key>'),
'a.id' => JText::_('JGRID_HEADING_ID')
);
}
} |
package com.nixmash.blog.jpa.dto;
import java.io.Serializable;
public class AlphabetDTO implements Serializable {
private static final long serialVersionUID = -<API key>;
private String alphaCharacter;
private Boolean isActive;
public AlphabetDTO() {}
public AlphabetDTO(String alphaCharacter, Boolean isActive) {
this.alphaCharacter = alphaCharacter;
this.isActive = isActive;
}
public String getAlphaCharacter() {
return alphaCharacter;
}
public void setAlphaCharacter(String alphaCharacter) {
this.alphaCharacter = alphaCharacter;
}
public Boolean getActive() {
return isActive;
}
public void setActive(Boolean active) {
isActive = active;
}
} |
#ifndef __GRAPHICS_H__
#define __GRAPHICS_H__
extern "C" {
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
}
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <map>
#include "point.h"
class XGraphics {
private:
bool initialized;
Display *display;
int screen_num;
unsigned int display_width, display_height;
XEvent report;
GC gc;
Window win;
int border_width;
unsigned int width, height;
XFontStruct * font;
Colormap screen_colormap;
std::map<std::string, int> color_list;
int line_thickness;
float scale;
Point2d<float> translate;
public:
XGraphics();
XGraphics(int w, int h, float s, const Point2d<float>& t);
~XGraphics();
void initialize(int w, int h, float s, const Point2d<float>& t);
int get_color(std::string c);
int get_rgb_color(double r, double g, double b);
void flush();
void list_fonts();
void setup_font();
//returns the vector to ADD to your vector such that the first character
//starts exactly on your point
Point2d<int> text_offset_left(const std::string& S);
//returns the vector to ADD to your vector such that the center of the
//text extents gets placed directly over your vector
Point2d<int> text_offset_center(const std::string& S);
void erase_field();
Point2d<int> mouse_location();
void draw_point(const Point2d<int>& p, long col);
void draw_point(const Point2d<float>& p, long col);
void draw_dot(const Point2d<int>& p, long col);
void draw_box(const Point2d<int>& p, int w, long col);
void draw_line(const Point2d<int>& p1, const Point2d<int>& p2, long col);
void draw_line(const Point2d<float>& p1, const Point2d<float>& p2, long col);
void draw_line(const Point2d<float>& p1, const Point2d<float>& p2, long col, int thickness);
void <API key>(const Point2d<float>& p1,
const Point2d<float>& p2,
long col,
int thickness,
const std::string& label);
void draw_square(int x, int y, int z, long col);
void draw_rectangle(int x, int y, int zx, int zy, long col);
void <API key>(int x, int y, int zx, int zy, long col);
void <API key>(const Point2d<int>& p, int w, int h, long col);
void draw_filled_polygon(const std::vector<Point2d<float> >& points, int col);
void draw_box_radius(Point2d<float>& center, float radius, long col);
void draw_faint_line(const Point2d<int>& p1, const Point2d<int>& p2, long col);
void erase_circle(const Point2d<int>& p, int r);
void draw_circle(const Point2d<int>& p, int r, long col);
void draw_circle(const Point2d<float>& p, int r, long col);
void draw_disk(const Point2d<int>& p, double r, long col);
void <API key>(const Point2d<int>& p, int r, long col);
void draw_path(const std::vector<Point2d<int> >& L, long col);
void draw_text(const Point2d<int>& p, std::stringstream &T, long col);
void draw_text(const Point2d<int>& p, std::string &S, long col);
void draw_text(const Point2d<float>& p, std::string &S, long col);
void draw_text_centered(const Point2d<float>& p, const std::string &S, long col);
void draw_label(const Point2d<int>& p, int i, long col);
std::string wait_for_key();
void get_next_event(XEvent& xe);
};
#endif |
define(['models/DataStorage'], function(DataStorage) {
'use strict';
/**
* HTML5 Audio player.
* @type {HTMLAudioElement}
*/
var _audio;
/**
* Attach event handler to player.
* @param {string} name
* @param {function} callback
*/
function attachEvent(name, callback) {
switch (name) {
case 'play':
case 'playing':
case 'abort':
case 'volumechange':
_audio.addEventListener(name, callback);
break;
case 'error':
_audio.addEventListener('error', callback);
_audio.addEventListener('stalled', callback);
break;
default:
console.warn('Unsupported event type', name);
}
}
/**
* Start playing.
* @param {string=} url Stream (or file) url.
*/
function play(url) {
url = url || _audio.src;
_audio.src = url;
_audio.play().catch(function() {
// pass
});
}
/**
* Stop playing.
*/
function stop() {
_audio.pause();
_audio.src = '';
}
/**
* Set player volume.
* @param {number} volume Volume value from 0 to 100.
*/
function setVolume(volume) {
_audio.volume = (volume / 100).toFixed(2);
}
/**
* Get player volume.
* @return {number}
*/
function getVolume() {
return Math.round(_audio.volume * 100);
}
/**
* Is playing now?
* @return {boolean}
*/
function isPlaying() {
return !_audio.paused && !_audio.ended && (_audio.readyState === 4 || _audio.networkState === 2);
}
/**
* Get audio data for equalizer.
* @return {Uint8Array}
*/
function getAudioData() {
var getAudioAnalyser = function() {
var context = new window.AudioContext();
var analyser = context.createAnalyser();
analyser.<API key> = 0.8;
analyser.fftSize = 128;
var source = context.<API key>(_audio);
source.connect(analyser);
analyser.connect(context.destination);
return analyser;
}.bind(this);
this._audioAnalyser = this._audioAnalyser || getAudioAnalyser();
var freqByteData = new Uint8Array(this._audioAnalyser.frequencyBinCount);
this._audioAnalyser.<API key>(freqByteData);
return freqByteData;
}
/**
* Init player.
*/
function init() {
_audio = new Audio();
_audio.preload = 'auto';
_audio.crossOrigin = 'anonymous';
setVolume(DataStorage.getVolume());
}
/**
* @typedef {{}} HtmlPlayer
*/
return {
init: init,
attachEvent: attachEvent,
play: play,
stop: stop,
setVolume: setVolume,
getVolume: getVolume,
isPlaying: isPlaying,
getAudioData: getAudioData
};
}); |
// modifyed by osilloscopion (2 Jul 2016)
#pragma once
#include "common.h"
void NTR_CmdReset(void);
u32 NTR_CmdGetCartId(void);
void <API key>(void);
void NTR_CmdReadHeader (void* buffer);
void NTR_CmdReadData (u32 offset, void* buffer);
bool NTR_Secure_Init (u8* buffer, u32 CartID); |
Joomla 2.5.28 = <API key>
Joomla 2.5.7 = <API key>
Joomla 3.3.3 = <API key>
Joomla 3.6.4 = <API key>
Joomla 3.2.1 = <API key>
Joomla 2.5.0 = <API key>
Joomla 3.4.8 = <API key>
Joomla 3.5.1 = <API key>
Joomla 3.7.0 = <API key>
Joomla 2.5.9 = <API key>
Joomla 3.7.3 = <API key>
Joomla 3.0.2 = <API key> |
<?php
namespace Gerh\Evecorp\Domain\Repository;
class <API key> extends ApiKeyRepository
{
} |
# 3. Ubuntu 16.04 as Server OS
Date: 2017-11-04
## Status
Accepted
## Context
We need to select a base operating system to install on all virtual machines that form
the Datalabs environment. There are three choices available through the JASIMN portal
Ubuntu 14.04, Ubuntu 16.04 and CentOS 6.9.
## Decision
We have selected Ubuntu 16.04 as the base operating system for our servers for several
reasons:
* The team are more familiar with Ubuntu over CentOS.
* Packages are likely to be more easily available on Ubuntu.
* CentOS 6.9 is no longer being updated (last update 10/5/2017).
* Ubuntu 16.04 will be supported for far longer. 14.04 end of life is early 2019.
## Consequences
The main consequence of this decision is that the development workstations are running
CentOS 7 rather than Ubuntu so we will see differences between the environments. This is
not expected to be a significant issue as we have plenty of JASMIN resource available to
create test servers as required and expect that most of the deployed software will be
containerised allowing easy testing on development machines. |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:06:09 MSK 2012 -->
<TITLE>
Uses of Class org.apache.poi.xslf.usermodel.XSLFTableCell (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-03-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.xslf.usermodel.XSLFTableCell (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/xslf/usermodel/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="XSLFTableCell.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.xslf.usermodel.XSLFTableCell</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.xslf.usermodel"><B>org.apache.poi.xslf.usermodel</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.xslf.usermodel"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A> in <A HREF="../../../../../../org/apache/poi/xslf/usermodel/package-summary.html">org.apache.poi.xslf.usermodel</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/xslf/usermodel/package-summary.html">org.apache.poi.xslf.usermodel</A> that return <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A></CODE></FONT></TD>
<TD><CODE><B>XSLFTableRow.</B><B><A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableRow.html#addCell()">addCell</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/xslf/usermodel/package-summary.html">org.apache.poi.xslf.usermodel</A> that return types with arguments of type <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A>></CODE></FONT></TD>
<TD><CODE><B>XSLFTableRow.</B><B><A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableRow.html#getCells()">getCells</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.Iterator<<A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel">XSLFTableCell</A>></CODE></FONT></TD>
<TD><CODE><B>XSLFTableRow.</B><B><A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableRow.html#iterator()">iterator</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/xslf/usermodel/XSLFTableCell.html" title="class in org.apache.poi.xslf.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/xslf/usermodel/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="XSLFTableCell.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML> |
<?php
namespace RevenantBlue\Admin;
use RevenantBlue;
use \PDO;
class Tags extends RevenantBlue\Db {
public $whiteList = array('id', 'tagId', 'tag_name', 'tag_alias', 'tag_description', 'tag_id', 'article_id', 'popularity');
private $tagsTable;
private $articleTagsTable;
public function __construct() {
$this->tagsTable = PREFIX . 'tags';
$this->articleTagsTable = PREFIX . 'article_tags';
}
public function loadTags($limit, $offset, $orderBy, $sort) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT *, t.id AS tagId, COUNT(*) - 1 AS popularity
FROM $this->tagsTable AS t
LEFT JOIN $this->articleTagsTable AS ats ON t.id = ats.tag_id
GROUP BY t.id
ORDER BY $orderBy $sort
LIMIT :limit
OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function countTags() {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->tagsTable");
$stmt->execute();
return $stmt->rowCount();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function <API key>($limit) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT DISTINCT *, t.id AS tagId, count(ats.tag_id) - 1 AS popularity FROM $this->tagsTable AS t
LEFT JOIN $this->articleTagsTable AS ats ON t.id = ats.tag_id
WHERE ats.article_id != ''
GROUP BY t.id
ORDER BY popularity DESC
LIMIT :limit");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function loadTagSearch($limit, $offset, $searchWord, $orderBy, $sort) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT *, t.id AS tagId, COUNT(*) - 1 AS popularity
FROM $this->tagsTable AS t
LEFT JOIN $this->articleTagsTable AS ats ON t.id = ats.tag_id
WHERE tag_name LIKE :searchWord
GROUP BY t.id
ORDER BY $orderBy $sort
LIMIT :limit
OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':searchWord', '%' . $searchWord . '%', PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function countTagSearch($searchWord) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->tagsTable
WHERE tag_name LIKE :searchWord");
$stmt->bindValue(':searchWord', '%' . $searchWord . '%', PDO::PARAM_STR);
$stmt->execute();
return $stmt->rowCount();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function loadTag($tagId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->tagsTable WHERE tag_id = :tagId");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function insertTag($tagName, $tagAlias, $tagDescription) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("INSERT INTO $this->tagsTable (tag_name, tag_alias, tag_description) VALUES (:tagName, :tagAlias, :tagDescription)");
$stmt->bindParam(':tagName', $tagName, PDO::PARAM_STR);
$stmt->bindParam(':tagAlias', $tagAlias, PDO::PARAM_STR);
$stmt->bindParam(':tagDescription', $tagDescription, PDO::PARAM_STR);
$stmt->execute();
return self::$dbh->lastInsertId();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function insertArticleTag($tagId, $articleId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("INSERT INTO $this->articleTagsTable (tag_id, article_id) VALUES (:tagId, :articleId)");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->bindParam(':articleId', $articleId, PDO::PARAM_INT);
$stmt->execute();
return self::$dbh->lastInsertId();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function updateTag($tagId, $tagName, $tagAlias, $tagDescription) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("UPDATE $this->tagsTable
SET tag_name = :tagName, tag_alias = :tagAlias, tag_description = :tagDescription
WHERE id = :tagId");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->bindParam(':tagName', $tagName, PDO::PARAM_STR);
$stmt->bindParam(':tagAlias', $tagAlias, PDO::PARAM_STR);
$stmt->bindParam(':tagDescription', $tagDescription, PDO::PARAM_STR);
$stmt->execute();
return $stmt->rowCount();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function deleteTag($tagId) {
try {
if(!self::$dbh) $this->connect();
self::$dbh->beginTransaction();
$stmt = self::$dbh->prepare("DELETE FROM $this->tagsTable WHERE id = :tagId");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->execute();
$stmt2 = self::$dbh->prepare("DELETE FROM $this->articleTagsTable WHERE tag_id = :tagId");
$stmt2->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt2->execute();
return self::$dbh->commit();
} catch(PDOException $e) {
self::$dbh->rollBack();
$this->errorLog($e);
}
}
public function deleteArticleTag($tagId, $articleId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("DELETE FROM $this->articleTagsTable WHERE tag_id = :tagId AND article_id = :articleId");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->bindParam(':articleId', $articleId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->rowCount();
} catch(PDOException $e) {
self::$dbh->rollBack();
$this->errorLog($e);
}
}
public function getTagByName($tagName) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->tagsTable WHERE tag_name = :tagName");
$stmt->bindParam(':tagName', $tagName, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function getTagByAlias($tagAlias) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->tagsTable WHERE tag_alias = :tagAlias");
$stmt->bindParam(':tagAlias', $tagAlias, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function getTagsForArticle($articleId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT *, t.tag_name FROM $this->articleTagsTable AS ats
RIGHT JOIN $this->tagsTable AS t ON ats.tag_id = t.id
WHERE article_id = :articleId");
$stmt->bindParam(':articleId', $articleId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function <API key>($articleId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT t.tag_name FROM $this->articleTagsTable AS ats
RIGHT JOIN $this->tagsTable AS t ON ats.tag_id = t.id
WHERE article_id = :articleId");
$stmt->bindParam(':articleId', $articleId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function getTagIdByName($tagName) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT id FROM $this->tagsTable WHERE tag_name = :tagName");
$stmt->bindParam(':tagName', $tagName, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result['id'];
} catch(PDOException $e) {
$this->errorLog($e);
}
}
public function <API key>($tagId) {
try {
if(!self::$dbh) $this->connect();
$stmt = self::$dbh->prepare("SELECT * FROM $this->articleTagsTable WHERE tag_id = :tagId");
$stmt->bindParam(':tagId', $tagId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->rowCount();
} catch(PDOException $e) {
$this->errorLog($e);
}
}
} |
from scapy.all import *
from veripy.assertions import *
from veripy.models import ComplianceTestCase
class <API key>(ComplianceTestCase):
"""
Stub Fragment Header
Verify that a node accepts the offset zero fragment with the More
Fragments flag clear.
@private
Source: IPv6 Ready Phase-1/Phase-2 Test Specification Core
Protocols (v6LC.1.3.4)
"""
def run(self):
self.logger.info("Sending an IPv6 packet header with an offset zero fragment and cleared More Fragments flag.")
self.node(1).send( \
IPv6(src=str(self.node(1).global_ip()), dst=str(self.target(1).global_ip()), nh=44)/
IPv6ExtHdrFragment(offset=0, m=0, nh=58)/
ICMPv6EchoRequest(seq=self.next_seq()))
self.logger.info("Checking for a reply...")
r1 = self.node(1).received(src=self.target(1).global_ip(), seq=self.seq(), type=ICMPv6EchoReply)
assertEqual(1, len(r1), "expected to receive an ICMPv6 Echo Reply")
assertNotHasLayer(IPv6ExtHdrFragment, r1[0], "did not expect the Echo Reply to contain a fragment header") |
package br.com.ezzysoft.restaurante.entidade;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "combinado")
public class Combinado implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;
@Column(name = "nome")
private String nome;
@ManyToMany(fetch = FetchType.EAGER)
private List<Produto> produtos = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<Produto> getProdutos() {
return produtos;
}
public void setProdutos(List<Produto> produtos) {
this.produtos = produtos;
}
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "<API key>.h"
#include <gnuradio/io_signature.h>
#include <boost/format.hpp>
namespace gr {
namespace blocks {
ctrlport_probe2_c::sptr ctrlport_probe2_c::make(const std::string& id,
const std::string& desc,
int len,
unsigned int disp_mask)
{
return gnuradio::make_block_sptr<<API key>>(id, desc, len, disp_mask);
}
<API key>::<API key>(const std::string& id,
const std::string& desc,
int len,
unsigned int disp_mask)
: sync_block("probe2_c",
io_signature::make(1, 1, sizeof(gr_complex)),
io_signature::make(0, 0, 0)),
d_id(id),
d_desc(desc),
d_len(len),
d_disp_mask(disp_mask)
{
set_length(len);
}
<API key>::~<API key>() {}
void <API key>::forecast(int noutput_items,
gr_vector_int& <API key>)
{
// make sure all inputs have noutput_items available
unsigned ninputs = <API key>.size();
for (unsigned i = 0; i < ninputs; i++)
<API key>[i] = d_len;
}
std::vector<gr_complex> <API key>::get() { return buffered_get.get(); }
void <API key>::set_length(int len)
{
gr::thread::scoped_lock guard(d_setlock);
if (len > 8191) {
GR_LOG_WARN(d_logger,
boost::format("probe2_c: length %1% exceeds maximum"
" buffer size of 8191") %
len);
len = 8191;
}
d_len = len;
d_buffer.resize(d_len);
d_index = 0;
}
int <API key>::length() const { return (int)d_len; }
int <API key>::work(int noutput_items,
<API key>& input_items,
gr_vector_void_star& output_items)
{
const gr_complex* in = (const gr_complex*)input_items[0];
gr::thread::scoped_lock guard(d_setlock);
// copy samples to get buffer if we need samples
if (d_index < d_len) {
// copy smaller of remaining buffer space and num inputs to work()
int num_copy = std::min((int)(d_len - d_index), noutput_items);
memcpy(&d_buffer[d_index], in, num_copy * sizeof(gr_complex));
d_index += num_copy;
}
// notify the waiting get() if we fill up the buffer
if (d_index == d_len) {
buffered_get.offer_data(d_buffer);
d_index = 0;
}
return noutput_items;
}
void <API key>::setup_rpc()
{
#ifdef GR_CTRLPORT
int len = static_cast<int>(d_len);
d_rpc_vars.emplace_back(
new <API key><ctrlport_probe2_c, std::vector<std::complex<float>>>(
alias(),
d_id.c_str(),
&ctrlport_probe2_c::get,
pmt::mp(-2),
pmt::mp(2),
pmt::mp(0),
"volts",
d_desc.c_str(),
RPC_PRIVLVL_MIN,
d_disp_mask | DISPOPTCPLX));
d_rpc_vars.emplace_back(
new <API key><ctrlport_probe2_c, int>(alias(),
"length",
&ctrlport_probe2_c::length,
pmt::mp(1),
pmt::mp(10 * len),
pmt::mp(len),
"samples",
"get vector length",
RPC_PRIVLVL_MIN,
DISPNULL));
d_rpc_vars.emplace_back(
new <API key><ctrlport_probe2_c, int>(alias(),
"length",
&ctrlport_probe2_c::set_length,
pmt::mp(1),
pmt::mp(10 * len),
pmt::mp(len),
"samples",
"set vector length",
RPC_PRIVLVL_MIN,
DISPNULL));
#endif /* GR_CTRLPORT */
}
} /* namespace blocks */
} /* namespace gr */ |
#include <linux/dvb/frontend.h>
#include "dvb_frontend.h"
static int stb6100_get_freq(struct dvb_frontend *fe, u32 *frequency)
{
struct dvb_frontend_ops *frontend_ops = &fe->ops;
struct dvb_tuner_ops *tuner_ops = &frontend_ops->tuner_ops;
int err = 0;
if (tuner_ops->get_frequency)
{
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 1);
}
err = tuner_ops->get_frequency(fe, frequency);
if (err < 0)
{
printk("%s: Invalid parameter\n", __func__);
return err;
}
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 0);
}
}
return 0;
}
static int stb6100_set_freq(struct dvb_frontend *fe, u32 frequency)
{
struct dvb_frontend_ops *frontend_ops = &fe->ops;
struct dvb_tuner_ops *tuner_ops = &frontend_ops->tuner_ops;
struct <API key> *c = &fe->dtv_property_cache;
u32 bw = c->bandwidth_hz;
int err = 0;
c->frequency = frequency;
c->bandwidth_hz = 0; /* Don't adjust the bandwidth */
if (tuner_ops->set_params)
{
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 1);
}
err = tuner_ops->set_params(fe);
c->bandwidth_hz = bw;
if (err < 0)
{
printk("%s: Invalid parameter\n", __func__);
return err;
}
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 0);
}
}
return 0;
}
static int stb6100_get_bandw(struct dvb_frontend *fe, u32 *bandwidth)
{
struct dvb_frontend_ops *frontend_ops = &fe->ops;
struct dvb_tuner_ops *tuner_ops = &frontend_ops->tuner_ops;
int err = 0;
if (tuner_ops->get_bandwidth)
{
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 1);
}
err = tuner_ops->get_bandwidth(fe, bandwidth);
if (err < 0)
{
printk(KERN_ERR "%s: Invalid parameter\n", __func__);
return err;
}
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 0);
}
}
return 0;
}
static int stb6100_set_bandw(struct dvb_frontend *fe, u32 bandwidth)
{
struct dvb_frontend_ops *frontend_ops = &fe->ops;
struct dvb_tuner_ops *tuner_ops = &frontend_ops->tuner_ops;
struct <API key> *c = &fe->dtv_property_cache;
u32 freq = c->frequency;
int err = 0;
c->bandwidth_hz = bandwidth;
c->frequency = 0; /* Don't adjust the frequency */
if (tuner_ops->set_params)
{
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 1);
}
err = tuner_ops->set_params(fe);
c->frequency = freq;
if (err < 0)
{
printk(KERN_ERR "%s: Invalid parameter\n", __func__);
return err;
}
if (frontend_ops->i2c_gate_ctrl)
{
frontend_ops->i2c_gate_ctrl(fe, 0);
}
}
return 0;
} |
package cwe.scala.library.math
import cwe.scala.library.boxes._
import cwe.scala.library.math.bignumbers.Integer
import cwe.scala.library.math.bignumbers.Natural
class PositiveRational[T] (numerator: T, denominator: T)(implicit nBox: Numeric[T])
extends Rational[T](if(nBox.smaller(numerator, nBox.zero)) throw new <API key>("numerator should be positive or null") else numerator,
denominator) {}
object PositiveRational {
def ZERO = MathServiceProvider.<API key>.ZERO
def ONE = MathServiceProvider.<API key>.ONE
def create(n: Int, d: Int): PositiveRational[Int] = MathServiceProvider.<API key>(n, d)
def create(n: Long, d: Long): PositiveRational[Long] = MathServiceProvider.<API key>(n, d)
def create(n: Integer, d: Integer): PositiveRational[Integer] = MathServiceProvider.<API key>(n, d)
def create(n: Natural, d: Natural): PositiveRational[Natural] = MathServiceProvider.<API key>(n, d)
def create(n: Int): PositiveRational[Int] = MathServiceProvider.<API key>(n, 1)
def create(n: Long): PositiveRational[Long] = MathServiceProvider.<API key>(n, 1)
def create(n: Integer): PositiveRational[Integer] = MathServiceProvider.<API key>(n, Integer.ONE)
def create(n: Natural): PositiveRational[Natural] = MathServiceProvider.<API key>(n, Natural.ONE)
def create[T](n: T, d: T)(implicit nBox: Numeric[T]): PositiveRational[T] = MathServiceProvider.<API key>(n, d)(nBox)
} |
#!/home/bjs66/anaconda2/bin/python2.7
import h5py
import numpy as np
import easyfit as ef
import datetime
import pytz
import os
# Prepare timezones and beginning of epcoch for later use
utc = pytz.utc
eastern = pytz.timezone('US/Eastern')
epochBeginning = utc.localize(datetime.datetime(1970,1,1))
# Run program
if __name__ == '__main__':
runDirs = ['<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>','<API key>',
'<API key>','<API key>']
# runDirs = ['<API key>']
dataDir = '/home/bjs66/csi/bjs-analysis/Processed/'
powerDir = '/home/bjs66/csi/bjs-analysis/BeamPowerHistory/'
# Read stop times of runs:
data = np.loadtxt('/home/bjs66/GitHub/sns-analysis/<API key>.txt',dtype=str)
# Prepare output file
h5Out = h5py.File(dataDir + 'Stability/Acceptances.h5','w')
# Prepare beam power file
h5Power= h5py.File(powerDir + 'BeamPowerHistory.h5','r')
# For each run to be analyzed
for run in runDirs:
print run
# Find each day in the run
dayNames = np.sort(os.listdir(dataDir + run))
# Get the correct stopping time for the run
for d in data:
if run in d:
easternEndTS = eastern.localize(datetime.datetime.strptime(d[1],'%y-%m-%d-%H-%M-%S'))
utcEndTS = (easternEndTS.astimezone(utc) - epochBeginning).total_seconds()
# Prepare output arrays:
dOut = {'time': [], 'sPT': [], 'bPT': [], 'muon': [], 'linGate': [], 'overflow': [], 'power': [], 'duration': [], 'beamOnDuration': [], 'beamOffDuration': []}
# For each day in the run
for dN in dayNames:
# Open the day as input file from which all the data will be derived
h5In = h5py.File(dataDir + run + '/' + dN)
# Crop the time from the filename
day = '20' + dN.split('.')[0]
# Check if this is the last day in a run, if so set the last timestamp for this day to the end
# otherwise set last tiemstamp for this day to the second before midnight
easternDayTS = eastern.localize(datetime.datetime.strptime(day,'%Y%m%d'))
if easternDayTS.date() == easternEndTS.date():
lastTSForThisDay = utcEndTS
else:
lastTSForThisDay = ((easternDayTS + datetime.timedelta(days=1)).astimezone(utc) - epochBeginning).total_seconds()
# Read power data for current day
timeData = h5Power['/%s/time'%day][...]
powerData = h5Power['/%s/power'%day][...]
# Get all time data in the info file, convert it to seconds since epoch
# and add the proper last timestamp of the day as determined above
timeArray = np.sort(h5In['/I'].keys())
utcTS = []
for time in timeArray:
dayTS = datetime.datetime.strptime('%s%s'%(day,time),'%Y%m%d%H%M%S')
easternTS = eastern.localize(dayTS)
utcTS.append((easternTS.astimezone(utc) - epochBeginning).total_seconds())
utcTS.append(lastTSForThisDay)
# For each time in the info file get the data needed to calculate the acceptances for those
# periods and integrate the power for that timefram
for i in range(len(timeArray)):
# Get the time as eastern time string
time = timeArray[i]
# Get the proper start and stop timestamps in utc seconds since epoch
tsStart = utcTS[i]
tsStop = utcTS[i+1] - 1
duration = tsStop - tsStart
# Read data
nWaveforms = np.sum(h5In['/I/%s/waveformsProcessed'%time][...])
sPTAccept = np.sum(h5In['/I/%s/sPeaksPTDist'%time][...][:3])
bPTAccept = np.sum(h5In['/I/%s/bPeaksPTDist'%time][...][:3])
muonHits = len(h5In['/I/%s/muonHits'%time][...])
linGates = np.sum(h5In['/I/%s/linearGates'%time][...])
overflows = np.sum(h5In['/I/%s/overflows'%time][...])
# Integrate the total power on target between the start and stop time
cutPowerTimes = (timeData>=tsStart) * (timeData<=tsStop)
beamOnSeconds = np.sum(powerData[cutPowerTimes] >= 5e-5)
beamOffSeconds = (tsStop - tsStart + 1) - beamOnSeconds
beamPower = np.sum(powerData[cutPowerTimes])/3600.0 # In MWhr
dOut['time'].append(tsStart)
dOut['sPT'].append(1.0*sPTAccept/nWaveforms)
dOut['bPT'].append(1.0*bPTAccept/nWaveforms)
dOut['muon'].append(1.0*muonHits/nWaveforms)
dOut['linGate'].append(1.0*linGates/nWaveforms)
dOut['overflow'].append(1.0*overflows/nWaveforms)
dOut['power'].append(beamPower)
dOut['duration'].append(duration)
dOut['beamOnDuration'].append(beamOnSeconds)
dOut['beamOffDuration'].append(beamOffSeconds)
h5In.close()
for key in ['time','sPT','bPT','muon','linGate','overflow','power','duration','beamOnDuration','beamOffDuration']:
if '/%s/%s'%(run,key) in h5Out:
del h5Out['/%s/%s'%(run,key)]
h5Out.create_dataset('/%s/%s'%(run,key),data=dOut[key])
h5Out.close()
h5Power.close() |
#include "vector3.h"
#include <stdio.h>
using namespace nautical::math;
void print_vector(Vector3<float> vector)
{
printf("Vector: X: %f Y: %f Z: %f", vector.x, vector.y, vector.z);
}
void test_vector3_add(void)
{
Vector3<float> vec1(15.0f, -30.0f, 10.2f);
Vector3<float> vec2(28.0f, 14.4, -2.0f);
Vector3<float> answer(43.0f, -15.6f, 8.2f);
CU_ASSERT((vec1 + vec2) == answer);
vec1 += vec2;
CU_ASSERT(vec1 == answer);
}
void <API key>(void)
{
Vector3<float> vec1(15.0f, -30.0f, 2.0f);
Vector3<float> vec2(28.0f, 14.4, -3.0f);
Vector3<float> answer(-13.0f, -44.4f, 5.0f);
CU_ASSERT((vec1 - vec2) == answer);
vec1 -= vec2;
CU_ASSERT(vec1 == answer);
}
void <API key>(void)
{
Vector3<float> vec1(15.0f, -30.0f, 2.5f);
Vector3<float> vec2(28.0f, 14.4, 2.0f);
Vector3<float> answer(420.0f, -432.0f, 5.0f);
CU_ASSERT((vec1 * vec2) == answer);
vec1 *= vec2;
CU_ASSERT(vec1 == answer);
}
void test_vector3_divide(void)
{
Vector3<float> vec1(15.0f, -30.0f, 49.0f);
Vector3<float> vec2(5.0f, 6.0f, -7.0f);
Vector3<float> answer(3.0f, -5.0f, -7.0f);
CU_ASSERT((vec1 / vec2) == answer);
vec1 /= vec2;
CU_ASSERT(vec1 == answer);
}
void <API key>(void)
{
Vector3<float> vec1(3.0f, 4.0f, 3.0f);
float magnitude = sqrt(34);
CU_ASSERT(vec1.length() == magnitude);
CU_ASSERT(vec1.lengthSquared() == 34.0f);
}
void test_vector3_dot(void)
{
Vector3<float> vec1(3.0f, 5.0f, 12.0f);
Vector3<float> vec2(12.0f, -2.0f, 4.0f);
float answer = 74.0f;
CU_ASSERT(vec1.dot(vec2) == answer);
}
void test_vector3_cross(void)
{
Vector3<float> vec1(3.0f, 5.0f, 4.0f);
Vector3<float> vec2(3.0f, -2.0f, 1.0f);
Vector3<float> cross(13.0f, 9.0f, -21.0f);
CU_ASSERT(vec1.cross(vec2) == cross);
}
void <API key>(void)
{
Vector3<float> vec1(15.0f, 0.0f, 0.0f);
Vector3<float> vec1Ans(1.0f, 0.0f, 0.0f);
Vector3<float> vec2(30.0f, 40.0f, 5.0f);
Vector3<float> vec2Ans(6.0f/sqrt(101), 8.0f/sqrt(101), 1/sqrt(101));
CU_ASSERT(vec1.normalized() == vec1Ans);
CU_ASSERT(vec2.normalized() == vec2Ans);
} |
/* Cute3D, a simple opengl based framework for writing interactive realtime applications */
/* This file is part of Cute3D. */
/* Cute3D is free software: you can redistribute it and/or modify */
/* (at your option) any later version. */
/* Cute3D is distributed in the hope that it will be useful, */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
#include "geometry_grid.h"
// x:3 y:3 z:3 = 27 cubes
// 0:x0y0z0, 1:x1y0z0, 2:x2y0z0, 3:x0y1z0, 4:x1y1z0, 5:x2y1z0, 6:x0y2z0, 7:x1y2z0, 8:x2y2z0,
// 9:x0y0z1, 10:x1y0z1, 11:x2y0z1, 12:x0y1z1, 13:x1y1z1, 14:x2y1z1, 15:x0y2z1, 16:x1y2z1, 17:x2y2z1,
// 18:x0y0z2, 19:x1y0z2, 20:x2y0z2, 21:x0y1z2, 22:x1y1z2, 23:x2y1z2, 24:x0y2z2, 25:x1y2z2, 26:x2y2z2
// 18.19 19.20 20.21
// 0...1 1...2 2...3
// 4...5 5...6 6...7
// 4...5 5...6 6...7
// 8...9 9..10 10.11
// 8...9 9..10 10.11
// 12.13 14.15 16.17
// x:1 y:0 z:0
// 0 1 2
// 0: 1 2 3
// 1: 4 5 6
// 2: 7 8 9
// 1 2 3 4 5 6 7 8 9
// 0 1 2 3 4 5 6 7 8
// box.dim = 2,2
// box.pos = 1,1
// grid.size = 3,3
// (1+0) + (1+0) * 3 = 4
// (1+1) + (1+0) * 3 = 5
// (1+0) + (1+1) * 3 = 7
// (1+1) + (1+1) * 3 = 8
struct GridBox* grid_pagebox_xyz(struct Grid* grid, struct GridPages* pages, uint64_t x, uint64_t y, uint64_t z, uint32_t level, struct GridBox* box) {
if( grid && pages && box ) {
box->position.x = x * pages->size.x;
box->position.y = y * pages->size.y;
box->position.z = z * pages->size.z;
box->size.x = pages->size.x;
box->size.y = pages->size.y;
box->size.z = pages->size.z;
box->level = level;
}
return box;
}
struct GridBox* grid_pagebox(struct Grid* grid, struct GridPages* pages, uint64_t page, uint32_t level, struct GridBox* box) {
uint64_t z = page / (pages->num.x * pages->num.y);
uint64_t y = page % (pages->num.x * pages->num.y) / pages->num.x;
uint64_t x = page % (pages->num.x * pages->num.y) % pages->num.x;
return grid_pagebox_xyz(grid, pages, x, y, z, level, box);
}
struct GridBox* grid_levelup(struct Grid* grid, struct GridPages* pages, struct GridBox* box) {
if( box && box->level < pages->top ) {
box->level++;
box->size.x /= 2;
box->size.y /= 2;
box->size.z /= 2;
box->position.x /= 2;
box->position.y /= 2;
box->position.z /= 2;
}
return box;
}
struct GridBox* grid_leveldown(struct Grid* grid, struct GridPages* pages, struct GridBox* box) {
if( box && box->level > 0 ) {
box->level
box->size.x *= 2;
box->size.y *= 2;
box->size.z *= 2;
box->position.x *= 2;
box->position.y *= 2;
box->position.z *= 2;
}
return box;
}
struct GridIndex* grid_index_xyz(struct Grid* grid, struct GridPages* pages, struct GridBox* box, uint64_t x, uint64_t y, uint64_t z, struct GridIndex* index) {
if( NULL == box && grid ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
uint32_t level = box->level;
if( x >= box->size.x ) x = box->size.x - 1;
if( y >= box->size.y ) y = box->size.y - 1;
if( z >= box->size.z ) z = box->size.z - 1;
if( pages && pages->size.x > 0 && pages->size.y > 0 && pages->size.z > 0 && index ) {
struct GridSize size;
grid_pagesize(pages, box->level, &size);
uint64_t pagesize_x = size.x;
uint64_t pagesize_y = size.y;
uint64_t pagesize_z = size.z;
uint64_t page_x = (box->position.x + x) / pagesize_x;
uint64_t page_y = (box->position.y + y) / pagesize_y;
uint64_t page_z = (box->position.z + z) / pagesize_z;
uint64_t cell_x = (box->position.x + x) % pagesize_x;
uint64_t cell_y = (box->position.y + y) % pagesize_y;
uint64_t cell_z = (box->position.z + z) % pagesize_z;
uint64_t page = page_z * pages->num.x * pages->num.y + page_y * pages->num.x + page_x;
uint64_t cell = cell_z * pagesize_x * pagesize_y + cell_y * pagesize_x + cell_x;
index->page = page;
index->level = level;
index->cell = cell;
return index;
} else {
return NULL;
}
}
struct GridIndex* grid_index(struct Grid* grid, struct GridPages* pages, struct GridBox* box, uint64_t i, struct GridIndex* index) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
uint64_t z = i / (box->size.x * box->size.y);
uint64_t y = i % (box->size.x * box->size.y) / box->size.x;
uint64_t x = i % (box->size.x * box->size.y) % box->size.x;
//printf("%lu | %lu %lu %lu | %lu %lu %lu\n", i, box->size.x, box->size.y, box->size.z, x, y, z);
return grid_index_xyz(grid,pages,box,x,y,z,index);
}
struct GridSize* grid_levelsize(struct Grid* grid, struct GridPages* pages, uint64_t level, struct GridSize* size) {
if( grid && pages && size ) {
if( level > pages->top ) {
level = pages->top;
}
size->x = grid->size.x > 1 ? grid->size.x / ((uint64_t)1 << level) : 1;
size->y = grid->size.y > 1 ? grid->size.y / ((uint64_t)1 << level) : 1;
size->z = grid->size.z > 1 ? grid->size.z / ((uint64_t)1 << level) : 1;
size->array = size->x * size->y * size->z;
}
return size;
}
struct GridSize* grid_pagesize(struct GridPages* pages, uint64_t level, struct GridSize* size) {
if( pages && size ) {
if( level > pages->top ) {
level = pages->top;
}
size->x = pages->size.x > 1 ? pages->size.x / ((uint64_t)1 << level) : 1;
size->y = pages->size.y > 1 ? pages->size.y / ((uint64_t)1 << level) : 1;
size->z = pages->size.z > 1 ? pages->size.z / ((uint64_t)1 << level) : 1;
size->array = size->x * size->y * size->z;
}
return size;
}
void grid_create(uint64_t x, uint64_t y, uint64_t z,
struct Grid* grid)
{
if( grid ) {
grid->size.x = x;
grid->size.y = y;
grid->size.z = z;
}
}
void grid_pages(struct Grid* grid, uint64_t x, uint64_t y, uint64_t z, struct GridPages* pages) {
if( pages &&
grid->size.x % x == 0 &&
grid->size.y % y == 0 &&
grid->size.z % z == 0 )
{
pages->num.x = grid->size.x / x;
pages->num.y = grid->size.y / y;
pages->num.z = grid->size.z / z;
pages->size.x = x;
pages->size.y = y;
pages->size.z = z;
pages->top = 0;
struct GridSize size;
while( grid_pagesize(pages, pages->top, &size)->array > 1 ) {
pages->top++;
}
pages->array = (Page*)calloc(x * y * z, sizeof(Page*));
for( int32_t i = 0; i < x * y * z; i++ ) {
pages->array[i] = (Cell**)calloc(pages->top, sizeof(Cell**));
}
}
}
void grid_dump(struct Grid grid, struct GridPages pages) {
printf("grid.size.x: %" PRIu64 "\n", grid.size.x);
printf("grid.size.y: %" PRIu64 "\n", grid.size.y);
printf("grid.size.z: %" PRIu64 "\n", grid.size.z);
printf("pages.size.x: %" PRIu64 "\n", pages.size.x);
printf("pages.size.y: %" PRIu64 "\n", pages.size.y);
printf("pages.size.z: %" PRIu64 "\n", pages.size.z);
printf("pages.top: %" PRIu64 "\n", pages.top);
if( pages.size.x > 0 && pages.size.y > 0 && pages.size.z > 0 ) {
uint64_t num_pages_x = grid.size.x / pages.size.x;
uint64_t num_pages_y = grid.size.y / pages.size.y;
uint64_t num_pages_z = grid.size.z / pages.size.z;
printf("num_pages_x: %" PRIu64 "\n", num_pages_x);
printf("num_pages_y: %" PRIu64 "\n", num_pages_y);
printf("num_pages_z: %" PRIu64 "\n", num_pages_z);
}
if( pages.top > 0 ) {
struct GridSize size = {0};
for( uint64_t l = 0; l < pages.top+1; l++ ) {
printf("levelsize_x@%" PRIu64 ": %" PRIu64 "\n", l, grid_levelsize(&grid, &pages, l, &size)->x);
printf("levelsize_y@%" PRIu64 ": %" PRIu64 "\n", l, grid_levelsize(&grid, &pages, l, &size)->y);
printf("levelsize_z@%" PRIu64 ": %" PRIu64 "\n", l, grid_levelsize(&grid, &pages, l, &size)->z);
}
}
}
void grid_alloc(struct GridPages* pages, uint64_t page, uint32_t level) {
struct GridSize size = {0};
if( pages && pages->array ) {
grid_pagesize(pages, level, &size);
printf("%lu %u %lu %lu\n", page, level, size.array, sizeof(Cell));
pages->array[page][level] = (Cell*)calloc(size.array, sizeof(Cell));
}
}
void grid_free(struct GridPages* pages, uint64_t page, uint32_t level) {
if( pages && pages->array ) {
free(pages->array[page][level]);
}
}
void grid_clear(struct Grid* grid, struct GridPages* pages, struct GridBox* box) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
grid_index(grid, pages, box, i, &index);
pages->array[index.page][index.level][index.cell] = 0;
}
}
}
void grid_set1(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell cell) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
grid_index(grid, pages, box, i, &index);
//printf("%d %lu %lu %" PRIu64 "\n", i, index.page, index.level, index.cell);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] = cell;
}
}
}
}
void grid_setN(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell* cells, uint64_t n) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages && cells && n ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
uint64_t cell_i = 0;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
if( cell_i == n ) {
cell_i = 0;
}
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] = cells[cell_i];
}
cell_i++;
}
}
}
void grid_and1(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell cell) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] &= cell;
}
}
}
}
void grid_andN(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell* cells, uint64_t n) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages && cells && n ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
uint64_t cell_i = 0;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
if( cell_i == n ) {
cell_i = 0;
}
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] &= cells[cell_i];
}
cell_i++;
}
}
}
void grid_or1(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell cell) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] |= cell;
}
}
}
}
void grid_orN(struct Grid* grid, struct GridPages* pages, struct GridBox* box, Cell* cells, uint64_t n) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages && cells && n ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
uint64_t cell_i = 0;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
if( cell_i == n ) {
cell_i = 0;
}
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
pages->array[index.page][index.level][index.cell] |= cells[cell_i];
}
cell_i++;
}
}
}
void grid_shift(struct Grid* grid, struct GridPages* pages, struct GridBox* box, int32_t shift) {
if( NULL == box ) {
box = &box_createN(0, 0, 0, grid->size.x, grid->size.y, grid->size.z, 0);
}
if( grid && pages && shift ) {
uint64_t array_size = box->size.x * box->size.y * box->size.z;
struct GridIndex index = {0};
for( uint64_t i = 0; i < array_size; i++ ) {
grid_index(grid, pages, box, i, &index);
if( pages->array[index.page][index.level] ) {
if( shift < 0 ) {
pages->array[index.page][index.level][index.cell] <<= abs(shift);
} else {
pages->array[index.page][index.level][index.cell] >>= shift;
}
}
}
}
}
void grid_pagein(struct Grid* grid, struct GridPages* pages, uint64_t page, uint32_t level, char** in) {
}
void grid_pageout(struct Grid* grid, struct GridPages* pages, uint64_t page, uint32_t level, char** out) {
}
// 0 1| 2 3| 4 5
// 0 | 1 | 2
// 6 7| 8 9|10 11
// 12 13|14 15|16 17
// 3 | 4 | 5
// 18 19|20 21|22 23
// 24 25|26 27|28 29
// 6 | 7 | 8
// 30 31|32 33|34 35
// y * size.x * 4 + x
// y*size.x*4+x+1
// y*size.x*4+2*x
// y*size.x*4+2*x+1
// 0,0 1,0|2,0 3,0|4,0 5,0
// 0,0 | 1,0 | 2,0
// 0,1 1,1|2,1 3,1|4,1 5,1
// 0,2 1,2|2,2 3,2|4,2 5,2
// 0,1 | 1,1 | 2,1
// 0,3 1,3|2,3 3,3|4,3 5,3
// 0,4 1,4|2,4 3,4|4,4 5,4
// 0,2 | 1,2 | 2,2
// 0,5 1,5|2,5 3,5|4,5 5,5
void world_grid_create(struct GridPages* pages,
uint32_t level,
float width,
float height,
float depth,
const struct SolidBox* cube,
struct VboMesh* mesh)
{
struct GridSize size = {0};
grid_pagesize(pages, level, &size);
uint64_t n = 12 * 3 * size.x * size.y * size.z;
float* vertices = malloc(sizeof(float) * 3 * n);
log_assert( vertices != NULL );
float* normals = malloc(sizeof(float) * 3 * n);
log_assert( normals != NULL );
uint8_t* colors = malloc(sizeof(uint8_t) * 4 * n);
log_assert( colors != NULL );
for( uint64_t zi = 0; zi < size.z; zi++ ) {
for( uint64_t yi = 0; yi < size.y; yi++ ) {
for( uint64_t xi = 0; xi < size.x; xi++ ) {
float x = xi * width;
float y = yi * height;
float z = zi * depth;
uint64_t offset = 12 * 3 * (zi * size.x * size.y + yi * size.x + xi);
printf("%" PRIu64 " %" PRIu64 " %" PRIu64 " %f %f %f %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", xi, yi, zi, x, y, z, offset, cube->solid.attributes_size*3, n, pages->size.x);
for( uint64_t i = 0; i < cube->solid.attributes_size; i++ ) {
vertices[(offset+i)*3+0] = x + cube->vertices[i*3+0]*width;
vertices[(offset+i)*3+1] = y + cube->vertices[i*3+1]*height;
vertices[(offset+i)*3+2] = z + cube->vertices[i*3+2]*depth;
normals[(offset+i)*3+0] = cube->normals[i*3+0];
normals[(offset+i)*3+1] = cube->normals[i*3+1];
normals[(offset+i)*3+2] = cube->normals[i*3+2];
colors[(offset+i)*4+0] = cube->colors[i*4+0];
colors[(offset+i)*4+1] = cube->colors[i*4+1];
colors[(offset+i)*4+2] = cube->colors[i*4+2];
colors[(offset+i)*4+3] = cube->colors[i*4+3];
}
}
}
}
size_t vertices_n = <API key>(mesh, <API key>, 3, GL_FLOAT, n, vertices);
size_t normals_n = <API key>(mesh, <API key>, 3, GL_FLOAT, n, normals);
size_t colors_n = <API key>(mesh, <API key>, 4, GL_UNSIGNED_BYTE, n, colors);
log_assert( vertices_n == n );
log_assert( normals_n == n );
log_assert( colors_n == n );
free(vertices);
free(normals);
free(colors);
}
void world_grid_update(struct Grid* grid,
struct GridPages* pages,
uint32_t level,
uint64_t page,
const struct SolidBox* cube,
struct VboMesh* mesh)
{
// first create _all_ vertices and normals in mesh needed for the grid, then just
// generate the mesh by modifying the indices buffer
// two ways to approach this:
// 1. create a box for every cell of the grid
// + more straightforward to implement
// 2. try to create only those faces that are neccessary
// + needs less bandwidth
// I need to somehow make it possible to use the buffers that contain
// the vertices and normals in multiple meshes if I want to be able
// to use grid pages
// 1. the best way to do this is to give this function the authority to
// create the meshes, given an vbo as input, an offset and a size as
// well as a page, this function then creates a mesh clone for that
// specific page
// 2. could expect the user to supply meshes created with mesh_clone instead,
// maybe add some kind of field to mesh to 'lock' a mesh to make clones
// non-modifyable
<API key>(mesh);
struct GridBox box = {0};
grid_pagebox(grid, pages, page, level, &box);
struct GridIndex index = {0};
uint64_t n = 6 * 2 * box.size.x * box.size.y * box.size.z;
uint64_t* triangles = malloc(sizeof(uint64_t) * 3 * n);
for( uint64_t xi = 0; xi < box.size.x; xi++ ) {
for( uint64_t yi = 0; yi < box.size.y; yi++ ) {
for( uint64_t zi = 0; zi < box.size.z; zi++ ) {
grid_index_xyz(grid, pages, &box, xi, yi, zi, &index);
if( pages->array[index.page][index.level][index.cell] > 0 ) {
uint64_t v_offset = 3 * 12 * 3 * (zi * box.size.x * box.size.y + yi * box.size.x + xi);
uint64_t t_offset = 3 * 6 * 2 * (zi * box.size.x * box.size.y + yi * box.size.x + xi);
for( uint64_t i = 0; i < 36; i++ ) {
triangles[t_offset+i] = v_offset + cube->triangles[i];
}
}
}
}
}
size_t triangles_n = <API key>(mesh, n, triangles);
log_assert( triangles_n == n );
free(triangles);
} |
package com.mprevisic.user.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Security key entity
*
* @author Marko Previsic
* @created May 22, 2017
*/
@Entity
@Table(name="security_keys")
public class KeyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(unique=true)
private String name;
private byte[] value;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
} |
CREATE TABLE IF NOT EXISTS `exf_page` (
`oid` binary(16) NOT NULL,
`created_on` datetime NOT NULL,
`modified_on` datetime NOT NULL,
`created_by_user_oid` binary(16) DEFAULT NULL,
`<API key>` binary(16) DEFAULT NULL,
`app_oid` binary(16) DEFAULT NULL,
`page_template_oid` binary(16) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`alias` varchar(100) DEFAULT NULL,
`description` varchar(200) DEFAULT NULL,
`intro` varchar(200) DEFAULT NULL,
`content` longtext,
`parent_oid` binary(16) DEFAULT NULL,
`menu_index` int(11) NOT NULL DEFAULT '0',
`menu_visible` tinyint(1) NOT NULL DEFAULT '1',
`<API key>` varchar(100) DEFAULT NULL,
`replace_page_oid` binary(16) DEFAULT NULL,
`replace_page_alias` varchar(100) DEFAULT NULL,
`<API key>` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- DOWN
DROP TABLE IF EXISTS `exf_page`; |
namespace Maticsoft.TaoBao.Request
{
using Maticsoft.TaoBao;
using Maticsoft.TaoBao.Util;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class FavoriteAddRequest : ITopRequest<FavoriteAddResponse>
{
private IDictionary<string, string> otherParameters;
public void AddOtherParameter(string key, string value)
{
if (this.otherParameters == null)
{
this.otherParameters = new TopDictionary();
}
this.otherParameters.Add(key, value);
}
public string GetApiName()
{
return "taobao.favorite.add";
}
public IDictionary<string, string> GetParameters()
{
TopDictionary dictionary = new TopDictionary();
dictionary.Add("collect_type", this.CollectType);
dictionary.Add("item_numid", this.ItemNumid);
dictionary.Add("shared", this.Shared);
dictionary.AddAll(this.otherParameters);
return dictionary;
}
public void Validate()
{
RequestValidator.ValidateRequired("collect_type", this.CollectType);
RequestValidator.ValidateRequired("item_numid", this.ItemNumid);
RequestValidator.ValidateMinValue("item_numid", this.ItemNumid, 1L);
}
public string CollectType { get; set; }
public long? ItemNumid { get; set; }
public bool? Shared { get; set; }
}
} |
$(window).scroll(
function() {
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight > scrollHeight - 200) {
ajax_sourch_submit();
}
}
); |
#coding:utf8
import re
import random
import time
import lxml.html
import json
def sleep(sleep_time):
sleep_time=sleep_time+random.randint(-2,2)
#print sleep_time
if sleep_time<=0:
sleep_time=0
#print('Sleeping for '+str(sleep_time)+' seconds')
time.sleep(sleep_time)
#print('Wake up')
def get_target(html):
if(not 'location.replace' in html):
#print('No location.replace in html')
return None
pat="location.replace\('[^']*'\)"
a=re.findall(pat,html)
pat='location.replace\("[^"]*"\)'
b=re.findall(pat,html)
ans=[]
for url in a:
ans.append(url[18:-2])
for url in b:
ans.append(url[18:-2])
if(ans==[]):
return None
else:
return ans
if __name__=='__main__':
print 'Helper'
#print <API key>()
#check()
#output_all_uids() |
package it.fmd.cocecl.gcm;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.<API key>;
import java.io.IOException;
import it.fmd.cocecl.APPConstants;
import it.fmd.cocecl.R;
public class UnregisterGCM {
private Context context;
public UnregisterGCM(Context context) {
this.context = context;
}
private static final String TAG = "MyActivity";
private static final String TOPIC_PREFIX = "/topics/";
private <API key> gcm;
private GcmPubSub pubSub;
private String token;
public void unregisterClient() {
gcm = <API key>.getInstance(context);
pubSub = GcmPubSub.getInstance(context);
String senderId = context.getString(R.string.gcm_defaultSenderId);
if (!("".equals(senderId))) {
// Create the bundle for registration with the server.
Bundle registration = new Bundle();
registration.putString(APPConstants.ACTION, APPConstants.UNREGISTER_CLIENT);
registration.putString(APPConstants.REGISTRATION_TOKEN, token);
try {
gcm.send(getServerUrl(senderId),
String.valueOf(System.currentTimeMillis()), registration);
} catch (IOException e) {
Log.e(TAG, "Message failed", e);
//updateUI("Unregistration FAILED", true);
}
}
}
public static String getServerUrl(String senderId) {
return senderId + "@gcm.googleapis.com";
}
} |
#include "Evento.h"
Evento::Evento(int _tempo, void *_objeto, void *_relacionado, int _tipo) {
tempo = _tempo;
objeto = _objeto;
tipo = _tipo;
relacionado = _relacionado;
}
int Evento::getTipo() { return tipo; }
int Evento::getTempo() const { return tempo; }
void *Evento::getObjeto() { return objeto; }
void *Evento::getRelacionado() { return relacionado; }
bool ListaDeEventos::maior(Evento *dado1, Evento *dado2) const {
return dado1->getTempo() > dado2->getTempo();
} |
package com.example.benzex.holamundo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
} |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<title>ActiveSupport</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/github.css" type="text/css" media="screen" />
<script src="../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.2.0</span><br />
<h1>
<span class="type">Module</span>
ActiveSupport
</h1>
<ul class="files">
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionpack-4_2_0/lib/action_dispatch/testing/assertions/dom_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionpack-4.2.0/lib/action_dispatch/testing/assertions/dom.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionpack-4_2_0/lib/action_dispatch/testing/assertions/selector_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionpack-4.2.0/lib/action_dispatch/testing/assertions/selector.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionpack-4_2_0/lib/action_dispatch/testing/assertions/tag_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionpack-4.2.0/lib/action_dispatch/testing/assertions/tag.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/base_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/base.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/flows_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/flows.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/helpers/form_helper_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/helpers/form_helper.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/helpers/number_helper_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/helpers/number_helper.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/helpers/tags/time_zone_select_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/helpers/tags/time_zone_select.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/renderer/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/renderer/abstract_renderer.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/template_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/template/resolver_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template/resolver.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/test_case_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/test_case.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/view_paths_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/view_paths.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activejob-4_2_0/lib/active_job/logging_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activejob-4.2.0/lib/active_job/logging.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activejob-4_2_0/lib/active_job/queue_adapters/sneakers_adapter_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activejob-4.2.0/lib/active_job/queue_adapters/sneakers_adapter.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activejob-4_2_0/lib/active_job/railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activejob-4.2.0/lib/active_job/railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/callbacks_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/callbacks.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/conversion_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/conversion.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/dirty_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/dirty.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/naming_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/naming.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/serializers/json_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/serializers/json.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activemodel-4_2_0/lib/active_model/serializers/xml_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activemodel-4.2.0/lib/active_model/serializers/xml.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/associations/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/associations/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/associations/join_dependency_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/associations/join_dependency.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/attribute_methods.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/attribute_methods/read_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/attribute_methods/read.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/attribute_methods/serialization_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/attribute_methods/serialization.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/coders/json_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/coders/json.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/abstract/connection_pool_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/connection_pool.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/abstract/query_cache_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/query_cache.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/abstract/quoting_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/quoting.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/abstract/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/schema_definitions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/abstract_adapter_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/postgresql/oid/json_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/oid/json.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/connection_adapters/postgresql/oid/range_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/oid/range.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/core_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/core.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/enum_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/enum.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/explain_subscriber.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/inheritance_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/inheritance.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/querying_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/querying.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/reflection_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/reflection.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/relation/finder_methods_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/relation/finder_methods.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/relation/predicate_builder/array_handler_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/relation/predicate_builder/array_handler.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/relation/query_methods_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/relation/query_methods.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/sanitization_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/sanitization.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/serializers/xml_serializer_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/serializers/xml_serializer.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/store_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/store.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/tasks/database_tasks_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/tasks/database_tasks.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/transactions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/transactions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/type/boolean_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/type/boolean.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activerecord-4_2_0/lib/active_record/type/string_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0/lib/active_record/type/string.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/backtrace_cleaner.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/benchmarkable_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/benchmarkable.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/file_store_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/file_store.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/mem_cache_store_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/mem_cache_store.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/memory_store_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/memory_store.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/null_store_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/null_store.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/strategy/local_cache_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/strategy/local_cache.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/cache/strategy/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/cache/strategy/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/callbacks_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/callbacks.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/concern_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/concern.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/concurrency/latch_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/concurrency/latch.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/configurable_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/configurable.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/array/conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/array/conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/big_decimal/yaml_conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/big_decimal/yaml_conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/date/calculations_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/date/calculations.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/date_and_time/zones_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/date_and_time/zones.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/date_time/conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/date_time/conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/hash/conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/hash/conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/hash/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/hash/indifferent_access.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/integer/inflections_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/integer/inflections.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/integer/time_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/integer/time.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/kernel/reporting_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/kernel/reporting.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/module/deprecation_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/module/deprecation.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/module/introspection_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/module/introspection.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/numeric/conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/numeric/time_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/time.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/object/json_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/object/json.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/object/with_options_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/object/with_options.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/string/inflections_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/string/inflections.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/string/inquiry_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/string/inquiry.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/string/multibyte_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/string/multibyte.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/string/output_safety_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/string/output_safety.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/time/calculations_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/time/calculations.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/time/conversions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/time/conversions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/core_ext/time/zones_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/core_ext/time/zones.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/dependencies_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/dependencies.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/dependencies/autoload_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/dependencies/autoload.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation/behaviors_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation/behaviors.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation/instance_delegator.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation/method_wrappers_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation/method_wrappers.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation/proxy_wrappers_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation/proxy_wrappers.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/deprecation/reporting_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/deprecation/reporting.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/descendants_tracker.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/duration_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/duration.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/file_update_checker.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/gem_version_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/gem_version.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/gzip_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/gzip.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/i18n_railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/i18n_railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/inflections_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/inflections.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/inflector/inflections_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/inflector/inflections.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/inflector/methods_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/inflector/methods.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/inflector/transliterate_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/inflector/transliterate.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/json/decoding_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/json/decoding.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/json/encoding_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/json/encoding.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/key_generator_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/key_generator.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/lazy_load_hooks_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/lazy_load_hooks.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/log_subscriber_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/log_subscriber.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/log_subscriber/test_helper_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/log_subscriber/test_helper.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/logger_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/logger.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/message_encryptor.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/message_verifier_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/message_verifier.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/multibyte_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/multibyte.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/multibyte/chars_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/multibyte/chars.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/multibyte/unicode_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/multibyte/unicode.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/notifications_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/notifications.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/notifications/fanout_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/notifications/fanout.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/notifications/instrumenter_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/notifications/instrumenter.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/number_converter_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/number_converter.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/number_helper/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/number_helper/<API key>.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/option_merger_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/option_merger.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/ordered_hash_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/ordered_hash.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/ordered_options_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/ordered_options.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/per_thread_registry.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/proxy_object_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/proxy_object.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/rescuable_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/rescuable.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/security_utils_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/security_utils.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/string_inquirer_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/string_inquirer.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/subscriber_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/subscriber.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/tagged_logging_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/tagged_logging.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/test_case_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/test_case.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/assertions_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/assertions.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/constant_lookup_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/constant_lookup.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/declarative_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/declarative.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/deprecation_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/deprecation.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/isolation_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/isolation.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/<API key>.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/setup_and_teardown.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/tagged_logging_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/tagged_logging.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/testing/time_helpers_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/testing/time_helpers.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/time_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/time.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/time_with_zone_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/time_with_zone.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/values/time_zone_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/version_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/version.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/jdom_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/jdom.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/libxml_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/libxml.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/libxmlsax_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/libxmlsax.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/nokogiri_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/nokogiri.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/nokogirisax_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/nokogirisax.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/activesupport-4_2_0/lib/active_support/xml_mini/rexml_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/xml_mini/rexml.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/application_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/application.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/application/bootstrap_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/application/bootstrap.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/application/configuration_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/application/configuration.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/application/finisher_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/application/finisher.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/application/routes_reloader_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/application/routes_reloader.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/commands/server_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/commands/server.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/engine_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/engine.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/rack/log_tailer_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/rack/log_tailer.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/rack/logger_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/rack/logger.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/railtie_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/railtie.rb</a></li>
<li><a href="../files/__/__/_rvm/gems/ruby-2_1_1/gems/railties-4_2_0/lib/rails/test_help_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/railties-4.2.0/lib/rails/test_help.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Autoload.html">ActiveSupport::Autoload</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Benchmarkable.html">ActiveSupport::Benchmarkable</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Cache.html">ActiveSupport::Cache</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Callbacks.html">ActiveSupport::Callbacks</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Concern.html">ActiveSupport::Concern</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Concurrency.html">ActiveSupport::Concurrency</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Configurable.html">ActiveSupport::Configurable</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Dependencies.html">ActiveSupport::Dependencies</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/DescendantsTracker.html">ActiveSupport::DescendantsTracker</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Gzip.html">ActiveSupport::Gzip</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Inflector.html">ActiveSupport::Inflector</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/JSON.html">ActiveSupport::JSON</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Multibyte.html">ActiveSupport::Multibyte</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Notifications.html">ActiveSupport::Notifications</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/NumberHelper.html">ActiveSupport::NumberHelper</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/PerThreadRegistry.html">ActiveSupport::PerThreadRegistry</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Rescuable.html">ActiveSupport::Rescuable</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/SecurityUtils.html">ActiveSupport::SecurityUtils</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/TaggedLogging.html">ActiveSupport::TaggedLogging</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/Testing.html">ActiveSupport::Testing</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/VERSION.html">ActiveSupport::VERSION</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/XmlMini.html">ActiveSupport::XmlMini</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/XmlMini_LibXMLSAX.html">ActiveSupport::XmlMini_LibXMLSAX</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/XmlMini_Nokogiri.html">ActiveSupport::XmlMini_Nokogiri</a>
</li>
<li>
<span class="type">MODULE</span>
<a href="ActiveSupport/XmlMini_NokogiriSAX.html">ActiveSupport::XmlMini_NokogiriSAX</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/BacktraceCleaner.html">ActiveSupport::BacktraceCleaner</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/CachingKeyGenerator.html">ActiveSupport::CachingKeyGenerator</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/Deprecation.html">ActiveSupport::Deprecation</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/<API key>.html">ActiveSupport::<API key></a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/Duration.html">ActiveSupport::Duration</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/FileUpdateChecker.html">ActiveSupport::FileUpdateChecker</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/<API key>.html">ActiveSupport::<API key></a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/InheritableOptions.html">ActiveSupport::InheritableOptions</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/KeyGenerator.html">ActiveSupport::KeyGenerator</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/LogSubscriber.html">ActiveSupport::LogSubscriber</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/Logger.html">ActiveSupport::Logger</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/MessageEncryptor.html">ActiveSupport::MessageEncryptor</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/MessageVerifier.html">ActiveSupport::MessageVerifier</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/OrderedHash.html">ActiveSupport::OrderedHash</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/OrderedOptions.html">ActiveSupport::OrderedOptions</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/ProxyObject.html">ActiveSupport::ProxyObject</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/SafeBuffer.html">ActiveSupport::SafeBuffer</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/StringInquirer.html">ActiveSupport::StringInquirer</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/Subscriber.html">ActiveSupport::Subscriber</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/TestCase.html">ActiveSupport::TestCase</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/TimeWithZone.html">ActiveSupport::TimeWithZone</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/TimeZone.html">ActiveSupport::TimeZone</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="ActiveSupport/XMLConverter.html">ActiveSupport::XMLConverter</a>
</li>
</ul>
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>E</dt>
<dd>
<ul>
<li>
<a href="#<API key>">execute_hook</a>
</li>
</ul>
</dd>
<dt>G</dt>
<dd>
<ul>
<li>
<a href="#<API key>">gem_version</a>
</li>
</ul>
</dd>
<dt>O</dt>
<dd>
<ul>
<li>
<a href="#method-c-on_load">on_load</a>
</li>
</ul>
</dd>
<dt>R</dt>
<dd>
<ul>
<li>
<a href="#<API key>">run_load_hooks</a>
</li>
</ul>
</dd>
<dt>V</dt>
<dd>
<ul>
<li>
<a href="#method-c-version">version</a>
</li>
</ul>
</dd>
</dl>
<!-- Methods -->
<div class="sectiontitle">Class Public methods</div>
<div class="method">
<div class="title method-title" id="<API key>">
<b>execute_hook</b>(base, options, block)
<a href="../classes/ActiveSupport.html#<API key>" name="<API key>" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/lazy_load_hooks.rb, line 34</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">self</span>.<span class="ruby-identifier">execute_hook</span>(<span class="ruby-identifier">base</span>, <span class="ruby-identifier">options</span>, <span class="ruby-identifier">block</span>)
<span class="ruby-keyword">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-value">:yield</span>]
<span class="ruby-identifier">block</span>.<span class="ruby-identifier">call</span>(<span class="ruby-identifier">base</span>)
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">base</span>.<span class="ruby-identifier">instance_eval</span>(<span class="ruby-operator">&</span><span class="ruby-identifier">block</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="<API key>">
<b>gem_version</b>()
<a href="../classes/ActiveSupport.html#<API key>" name="<API key>" class="permalink">Link</a>
</div>
<div class="description">
<p>Returns the version of the currently loaded Active Support as a
<code>Gem::Version</code></p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/gem_version.rb, line 3</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">self</span>.<span class="ruby-identifier">gem_version</span>
<span class="ruby-constant">Gem</span><span class="ruby-operator">::</span><span class="ruby-constant">Version</span>.<span class="ruby-identifier">new</span> <span class="ruby-constant">VERSION</span><span class="ruby-operator">::</span><span class="ruby-constant">STRING</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-c-on_load">
<b>on_load</b>(name, options = {}, &block)
<a href="../classes/ActiveSupport.html#method-c-on_load" name="method-c-on_load" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/lazy_load_hooks.rb, line 26</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">self</span>.<span class="ruby-identifier">on_load</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span> = {}, <span class="ruby-operator">&</span><span class="ruby-identifier">block</span>)
<span class="ruby-ivar">@loaded</span>[<span class="ruby-identifier">name</span>].<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">base</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">execute_hook</span>(<span class="ruby-identifier">base</span>, <span class="ruby-identifier">options</span>, <span class="ruby-identifier">block</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-ivar">@load_hooks</span>[<span class="ruby-identifier">name</span>] <span class="ruby-operator"><<</span> [<span class="ruby-identifier">block</span>, <span class="ruby-identifier">options</span>]
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="<API key>">
<b>run_load_hooks</b>(name, base = Object)
<a href="../classes/ActiveSupport.html#<API key>" name="<API key>" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/lazy_load_hooks.rb, line 42</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">self</span>.<span class="ruby-identifier">run_load_hooks</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">base</span> = <span class="ruby-constant">Object</span>)
<span class="ruby-ivar">@loaded</span>[<span class="ruby-identifier">name</span>] <span class="ruby-operator"><<</span> <span class="ruby-identifier">base</span>
<span class="ruby-ivar">@load_hooks</span>[<span class="ruby-identifier">name</span>].<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">hook</span>, <span class="ruby-identifier">options</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">execute_hook</span>(<span class="ruby-identifier">base</span>, <span class="ruby-identifier">options</span>, <span class="ruby-identifier">hook</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-c-version">
<b>version</b>()
<a href="../classes/ActiveSupport.html#method-c-version" name="method-c-version" class="permalink">Link</a>
</div>
<div class="description">
<p>Returns the version of the currently loaded <a
href="ActiveSupport.html">ActiveSupport</a> as a <code>Gem::Version</code></p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/activesupport-4.2.0/lib/active_support/version.rb, line 5</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">self</span>.<span class="ruby-identifier">version</span>
<span class="ruby-identifier">gem_version</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Sidequest2: SideQuest II/SideQuest II/Tilemap.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo_small.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Sidequest2
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">SideQuest II</a></li><li class="navelem"><a class="el" href="<API key>.html">SideQuest II</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Tilemap.h</div> </div>
</div><!--header
<div class="contents">
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="preprocessor">#pragma once</span></div>
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="preprocessor"></span><span class="preprocessor">#include <string></span></div>
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> <span class="preprocessor">#include <pugixml.hpp></span></div>
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> <span class="preprocessor">#include <SFML/Graphics.hpp></span></div>
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> <span class="preprocessor">#include "TilemapObject.h"</span></div>
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> </div>
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> <span class="keyword">class </span><a class="code" href="class_app.html">App</a>;</div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> </div>
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span> </div>
<div class="line"><a name="l00010"></a><span class="lineno"><a class="line" href="class_tilemap.html"> 10</a></span> <span class="keyword">class </span><a class="code" href="class_tilemap.html">Tilemap</a></div>
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span>  : <span class="keyword">public</span> sf::Drawable</div>
<div class="line"><a name="l00012"></a><span class="lineno"> 12</span> {</div>
<div class="line"><a name="l00013"></a><span class="lineno"> 13</span> <span class="keyword">public</span>:</div>
<div class="line"><a name="l00014"></a><span class="lineno"> 14</span>  <a class="code" href="class_tilemap.html">Tilemap</a>(<a class="code" href="class_app.html">App</a>& app, std::string filename = <span class="stringliteral">""</span>);</div>
<div class="line"><a name="l00015"></a><span class="lineno"> 15</span> </div>
<div class="line"><a name="l00016"></a><span class="lineno"> 16</span>  <span class="keywordtype">void</span> loadFromFile(std::string filename);</div>
<div class="line"><a name="l00017"></a><span class="lineno"> 17</span>  <span class="keywordtype">void</span> fillVAs();</div>
<div class="line"><a name="l00018"></a><span class="lineno"> 18</span> </div>
<div class="line"><a name="l00019"></a><span class="lineno"> 19</span>  <span class="keyword">virtual</span> <span class="keywordtype">void</span> draw(sf::RenderTarget& target, sf::RenderStates states) <span class="keyword">const</span>;</div>
<div class="line"><a name="l00020"></a><span class="lineno"> 20</span> </div>
<div class="line"><a name="l00021"></a><span class="lineno"> 21</span> <span class="keyword">private</span>:</div>
<div class="line"><a name="l00022"></a><span class="lineno"> 22</span>  pugi::xml_document m_doc;</div>
<div class="line"><a name="l00023"></a><span class="lineno"> 23</span>  sf::Texture* m_tileset;</div>
<div class="line"><a name="l00024"></a><span class="lineno"> 24</span>  <a class="code" href="class_app.html">App</a>& m_app;</div>
<div class="line"><a name="l00025"></a><span class="lineno"> 25</span> </div>
<div class="line"><a name="l00026"></a><span class="lineno"> 26</span>  <span class="comment">// Map data</span></div>
<div class="line"><a name="l00027"></a><span class="lineno"> 27</span>  sf::Vector2u m_mapsize;</div>
<div class="line"><a name="l00028"></a><span class="lineno"> 28</span>  sf::Vector2u m_tilesize;</div>
<div class="line"><a name="l00029"></a><span class="lineno"> 29</span>  sf::Vector2u m_tilesetsize;</div>
<div class="line"><a name="l00030"></a><span class="lineno"> 30</span> </div>
<div class="line"><a name="l00031"></a><span class="lineno"> 31</span>  std::vector<sf::VertexArray> m_layers;</div>
<div class="line"><a name="l00032"></a><span class="lineno"> 32</span>  std::vector<std::vector<unsigned int>> m_layerdata;</div>
<div class="line"><a name="l00033"></a><span class="lineno"> 33</span>  std::vector<std::vector<TilemapObject>> m_objects;</div>
<div class="line"><a name="l00034"></a><span class="lineno"> 34</span> };</div>
<div class="line"><a name="l00035"></a><span class="lineno"> 35</span> </div>
<div class="ttc" id="class_tilemap_html"><div class="ttname"><a href="class_tilemap.html">Tilemap</a></div><div class="ttdef"><b>Definition:</b> Tilemap.h:10</div></div>
<div class="ttc" id="class_app_html"><div class="ttname"><a href="class_app.html">App</a></div><div class="ttdef"><b>Definition:</b> App.h:8</div></div>
</div><!-- fragment --></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Feb 4 2014 20:52:00 for Sidequest2 by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html> |
package adams.flow.transformer;
import adams.core.QuickInfoHelper;
import adams.core.Utils;
import adams.core.io.PlaceholderFile;
import adams.flow.core.Token;
import adams.gui.tools.<API key>.io.<API key>;
import adams.gui.tools.<API key>.io.<API key>;
import java.io.File;
/**
<!-- globalinfo-start -->
* Loads an experiment file.
* <br><br>
<!-- globalinfo-end -->
*
<!-- flow-summary-start -->
* Input/output:<br>
* - accepts:<br>
* java.lang.String<br>
* java.io.File<br>
* - generates:<br>
* adams.gui.tools.<API key>.experiment.AbstractExperiment<br>
* <br><br>
<!-- flow-summary-end -->
*
<!-- options-start -->
* <pre>-logging-level <OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST> (property: loggingLevel)
* The logging level for outputting errors and debugging output.
* default: WARNING
* </pre>
*
* <pre>-name <java.lang.String> (property: name)
* The name of the actor.
* default: <API key>
* </pre>
*
* <pre>-annotation <adams.core.base.BaseAnnotation> (property: annotations)
* The annotations to attach to this actor.
* default:
* </pre>
*
* <pre>-skip <boolean> (property: skip)
* If set to true, transformation is skipped and the input token is just forwarded
* as it is.
* default: false
* </pre>
*
* <pre>-stop-flow-on-error <boolean> (property: stopFlowOnError)
* If set to true, the flow execution at this level gets stopped in case this
* actor encounters an error; the error gets propagated; useful for critical
* actors.
* default: false
* </pre>
*
* <pre>-silent <boolean> (property: silent)
* If enabled, then no errors are output in the console; Note: the enclosing
* actor handler must have this enabled as well.
* default: false
* </pre>
*
* <pre>-handler <adams.gui.tools.<API key>.io.<API key>> (property: handler)
* The I/O handler to use.
* default: adams.gui.tools.<API key>.io.<API key>
* </pre>
*
<!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class <API key>
extends AbstractTransformer {
private static final long serialVersionUID = <API key>;
/** the IO handler. */
protected <API key> m_Handler;
/**
* Returns a string describing the object.
*
* @return a description suitable for displaying in the gui
*/
@Override
public String globalInfo() {
return
"Loads an experiment file.\n"
+ "Supported file formats of current handler: "
+ Utils.flatten(m_Handler.<API key>(true), ",");
}
/**
* Adds options to the internal list of options.
*/
@Override
public void defineOptions() {
super.defineOptions();
m_OptionManager.add(
"handler", "handler",
getDefaultHandler());
}
/**
* Returns the default IO handler.
*
* @return the handler
*/
protected <API key> getDefaultHandler() {
return new <API key>();
}
/**
* Sets the IO handler.
*
* @param value the handler
*/
public void setHandler(<API key> value) {
m_Handler = value;
reset();
}
/**
* Returns the IO handler.
*
* @return the handler
*/
public <API key> getHandler() {
return m_Handler;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String handlerTipText() {
return "The I/O handler to use.";
}
/**
* Returns a quick info about the actor, which will be displayed in the GUI.
*
* @return null if no info available, otherwise short string
*/
@Override
public String getQuickInfo() {
return QuickInfoHelper.toString(this, "handler", m_Handler, "handler: ");
}
/**
* Returns the class that the consumer accepts.
*
* @return the Class of objects that can be processed
*/
@Override
public Class[] accepts() {
return new Class[]{String.class, File.class};
}
/**
* Returns the class of objects that it generates.
*
* @return the Class of the generated tokens
*/
@Override
public Class[] generates() {
return new Class[]{m_Handler.getExperimentClass()};
}
/**
* Executes the flow item.
*
* @return null if everything is fine, otherwise error message
*/
@Override
protected String doExecute() {
String result;
PlaceholderFile file;
Object exp;
result = null;
if (m_InputToken.getPayload() instanceof File)
file = new PlaceholderFile((File) m_InputToken.getPayload());
else
file = new PlaceholderFile((String) m_InputToken.getPayload());
exp = m_Handler.load(file.getAbsoluteFile());
if (exp == null)
result = "Failed to load experiment: " + file;
else
m_OutputToken = new Token(exp);
return result;
}
} |
$(document).ready(function() {
$("#search_box").keyup(function() {
$("#search_div").load("/corect/ajax_search/" + $("#search_box").val());
});
$("#search_box").bind("enterKey",function() {
$("#search_div").load("/corect/ajax_search/" + $("#search_box").val());
});
}); |
#ifndef _FILE_EXT_H
#define _FILE_EXT_H
#ifdef HAVE_DYNAMIC
#ifdef _WIN32
#define EXT_EXECUTABLES "dll"
#elif defined(__APPLE__) || defined(__MACH__)
#define EXT_EXECUTABLES "dylib"
#else
#define EXT_EXECUTABLES "so"
#endif
#else
#if defined(__CELLOS_LV2__)
#define EXT_EXECUTABLES "self|SELF|bin|BIN"
#define SALAMANDER_FILE "EBOOT.BIN"
#define PLATFORM_NAME "ps3"
#elif defined(PSP)
#define EXT_EXECUTABLES "pbp|PBP"
#define SALAMANDER_FILE "EBOOT.PBP"
#define PLATFORM_NAME "psp"
#elif defined(_XBOX1)
#define EXT_EXECUTABLES "xbe|XBE"
#define SALAMANDER_FILE "default.xbe"
#define PLATFORM_NAME "xdk1"
#elif defined(_XBOX360)
#define EXT_EXECUTABLES "xex|XEX"
#define SALAMANDER_FILE "default.xex"
#define PLATFORM_NAME "xdk360"
#elif defined(GEKKO)
#define EXT_EXECUTABLES "dol|DOL"
#define SALAMANDER_FILE "boot.dol"
#ifdef HW_RVL
#define PLATFORM_NAME "wii"
#else
#define PLATFORM_NAME "ngc"
#endif
#elif defined(ANDROID)
#define PLATFORM_NAME "android"
#elif defined(IOS)
#define PLATFORM_NAME "ios"
#elif defined(__QNX__)
#define PLATFORM_NAME "qnx"
#elif defined(EMSCRIPTEN)
#define EXT_EXECUTABLES ""
#endif
#endif
#endif |
import bisect
import json
import progress
import zoning
def <API key>(stream):
old_pos = stream.tell()
stream.seek(0, 2)
size = f.tell()
stream.seek(old_pos, 0)
return size
class NullFeatures(object):
def __init__(self, map1_len, map2_len):
self._mapping = map1_len * map2_len
self._max_mapping = self._mapping * map1_len + 1
self.regions = []
def add_null_region(self, fromn, fromi, ton, toi):
fromid = fromn * self._mapping + fromi
toid = ton * self._mapping + toi
bisect.insort_right(self.regions, (fromid, toid))
def is_null(self, n, i):
fid = n * self._mapping + i
j = bisect.bisect_right(self.regions, (fid, self._max_mapping))
if j == 0:
return False
else:
return self.regions[j - 1][1] >= fid
def load_save_file(stream, logger = None):
if hasattr(stream, "name"):
estimator = progress.TimeEstimator(logger, 0, <API key>(stream), precision = 1)
else:
estimator = None
save = {}
map1_len = None
map2_len = None
null_features = None
last_index = None
for line in stream:
if estimator is not None:
estimator.increment(len(line))
data = json.loads(line)
if map1_len is None:
map1_len = data["MAP1_LEN"]
map2_len = data["MAP2_LEN"]
save[None] = null_features = NullFeatures(map1_len, map2_len)
continue;
elif data[0] is None:
fromn, fromi = data[1]
ton, toi = data[2]
last_index = data[2]
null_features.add_null_region(fromn, fromi, ton, toi)
#for n in range(fromn, ton + 1):
# for i in range(fromi, map2_len):
# if n == ton and i == toi:
# break
# save[(n, i)] = None
elif data[2] is None:
save[(data[0], data[1])] = None
last_index = data[:2]
else:
features = []
for f in data[2:]:
if f is None:
features.append(None)
else:
features.append(zoning.parse_feature(f))
save[(data[0], data[1])] = features
last_index = data[:2]
save["LAST_INDEX"] = last_index
return save
class StateSaver(object):
def __init__(self, save_state_to, flush_interval = 50000):
self.stream = save_state_to
self.flush_interval = flush_interval
self.current_state_flush = 0
self.last_state_flush = 0
self.nulls_start = None
def record_map_sizes(self, map1_len, map2_len):
if self.stream is not None:
self.stream.write("%s\n" % json.dumps({"MAP1_LEN" : map1_len, "MAP2_LEN" : map2_len}))
def record(self, n, i, *args):
if self.stream is None:
return
self.current_state_flush += 1
flush = (self.current_state_flush - self.last_state_flush) >= self.flush_interval
if args:
if self.nulls_start:
line = "[null,[%d,%d],[%d,%d]]" % (self.nulls_start[0], self.nulls_start[1], n, i)
self.stream.write("%s\n" % line)
flush = True
self.nulls_start = None
a = []
for arg in args:
if arg is None:
a.append(None)
else:
a.append(arg.to_geo())
line = json.dumps([n, i] + a)
self.stream.write("%s\n" % line)
else:
if self.nulls_start is None:
self.nulls_start = [n, i]
#line = json.dumps([n, i, None])
if flush:
self.last_state_flush = self.current_state_flush
self.stream.flush()
def intersect(map1, map2, logger = None, previous_save = None, save_state_to = None, <API key> = None, <API key> = 600):
if logger is None:
logger = lambda m : None
map1 = zoning.ModifiableMap(map1)
map2 = zoning.ModifiableMap(map2)
estimator = progress.TimeEstimator(logger, 0, len(map1) * len(map2), precision = 2, interval = 3.0)
saver = StateSaver(save_state_to)
<API key> = 0
if previous_save is not None:
logger("\r%s\rFast-forwarding using saved state...\n" % (' ' * 40))
last_n, last_i = previous_save["LAST_INDEX"]
estimator.end_value = (last_n - 1) * len(map2) + last_i
else:
saver.record_map_sizes(len(map1), len(map2))
for n, f1 in enumerate(map1):
if f1.geometry.is_empty:
continue
for i, f2 in enumerate(map2):
if previous_save is not None and n <= last_n:
if (n, i) in previous_save:
state = previous_save[(n,i)]
if state is None:
continue
map2[i] = state[0]
if state[1] is not None:
map2.append(state[1])
map1[n] = state[2]
estimator.increment()
if map1[n].geometry.is_empty:
estimator.increment(len(map2) - i)
break
continue
elif previous_save[None].is_null(n, i):
estimator.increment()
continue
elif n < last_n or (n == last_n and i <= last_i):
estimator.increment()
continue
elif n == last_n and i == last_i:
estimator.end_value = len(map1) * len(map2)
logger("\r%s\rDone.\n" % (' ' * 40))
estimator.update(n * len(map2) + i)
if f2.geometry.is_empty:
saver.record(n, i)
continue
try:
isect = f1.geometry.intersection(f2.geometry)
except Exception as e:
logger("\r%s\rError: %s\n" % (' ' * 40, e))
estimator.force_next_refresh()
continue
if isect.is_empty:
saver.record(n, i)
continue
area_delta = 10.0 # square meters
new_feature = zoning.ZoningFeature("%s->%s" % (f1.objectid, f2.objectid), f2.zoning, isect, f2.old_zoning + f1.zoning)
new_state = [None, None, None]
if new_feature.area() < area_delta:
# The intersection is less than area_delta square meters, so it's probably just floating point error.
# Skip it!
saver.record(n, i)
continue
elif f2.area() - area_delta < new_feature.area():
# the intersection is almost covering the entire preexisting area, so just assume that they're identical.
new_feature = zoning.ZoningFeature("%s->%s" % (f1.objectid, f2.objectid), f2.zoning, f2.geometry, f2.old_zoning + f1.zoning)
else:
# add a new feature containing the portion of f2 that does not intersect with f1
new_geom = f2.geometry.difference(new_feature.geometry)
if not new_geom.is_empty:
map2.append(zoning.ZoningFeature("%s.2" % f2.objectid, f2.zoning, new_geom, f2.old_zoning))
estimator.end_value = len(map1) * len(map2)
new_state[1] = map2[-1]
map2[i] = new_feature
new_state[0] = map2[i]
logger("\r%s\rPlot %s (%.02f acres) -> %s (%.02f acres) went from %s to %s\n" % (' ' * 40, f1.objectid, zoning.<API key>(f1.area()), f2.objectid, zoning.<API key>(new_feature.area()), f1.zoning, f2.zoning))
estimator.force_next_refresh()
# Delete the portion of overlap in f1 to hopefully speed up further comparisons:
# (This is making the assumption that the zoning regions in map2 are non-overlapping)
map1[n] = zoning.ZoningFeature(f1.objectid, f1.zoning, f1.geometry.difference(isect))
new_state[2] = map1[n]
saver.record(n, i, *new_state)
if <API key> and estimator.get_time() - <API key> >= <API key>:
# do an incremental save once every <API key> seconds
logger("\r%s\rDoing an incremental save to %s..." % (' ' * 40, <API key>))
<API key> = estimator.get_time()
with open(<API key>, 'w') as f:
map2.save(f)
if map1[n].geometry.is_empty:
break
logger('\n')
return map2
if __name__ == "__main__":
import os
import sys
with open(sys.argv[1], 'r') as f1:
with open(sys.argv[2], 'r') as f2:
def logger(msg):
sys.stderr.write(msg)
sys.stderr.flush()
previous_save = None
save_state_to = None
if len(sys.argv) >= 4:
if os.path.exists(sys.argv[3]):
logger('Loading save state...\n')
with open(sys.argv[3], 'r') as f:
previous_save = load_save_file(f)
logger("\r%s\rLoaded.\n" % (' ' * 40))
save_state_to = open(sys.argv[3], 'a')
try:
intersected = intersect(zoning.ZoningMap(f1), zoning.ZoningMap(f2), logger = logger, previous_save = previous_save, save_state_to = save_state_to, <API key> = "%s.incremental" % sys.argv[3])
finally:
if save_state_to is not None:
save_state_to.close()
intersected.save(sys.stdout)
os.unlink("%s.incremental" % sys.argv[3])
## Sanity check:
#import StringIO
#output = StringIO.StringIO()
#intersected.save(output)
#output.seek(0)
#list(zoning.ZoningMap(output))
#output.close() |
"""Collection of DIRAC useful file related modules.
.. warning::
By default on Error they return None.
"""
# pylint: skip-file
# getGlobbedFiles gives "RuntimeError: maximum recursion depth exceeded" in pylint
import os
import hashlib
import random
import glob
import sys
import re
import errno
__RCSID__ = "$Id$"
# Translation table of a given unit to Bytes
# I know, it should be kB...
<API key> = {
'B': 1,
'KB': 1024,
'MB': 1024 *
1024,
'GB': 1024 *
1024 *
1024,
'TB': 1024 *
1024 *
1024 *
1024,
'PB': 1024 *
1024 *
1024 *
1024 *
1024}
def mkDir(path):
""" Emulate 'mkdir -p path' (if path exists already, don't raise an exception)
"""
try:
if os.path.isdir(path):
return
os.makedirs(path)
except OSError as osError:
if osError.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def mkLink(src, dst):
""" Protected creation of simbolic link
"""
try:
os.symlink(src, dst)
except OSError as osError:
if osError.errno == errno.EEXIST and os.path.islink(dst) and os.path.realpath(dst) == src:
pass
else:
raise
def makeGuid(fileName=None):
"""Utility to create GUID. If a filename is provided the
GUID will correspond to its content's hexadecimal md5 checksum.
Otherwise a random seed is used to create the GUID.
The format is capitalized 8-4-4-4-12.
.. warning::
Could return None in case of OSError or IOError.
:param string fileName: name of file
"""
myMd5 = hashlib.md5()
if fileName:
try:
with open(fileName, 'r') as fd:
data = fd.read(10 * 1024 * 1024)
myMd5.update(data)
except BaseException:
return None
else:
myMd5.update(str(random.getrandbits(128)))
md5HexString = myMd5.hexdigest().upper()
return generateGuid(md5HexString, "MD5")
def generateGuid(checksum, checksumtype):
""" Generate a GUID based on the file checksum
"""
if checksum:
if checksumtype == "MD5":
checksumString = checksum
elif checksumtype == "Adler32":
checksumString = str(checksum).zfill(32)
else:
checksumString = ''
if checksumString:
guid = "%s-%s-%s-%s-%s" % (checksumString[0:8],
checksumString[8:12],
checksumString[12:16],
checksumString[16:20],
checksumString[20:32])
guid = guid.upper()
return guid
# Failed to use the check sum, generate a new guid
myMd5 = hashlib.md5()
myMd5.update(str(random.getrandbits(128)))
md5HexString = myMd5.hexdigest()
guid = "%s-%s-%s-%s-%s" % (md5HexString[0:8],
md5HexString[8:12],
md5HexString[12:16],
md5HexString[16:20],
md5HexString[20:32])
guid = guid.upper()
return guid
def checkGuid(guid):
"""Checks whether a supplied GUID is of the correct format.
The guid is a string of 36 characters [0-9A-F] long split into 5 parts of length 8-4-4-4-12.
.. warning::
As we are using GUID produced by various services and some of them could not follow
convention, this function is passing by a guid which can be made of lower case chars or even just
have 5 parts of proper length with whatever chars.
:param string guid: string to be checked
:return: True (False) if supplied string is (not) a valid GUID.
"""
reGUID = re.compile("^[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}$")
if reGUID.match(guid.upper()):
return True
else:
guid = [len(x) for x in guid.split("-")]
if (guid == [8, 4, 4, 4, 12]):
return True
return False
def getSize(fileName):
"""Get size of a file.
:param string fileName: name of file to be checked
The os module claims only OSError can be thrown,
but just for curiosity it's catching all possible exceptions.
.. warning::
On any exception it returns -1.
"""
try:
return os.stat(fileName)[6]
except OSError:
return - 1
def getGlobbedTotalSize(files):
"""Get total size of a list of files or a single file.
Globs the parameter to allow regular expressions.
:params list files: list or tuple of strings of files
"""
totalSize = 0
if isinstance(files, (list, tuple)):
for entry in files:
size = getGlobbedTotalSize(entry)
if size == -1:
size = 0
totalSize += size
else:
for path in glob.glob(files):
if os.path.isdir(path):
for content in os.listdir(path):
totalSize += getGlobbedTotalSize(os.path.join(path, content))
if os.path.isfile(path):
size = getSize(path)
if size == -1:
size = 0
totalSize += size
return totalSize
def getGlobbedFiles(files):
"""Get list of files or a single file.
Globs the parameter to allow regular expressions.
:params list files: list or tuple of strings of files
"""
globbedFiles = []
if isinstance(files, (list, tuple)):
for entry in files:
globbedFiles += getGlobbedFiles(entry)
else:
for path in glob.glob(files):
if os.path.isdir(path):
for content in os.listdir(path):
globbedFiles += getGlobbedFiles(os.path.join(path, content))
if os.path.isfile(path):
globbedFiles.append(path)
return globbedFiles
def getCommonPath(files):
"""Get the common path for all files in the file list.
:param files: list of strings with paths
:type files: python:list
"""
def properSplit(dirPath):
"""Splitting of path to drive and path parts for non-Unix file systems.
:param string dirPath: path
"""
nDrive, nPath = os.path.splitdrive(dirPath)
return [nDrive] + [d for d in nPath.split(os.sep) if d.strip()]
if not files:
return ""
commonPath = properSplit(files[0])
for fileName in files:
if os.path.isdir(fileName):
dirPath = fileName
else:
dirPath = os.path.dirname(fileName)
nPath = properSplit(dirPath)
tPath = []
for i in range(min(len(commonPath), len(nPath))):
if commonPath[i] != nPath[i]:
break
tPath .append(commonPath[i])
if not tPath:
return ""
commonPath = tPath
return tPath[0] + os.sep + os.path.join(*tPath[1:])
def getMD5ForFiles(fileList):
"""Calculate md5 for the content of all the files.
:param fileList: list of paths
:type fileList: python:list
"""
fileList.sort()
hashMD5 = hashlib.md5()
for filePath in fileList:
if os.path.isdir(filePath):
continue
with open(filePath, "rb") as fd:
buf = fd.read(4096)
while buf:
hashMD5.update(buf)
buf = fd.read(4096)
return hashMD5.hexdigest()
def convertSizeUnits(size, srcUnit, dstUnit):
""" Converts a number from a given source unit to a destination unit.
Example:
In [1]: convertSizeUnits(1024, 'B', 'kB')
Out[1]: 1
In [2]: convertSizeUnits(1024, 'MB', 'kB')
Out[2]: 1048576
:param size: number to convert
:param srcUnit: unit of the number. Any of ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB')
:param dstUnit: unit expected for the return. Any of ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB')
:returns: the size number converted in the dstUnit. In case of problem -sys.maxint is returned (negative)
"""
srcUnit = srcUnit.upper()
dstUnit = dstUnit.upper()
try:
convertedValue = float(size) * <API key>[srcUnit] / <API key>[dstUnit]
return convertedValue
# TypeError, ValueError: size is not a number
# KeyError: srcUnit or dstUnit are not in the conversion list
except (TypeError, ValueError, KeyError):
return -sys.maxsize
if __name__ == "__main__":
for p in sys.argv[1:]:
print "%s : %s bytes" % (p, getGlobbedTotalSize(p)) |
// File : exLayerMng.cs
// Author : Wu Jie
// Last Change : 11/06/2011 | 17:23:35 PM | Sunday,November
// Description :
// usings
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
A component to manage draw order
[ExecuteInEditMode]
[AddComponentMenu("ex2D Helper/Layer Manager")]
public class exLayerMng : exLayer {
// static
public static int <API key> ( exLayer _a, exLayer _b ) {
return _a.indentLevel - _b.indentLevel;
}
// non-serialized
List<exLayer> dirtyLayers = new List<exLayer>();
bool updateAll = false;
// functions
// Desc:
protected new void Awake () {
base.Awake();
}
// Desc:
void OnPreRender () {
UpdateLayers ();
}
// Desc:
public void UpdateLayers () {
if ( updateAll ) {
updateAll = false;
List<exLayer> layerList = new List<exLayer>();
List<exLayer> specialLayerList = new List<exLayer>();
float totalDepth = camera.farClipPlane - camera.nearClipPlane;
totalDepth -= 0.2f; // we leave 1.0 for both near and far clip
float startFrom = transform.position.z + camera.nearClipPlane + 0.1f;
int <API key> = 0;
for ( int i = 0; i < children.Count; ++i ) {
exLayer childLayer = children[i];
childLayer.indentLevel = 1;
<API key> += AddLayerRecursively ( childLayer, true, ref totalDepth, ref layerList );
}
float unitLayer = totalDepth/<API key>;
// normal layer depth calcualte
const int MAX_INDENT = 99999;
int specialIndentLevel = MAX_INDENT;
float curDepth = startFrom + unitLayer; // skip layerMng
for ( int i = 0; i < layerList.Count; ++i ) {
exLayer layer = layerList[i];
layer.depth = curDepth;
if ( layer.type != exLayer.Type.Normal ) {
specialLayerList.Add (layer);
specialIndentLevel = layer.indentLevel;
if ( layer.type == exLayer.Type.Dynamic )
curDepth += layer.range;
else if ( layer.type == exLayer.Type.Abstract )
curDepth += unitLayer;
}
else {
if ( layer.indentLevel <= specialIndentLevel ) {
// Debug.Log( layer.gameObject.name + " curDepth = " + curDepth + " , " + specialIndentLevel );
specialIndentLevel = MAX_INDENT;
curDepth += unitLayer;
}
}
}
// special layer depth calculate
for ( int i = 0; i < specialLayerList.Count; ++i ) {
exLayer layer = specialLayerList[i];
if ( layer.type == exLayer.Type.Dynamic )
<API key> ( layer );
else if ( layer.type == exLayer.Type.Abstract )
<API key> ( layer );
}
// assignment
for ( int i = 0; i < layerList.Count; ++i ) {
exLayer layer = layerList[i];
if ( layer.isDirty == false )
continue;
<API key> ( layer.transform.root, false );
}
}
else {
List<exLayer> layerList = new List<exLayer>();
// re-update special layers
for ( int i = 0; i < dirtyLayers.Count; ++i ) {
exLayer layer = dirtyLayers[i];
if ( layer.type == exLayer.Type.Dynamic )
layerList.AddRange ( <API key> ( layer ) );
else if ( layer.type == exLayer.Type.Abstract )
layerList.AddRange ( <API key> ( layer ) ) ;
}
// assignment
for ( int i = 0; i < layerList.Count; ++i ) {
exLayer layer = layerList[i];
if ( layer.isDirty == false )
continue;
<API key> ( layer.transform.root, true );
}
}
dirtyLayers.Clear();
}
// Desc:
void <API key> ( Transform _trans, bool _force ) {
exLayer layer = _trans.GetComponent<exLayer>();
if ( layer != null && (_force || layer.isDirty) ) {
layer.isDirty = false;
_trans.position = new Vector3 ( _trans.position.x, _trans.position.y, layer.depth );
}
foreach ( Transform child in _trans ) {
<API key> ( child, _force );
}
}
// Desc:
int AddLayerRecursively ( exLayer _curLayer,
bool _doCount,
ref float _totalDepth,
ref List<exLayer> _layerList ) {
int count = 1;
bool doCount = _doCount;
_curLayer.isDirty = true;
_layerList.Add ( _curLayer );
if ( _curLayer.type != exLayer.Type.Normal ) {
doCount = false;
if ( _curLayer.type == exLayer.Type.Dynamic ) {
_totalDepth -= _curLayer.range;
}
}
for ( int i = 0; i < _curLayer.children.Count; ++i ) {
exLayer childLayer = _curLayer.children[i];
childLayer.indentLevel = _curLayer.indentLevel + 1;
count += AddLayerRecursively ( childLayer, doCount, ref _totalDepth, ref _layerList );
}
if ( doCount == false )
return 1;
return count;
}
// Desc:
void <API key> ( exLayer _curLayer, float _depth ) {
_curLayer.depth = _depth;
for ( int i = 0; i < _curLayer.children.Count; ++i ) {
<API key> ( _curLayer.children[i], _depth );
}
}
// Desc:
List<exLayer> <API key> ( exLayer _curLayer ) {
float totalDepth = 0.0f;
List<exLayer> layerList = new List<exLayer>();
AddLayerRecursively ( _curLayer, true, ref totalDepth, ref layerList );
if ( layerList.Count > 1 ) {
float unitLayer = (float)_curLayer.range/(float)(layerList.Count-1);
float curDepth = _curLayer.depth;
for ( int i = 0; i < layerList.Count; ++i ) {
exLayer layer = layerList[i];
layer.depth = curDepth;
layer.isDirty = true;
if ( layer.type == exLayer.Type.Normal ) {
curDepth += unitLayer;
}
}
}
return layerList;
}
// Desc:
List<exLayer> <API key> ( exLayer _curLayer ) {
float totalDepth = 0.0f;
List<exLayer> layerList = new List<exLayer>();
AddLayerRecursively ( _curLayer, true, ref totalDepth, ref layerList );
float curDepth = _curLayer.depth;
for ( int i = 0; i < layerList.Count; ++i ) {
exLayer layer = layerList[i];
layer.depth = curDepth;
layer.isDirty = true;
}
return layerList;
}
// Desc:
public void AddDirtyLayer ( exLayer _layer ) {
if ( _layer.type == exLayer.Type.Normal ) {
updateAll = true;
}
else {
dirtyLayers.Add (_layer);
_layer.isDirty = true;
}
}
} |
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.util import dpidToStr
from pox.lib.addresses import EthAddr, IPAddr
from collections import namedtuple
import pox.lib.packet as pkt
import os
import string,sys,socket,json, subprocess
import thread
log = core.getLogger()
#globlal variables
#global received #Revisar si funciona
ip_honeypot=IPAddr("192.168.0.14")
mac_honey= EthAddr("00:19:e2:4d:ac:02")
#ip_dest = str(sys.argv[1])
#def thread_socket(): #thread 1
# global received
# s = socket.socket() # Create a socket object
# host = '192.168.254.254' #the host is receiving by interface 2
# port = 12345 # Reserve a port for your service.
# s.bind((host, port)) # Bind to the port
# s.listen(5) # Now wait for client connection.
# while True:
# c, addr = s.accept() # Establish connection with client.
# print 'Message from', addr
# received_data = c.recv(1024)
# global received
# received = received_data
# if received == "quit":
# print "Closing..."
# break
# c.close() # Close the socket connection
# thread.exit()
#return received_data
###openflow code
# global Interface, IP_dst, Port, MAC, IP_attack
class connect_test(EventMixin):
# Waits for OpenFlow switches to connect and makes them learning switches.
#Global variables of connect_test subclass
#global received
def __init__(self):
self.listenTo(core.openflow)
log.debug("Enabling Firewall Module")
def thread_socket(): #thread 1
global received
s = socket.socket() # Create a socket object
host = '192.168.254.254' #the host is receiving by interface 2
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Message from', addr
received_data = c.recv(1024)
global received
received = received_data
# if received == "quit":
# print "Closing..."
# break
c.close() # Close the socket connection
thread.exit()
def <API key> (self, event):
# log.debug("Connection %s" % (event.connection,))
# self.switches[str(event.dpid)] = LearningSwitch(event.connection, self.transparent)
print event.dpid
#thread.start_new_thread(thread_socket, tuple([]))
# global received
thread.start_new_thread(thread_socket,tuple([]))
global received
encoded_data = json.loads(received)
Interface=encoded_data[0]["Interface"]
IP_dst=encoded_data[0]["IP_dst"]
Port=encoded_data[0]["Port"]
MAC=encoded_data[0]["MAC"]
IP_attack=encoded_data[0]["IP_attack"]
ifaceid=Interface.split("eth")
ifaceid=ifaceid[1]
port_dst=Port.split("/")
port_dst=port_dst[0]
# print Interface
# print IP_dst
# print Port
# print MAC
# print IP_attack
directory= "cd /root/VMs/cfgvms " #virtual machine configuration directory
cmd= " grep -ri "
name= subprocess.check_output(directory + "&&" + cmd + MAC, shell=True)
aux_name=name.split(".cfg")
name=aux_name[0]
here i get the vif
command="xm domid " #getting de domain id
vmid=subprocess.check_output(command + name, shell=True)
aux_v=vmid.split("\n")
vmid=aux_v[0]
#vmid=45
#ifaceid=2
#tag1=`ovs-vsctl list port vif$vmid.$ifaceid | grep tag | awk '{print$3}'
##here i get the vlan tag
proceso= 'ovs-vsctl list port '
proceso2= '| grep tag |'
proceso3= " awk '{print $3}'"
# print "vif"+vmid+"."+Interface
vlan_tag = subprocess.check_output(proceso +"vif"+vmid+"."+ifaceid + proceso2 +proceso3 ,shell=True)
aux2=vlan_tag.split("\n")
vlan_tag=aux2[0]
print vlan_tag
my_match = of.ofp_match(dl_type = 0x800,
dl_vlan=vlan_tag,
nw_src=IP_attack,
nw_dst=IP_dst,
tp_dst=port_dst ) ### i got the flux from the attacker to the Bro
my_match.set_dst(IPAddr(ip_honeypot))
## i got this from antonio and ulysses
# def _handle_PacketIn (event):
# packet = event.parsed
##creating msg to match the correct vlan tag
# msg = of.ofp_flow_mod()
# msg.match.dl_type = 0x800
# msg.match.nw_src = ip_packet.srcip
# msg.match.nw_dst = ip_packet.dstip
# msg.match.dl_vlan = vlan_tag #it is like that???
## action = ofp_action_nw_addr.set_dst(IPAddr(ip_honeypot)) #this flux is send to the honeypot
##c.close() # Close the socket connection
def launch ():
core.registerNew(connect_test)
#t = threading.Thread(target=thread_socket)
#args=(Interface, IP_dst, Port, MAC,IP_attack))
#t2= threading.Thread(target=open_flow, args=(Interface, IP_dst, Port, MAC,IP_attack) )
#t.start()
#t2.start() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.