code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
INSERT INTO `payment_type` VALUES
(1,'Card','CARD',1,1,0,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(2,'Direct Debit','DIRECT-DEBIT',1,2,0,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(3,'Cash','CASH',0,3,0,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(4,'Cheque','CHEQUE',0,4,1,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(5,'Postal Order','POSTAL-ORDER',0,5,0,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(7,'Transition','TRANSITION',1,6,1,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1),
(9,'Manual Adjustment','MANUAL-ADJUSTMENT',1,7,1,1,'2016-12-20 11:02:12.000000',1,'2016-12-20 11:02:12.000000',1);
| dvsa/mot | mot-api/db/dev/populate/static-data/payment_type.sql | SQL | mit | 731 |
angular.module('africaXpress')
.controller('ShopController', function($scope, Item){
$scope.allItems;
$scope.getAll = function () {
Item.getAll().success(function(data){
$scope.allItems = data
});
};
$scope.getAll();
}); | ctodmia/africaexpress | client/controllers/shopcontroller.js | JavaScript | mit | 244 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Toastpf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Toastpf")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| cemtuver/toastpf | Toastpf/Properties/AssemblyInfo.cs | C# | mit | 2,340 |
//同一个键的值连续存储,使用find产生的迭代器连续删除n次,n是该键对应的值的个数
| hongmi/cpp-primer-4-exercises | chapter-10/10.26.cc | C++ | mit | 114 |
var REGEX = require('REGEX'),
MAX_SINGLE_TAG_LENGTH = 30,
create = require('DIV/create');
var parseString = function(parentTagName, htmlStr) {
var parent = create(parentTagName);
parent.innerHTML = htmlStr;
return parent;
};
var parseSingleTag = function(htmlStr) {
if (htmlStr.length > MAX_SINGLE_TAG_LENGTH) { return null; }
var singleTagMatch = REGEX.singleTagMatch(htmlStr);
return singleTagMatch ? [create(singleTagMatch[1])] : null;
};
module.exports = function(htmlStr) {
var singleTag = parseSingleTag(htmlStr);
if (singleTag) { return singleTag; }
var parentTagName = REGEX.getParentTagName(htmlStr),
parent = parseString(parentTagName, htmlStr);
var child,
idx = parent.children.length,
arr = Array(idx);
while (idx--) {
child = parent.children[idx];
parent.removeChild(child);
arr[idx] = child;
}
parent = null;
return arr.reverse();
};
| JosephClay/d-js | src/parser.js | JavaScript | mit | 975 |
<<<<<<< HEAD
=======
<header class="hide-on-large-only">
<img src="{{"assets/img/logo-mds-big.png"}}" alt="" style="width: 100%;">
</header>
>>>>>>> 9bc2ead780ab1fa06cd37135345925de18a2a3fd
| moredms/moredms-com | _includes/mobile_banner.html | HTML | mit | 192 |
// softlayer_scale_policy_trigger_resourceuse_watch - This is a specific watch for a resource use
// policy trigger.
package softlayer_scale_policy_trigger_resourceuse_watch
// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED
| sudorandom/softlayer-go-gen | methods/softlayer_scale_policy_trigger_resourceuse_watch/doc.go | GO | mit | 229 |
package seedu.jobs.logic.commands;
import java.io.IOException;
import com.google.common.eventbus.Subscribe;
import seedu.jobs.commons.core.EventsCenter;
import seedu.jobs.commons.events.storage.SavePathChangedEventException;
/* Change save path
*/
//@@author A0130979U
public class PathCommand extends Command {
public static final String COMMAND_WORD = "path";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Change save path. "
+ "Parameters: path [filename] \n"
+ "Example: " + COMMAND_WORD
+ " taskbook.xml";
private String path;
private boolean isValid;
public static final String MESSAGE_SUCCESS = "Save path has been successfully updated \n";
public static final String MESSAGE_INVALID_FILE_PATH = "This path is invalid";
public PathCommand(String path) {
this.path = path;
this.isValid = true;
EventsCenter.getInstance().registerHandler(this);
}
@Override
public CommandResult execute() throws IOException {
assert model != null;
model.changePath(path);
if (!isValid) {
throw new IOException(MESSAGE_INVALID_FILE_PATH);
}
return new CommandResult(String.format(MESSAGE_SUCCESS));
}
@Subscribe
public void handleSavePathChangedEventException(SavePathChangedEventException event) {
isValid = false;
}
}
//@@author
| CS2103JAN2017-F11-B1/main | src/main/java/seedu/jobs/logic/commands/PathCommand.java | Java | mit | 1,421 |
import { module, test } from "qunit";
import argvInjector from "inject-loader?nwjs/App!nwjs/argv";
module( "nwjs/argv" );
test( "Default values", assert => {
const argv = argvInjector({
"nwjs/App": {
argv: []
}
});
assert.propEqual(
argv.argv,
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
assert.deepEqual(
Object.keys( argv ).sort(),
[
"argv",
"parseCommand",
"ARG_GOTO",
"ARG_LAUNCH",
"ARG_LOGFILE",
"ARG_LOGLEVEL",
"ARG_MAX",
"ARG_MIN",
"ARG_RESET_WINDOW",
"ARG_TRAY",
"ARG_VERSIONCHECK"
].sort(),
"Exports the correct constants"
);
});
test( "Custom parameters", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
// boolean without values
"--tray",
"--max",
"--min",
"--reset-window",
// boolean with "no-" prefix
"--no-versioncheck",
// boolean with value
"--logfile=false",
// string
"--loglevel",
"debug",
"--goto",
"foo",
"--launch",
"bar",
"positional"
]
}
});
assert.propEqual(
argv,
{
"_": [ "positional" ],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": true,
"versioncheck": false,
"version-check": false,
"logfile": false,
"loglevel": "debug",
"l": "debug",
"goto": "foo",
"launch": "bar"
},
"Has the correct parameters"
);
});
test( "Aliases", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
"--hide",
"--maximize",
"--minimize",
"--no-version-check",
"-l",
"debug"
]
}
});
assert.propEqual(
argv,
{
"_": [],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": false,
"versioncheck": false,
"version-check": false,
"logfile": true,
"loglevel": "debug",
"l": "debug",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
});
test( "Parse command", assert => {
const { parseCommand } = argvInjector({
"nwjs/App": {
argv: [],
manifest: {
"chromium-args": "--foo --bar"
}
}
});
assert.propEqual(
// this is unfortunately how NW.js passes through the command line string from second
// application starts: parameters with leading dashes get moved to the beginning
parseCommand([
"/path/to/executable",
"--goto",
"--unrecognized-parameter-name",
"--foo",
"--bar",
"--user-data-dir=baz",
"--no-sandbox",
"--no-zygote",
"--flag-switches-begin",
"--flag-switches-end",
"foo"
].join( " " ) ),
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "foo",
"launch": ""
},
"Correctly parses parameters"
);
});
| bastimeyer/livestreamer-twitch-gui | src/test/tests/nwjs/argv.js | JavaScript | mit | 3,497 |
//
// AppController.h
// Spotify Menubar
//
// Created by Ruaridh Thomson on 06/06/2010.
// Copyright 2010 Life Up North/Ruaridh Thomson. All rights reserved.
//
// This software is distributed under licence. Use of this software
// implies agreement with all terms and conditions of the accompanying
// software licence.
#import <Cocoa/Cocoa.h>
#import <ShortcutRecorder/ShortcutRecorder.h>
#import <SDGlobalShortcuts/SDGlobalShortcuts.h>
@interface AppController : NSObject {
NSOperationQueue *queue;
NSTimer *spotifyChecker;
// Process Stuff
int numberOfProcesses;
NSMutableArray *processList;
int processID;
IBOutlet NSTextField *textfield;
int _selectedPID;
int _lastAttachedPID;
CGEventSourceRef theSource;
// Status menu stuff
NSStatusItem *statusItem;
NSStatusItem *playItem;
NSStatusItem *fwrdItem;
NSStatusItem *backItem;
IBOutlet NSView *statusView;
IBOutlet NSMenu *statusMenu;
// Interface Stuff
IBOutlet NSWindow *welcomeWindow;
IBOutlet SRRecorderControl *playPauseRecorder;
IBOutlet SRRecorderControl *skipForwardRecorder;
IBOutlet SRRecorderControl *skipBackRecorder;
KeyCombo ppGlobalHotkey;
KeyCombo sfGlobalHotkey;
KeyCombo sbGlobalHotkey;
IBOutlet NSButton *showDockIcon;
IBOutlet NSButton *showMenubarIcon;
IBOutlet NSButton *openAtLogin;
IBOutlet NSButton *showWelcomeWindow;
IBOutlet NSButton *openSpotifyOnLaunch;
IBOutlet NSButton *openSpotifyOnKeybind;
// Hidden Interface Stuff
IBOutlet NSButton *playPauseButton;
IBOutlet NSButton *skipForwardButton;
IBOutlet NSButton *skipBackButton;
// Preferences Stuff
IBOutlet NSWindow *prefWindow;
NSView *currentView;
IBOutlet NSView *prefContentView;
IBOutlet NSView *generalView;
IBOutlet NSView *shortcutsView;
IBOutlet NSView *helpView;
IBOutlet NSView *aboutView;
IBOutlet NSView *simbleView;
IBOutlet NSToolbar *prefToolbar;
IBOutlet NSToolbarItem *generalToolbarItem;
IBOutlet NSToolbarItem *shortcutsToolbarItem;
IBOutlet NSToolbarItem *advancedToolbarItem;
IBOutlet NSToolbarItem *helpToolbarItem;
IBOutlet NSToolbarItem *aboutToolbarItem;
IBOutlet NSToolbarItem *simblToolbarItem;
IBOutlet NSPopUpButton *menubarIconStyle;
}
- (int)numberOfProcesses;
- (void)obtainFreshProcessList;
- (BOOL)findProcessWithName:(NSString *)procNameToSearch;
- (IBAction)checkForProcesses:(id)sender;
- (IBAction)findProcessesWithName:(id)sender;
- (ProcessSerialNumber)getSpotifyProcessSerialNumber;
- (CGEventSourceRef)source;
- (NSOperationQueue *)operationQueue;
- (void)checkIsSpotifyActive;
- (BOOL)isSpotifyActive;
- (void)sendPlayPauseThreaded;
- (void)sendSkipBackThreaded;
- (void)sendSkipForwardThreaded;
- (void)pressHotkey: (int)hotkey withModifier: (unsigned int)modifier;
- (IBAction)openPreferences:(id)sender;
- (IBAction)openSpotifyPreferences:(id)sender;
- (IBAction)resetKeybinds:(id)sender;
- (IBAction)toggleOpenAtLogin:(id)sender;
- (void)toggleMenuForMiniControls;
- (IBAction)toggleMiniControls:(id)sender;
- (IBAction)switchMenubarIconStyle:(id)sender;
- (IBAction)openAboutWindow:(id)sender;
- (IBAction)switchPreferenceView:(id)sender;
- (void)loadView:(NSView *)theView;
- (IBAction)sendPlayPause:(id)sender;
- (IBAction)sendSkipForward:(id)sender;
- (IBAction)sendSkipBack:(id)sender;
- (IBAction)sendKeystroke:(id)sender;
- (IBAction)syncroniseUserDefaults:(id)sender;
- (IBAction)openURLLifeUpNorth:(id)sender;
- (IBAction)sendLUNemail:(id)sender;
- (IBAction)openUrlSimbl:(id)sender;
- (IBAction)openUrlLunPlugin:(id)sender;
- (void)setStatusItem;
- (void)addAppAsLoginItem;
- (void)deleteAppFromLoginItem;
- (IBAction)setApplicationIsAgent:(id)sender;
- (BOOL)shouldBeUIElement;
- (void)setShouldBeUIElement:(BOOL)hidden;
@end
| ruaridht/Spotify-Menubar | AppController.h | C | mit | 3,729 |
<section data-ng-controller="Page1Controller">
<md-grid-list
md-cols-sm="1" md-cols-md="2" md-cols-gt-md="6"
md-row-height-gt-md="1:1" md-row-height="2:2"
md-gutter="12px" md-gutter-gt-sm="8px" >
<md-grid-tile class="red" md-rowspan="1" md-colspan="2">
<md-grid-tile-footer>
<h3>TODAY</h3>
</md-grid-tile-footer>
</md-grid-tile>
<md-grid-tile class="green" md-rowspan="1" md-colspan="2">
<h1 class="md-display-3">70%</h1>
<md-grid-tile-footer>
<h3>YESTERDAY</h3>
</md-grid-tile-footer>
</md-grid-tile>
<md-grid-tile class="yellow" md-rowspan="1" md-colspan="2">
<h1 class="md-display-3">40%</h1>
<md-grid-tile-footer>
<h3>LAST WEEK</h3>
</md-grid-tile-footer>
</md-grid-tile>
</md-grid-list>
</section> | SamDC/MEANMaterial | public/modules/core/views/page1.client.view.html | HTML | mit | 829 |
package mobi.qubits.tradingapp.query;
import java.util.Date;
import org.springframework.data.annotation.Id;
public class QuoteEntity {
@Id
private String id;
private String symbol;
private String name;
private float open;
private float prevClose;
private float currentQuote;
private float high;
private float low;
private String date;
private String quoteTime;
private Date timestamp;
public QuoteEntity() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getOpen() {
return open;
}
public void setOpen(float open) {
this.open = open;
}
public float getPrevClose() {
return prevClose;
}
public void setPrevClose(float prevClose) {
this.prevClose = prevClose;
}
public float getCurrentQuote() {
return currentQuote;
}
public void setCurrentQuote(float currentQuote) {
this.currentQuote = currentQuote;
}
public float getHigh() {
return high;
}
public void setHigh(float high) {
this.high = high;
}
public float getLow() {
return low;
}
public void setLow(float low) {
this.low = low;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getQuoteTime() {
return quoteTime;
}
public void setQuoteTime(String quoteTime) {
this.quoteTime = quoteTime;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
| yizhuan/tradingac | src/main/java/mobi/qubits/tradingapp/query/QuoteEntity.java | Java | mit | 1,859 |
#!/usr/bin/python
""" fanhaorename.py
"""
import os
import os.path
import logging
import fileorganizer
from fileorganizer import _helper
from fileorganizer.replacename import _replacename
__author__ = "Jack Chang <wei0831@gmail.com>"
def _tagHelper(tag):
""" TODO
"""
result = ""
for c in tag:
if c.isalpha():
result += "[{0}{1}]".format(c.lower(), c.upper())
else:
result += c
return result
def fanhaorename(work_dir,
tag,
exclude=None,
mode=0,
wetrun=False,
this_name=os.path.basename(__file__)):
""" Batch Rename Fanhao
\b
Args:
work_dir (str): Working Directory
tag (str): Fanhao tag
find (str, optional): Regex string to find in filename/foldername
replace (str, optional): Regex string to replace in filename/foldername
exclude (str, optional): Regex string to exclude in mattches
mode (int, optional): 0=FILE ONLY, 1=FOLDER ONLY, 2=BOTH
wetrun (bool, optional): Test Run or not
"""
_find_dir = r"(.*)({0})(-|_| )*(\d\d\d)(.*)".format(_tagHelper(tag))
_replace_dir = r"{0}-\4".format(tag)
_find_file = _find_dir + r"(\.(.*))"
_replace_file = _replace_dir + r"\6"
_helper.init_loger()
this_run = "WET" if wetrun else "DRY"
loger = logging.getLogger(this_name)
loger.info("[START] === %s [%s RUN] ===", this_name, this_run)
loger.info("[DO] Rename \"%s\" fanhao in \"%s\"; Mode %s", tag, work_dir,
mode)
if mode in (0, 2): # mode 0 and 2
for item in _replacename(_find_file, _replace_file, work_dir, 0,
exclude):
item.commit() if wetrun else loger.info("%s", item)
if mode in (1, 2): # mode 1 and 2
for item in _replacename(_find_dir, _replace_dir, work_dir, 1,
exclude):
item.commit() if wetrun else loger.info("%s", item)
loger.info("[END] === %s [%s RUN] ===", this_name, this_run)
if __name__ == "__main__":
fileorganizer.cli.cli_fanhaorename()
| wei0831/fileorganizer | fileorganizer/fanhaorename.py | Python | mit | 2,156 |
<?php namespace Mitch\EventDispatcher;
class Dispatcher
{
private $listeners = [];
public function dispatch($event)
{
if (is_array($event)) {
$this->fireEvents($event);
return;
}
$this->fireEvent($event);
}
public function addListener($name, Listener $listener)
{
$this->listeners[$name][] = $listener;
}
private function fireEvents(array $events)
{
foreach ($events as $event) {
$this->fireEvent($event);
}
}
private function fireEvent(Event $event)
{
$listeners = $this->getListeners($event->getName());
if ( ! $listeners) {
return;
}
foreach ($listeners as $listener) {
$listener->handle($event);
}
}
private function getListeners($name)
{
if ( ! $this->hasListeners($name)) {
return;
}
return $this->listeners[$name];
}
private function hasListeners($name)
{
return isset($this->listeners[$name]);
}
}
| mitchellvanw/event-dispatcher | src/Dispatcher.php | PHP | mit | 1,085 |
using System;
using System.Runtime.InteropServices;
namespace UnityMathReference
{
[StructLayout(LayoutKind.Sequential)]
public struct Point3
{
#region Properties
public int x, y, z;
public static readonly Point3 one = new Point3(1);
public static readonly Point3 minusOne = new Point3(-1);
public static readonly Point3 zero = new Point3();
public static readonly Point3 right = new Point3(1, 0, 0);
public static readonly Point3 left = new Point3(-1, 0, 0);
public static readonly Point3 up = new Point3(0, 1, 0);
public static readonly Point3 down = new Point3(0, -1, 0);
public static readonly Point3 forward = new Point3(0, 0, 1);
public static readonly Point3 backward = new Point3(0, 0, -1);
#endregion
#region Constructors
public Point3(int value)
{
x = value;
y = value;
z = value;
}
public Point3(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Point3(Point2 point, int z)
{
x = point.x;
y = point.y;
this.z = z;
}
#endregion
#region Operators
// +
public static Point3 operator+(Point3 p1, Point3 p2)
{
return new Point3(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
}
public static Point3 operator+(Point3 p1, Point2 p2)
{
return new Point3(p1.x + p2.x, p1.y + p2.y, p1.z);
}
public static Point3 operator+(Point2 p1, Point3 p2)
{
return new Point3(p1.x + p2.x, p1.y + p2.y, p2.z);
}
public static Point3 operator+(Point3 p1, int p2)
{
return new Point3(p1.x + p2, p1.y + p2, p1.z + p2);
}
public static Point3 operator+(int p1, Point3 p2)
{
return new Point3(p1 + p2.x, p1 + p2.y, p1 + p2.z);
}
// -
public static Point3 operator-(Point3 p1, Point3 p2)
{
return new Point3(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z);
}
public static Point3 operator-(Point3 p1, Point2 p2)
{
return new Point3(p1.x - p2.x, p1.y - p2.y, p1.z);
}
public static Point3 operator-(Point2 p1, Point3 p2)
{
return new Point3(p1.x - p2.x, p1.y - p2.y, p2.z);
}
public static Point3 operator-(Point3 p1, int p2)
{
return new Point3(p1.x - p2, p1.y - p2, p1.z - p2);
}
public static Point3 operator-(int p1, Point3 p2)
{
return new Point3(p1 - p2.x, p1 - p2.y, p1 - p2.z);
}
public static Point3 operator-(Point3 p2)
{
return new Point3(-p2.x, -p2.y, -p2.z);
}
// *
public static Point3 operator*(Point3 p1, Point3 p2)
{
return new Point3(p1.x * p2.x, p1.y * p2.y, p1.z * p2.z);
}
public static Point3 operator*(Point3 p1, Point2 p2)
{
return new Point3(p1.x * p2.x, p1.y * p2.y, p1.z);
}
public static Point3 operator*(Point2 p1, Point3 p2)
{
return new Point3(p1.x * p2.x, p1.y * p2.y, p2.z);
}
public static Point3 operator*(Point3 p1, int p2)
{
return new Point3(p1.x * p2, p1.y * p2, p1.z * p2);
}
public static Point3 operator*(int p1, Point3 p2)
{
return new Point3(p1 * p2.x, p1 * p2.y, p1 * p2.z);
}
// /
public static Point3 operator/(Point3 p1, Point3 p2)
{
return new Point3(p1.x / p2.x, p1.y / p2.y, p1.z / p2.z);
}
public static Point3 operator/(Point3 p1, Point2 p2)
{
return new Point3(p1.x / p2.x, p1.y / p2.y, p1.z);
}
public static Point3 operator/(Point2 p1, Point3 p2)
{
return new Point3(p1.x / p2.x, p1.y / p2.y, p2.z);
}
public static Point3 operator/(Point3 p1, int p2)
{
return new Point3(p1.x / p2, p1.y / p2, p1.z / p2);
}
public static Point3 operator/(int p1, Point3 p2)
{
return new Point3(p1 / p2.x, p1 / p2.y, p1 / p2.z);
}
// ==
public static bool operator==(Point3 p1, Point3 p2) {return p1.x==p2.x && p1.y==p2.y && p1.z==p2.z;}
public static bool operator!=(Point3 p1, Point3 p2) {return p1.x!=p2.x || p1.y!=p2.y || p1.z!=p2.z;}
// convert
public Point2 ToPoint2()
{
return new Point2(x, y);
}
public Vec2 ToVec2()
{
return new Vec2(x, y);
}
public Vec3 ToVec3()
{
return new Vec3(x, y, z);
}
#endregion
#region Methods
public override bool Equals(object obj)
{
return obj != null && (Point3)obj == this;
}
public override string ToString()
{
return string.Format("<{0}, {1}, {2}>", x, y, z);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public bool Intersects(Rect3 rect)
{
return x >= rect.left && x <= rect.right && y >= rect.bottom && y <= rect.top && z >= rect.back && z <= rect.front;
}
public void Intersects(Rect3 rect, out bool result)
{
result = x >= rect.left && x <= rect.right && y >= rect.bottom && y <= rect.top && z >= rect.back && z <= rect.front;
}
public bool Intersects(Bound3 boundingBox)
{
return x >= boundingBox.left && x <= boundingBox.right && y >= boundingBox.bottom && y <= boundingBox.top && z >= boundingBox.back && z <= boundingBox.front;
}
public void Intersects(Bound3 boundingBox, out bool result)
{
result = x >= boundingBox.left && x <= boundingBox.right && y >= boundingBox.bottom && y <= boundingBox.top && z >= boundingBox.back && z <= boundingBox.front;
}
#endregion
}
} | zezba9000/UnityMathReference | Assets/Math/Point3.cs | C# | mit | 5,085 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_13) on Sun Jan 24 12:52:50 EST 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Class edu.uci.ics.jung.io.graphml.GraphMLReader2 (jung2 2.0.1 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class edu.uci.ics.jung.io.graphml.GraphMLReader2 (jung2 2.0.1 API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<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="../../../../../../../edu/uci/ics/jung/io/graphml/GraphMLReader2.html" title="class in edu.uci.ics.jung.io.graphml"><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="../../../../../../../overview-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?edu/uci/ics/jung/io/graphml//class-useGraphMLReader2.html" target="_top"><B>FRAMES</B></A>
<A HREF="GraphMLReader2.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>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>edu.uci.ics.jung.io.graphml.GraphMLReader2</B></H2>
</CENTER>
No usage of edu.uci.ics.jung.io.graphml.GraphMLReader2
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="navbar_bottom_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="../../../../../../../edu/uci/ics/jung/io/graphml/GraphMLReader2.html" title="class in edu.uci.ics.jung.io.graphml"><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="../../../../../../../overview-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?edu/uci/ics/jung/io/graphml//class-useGraphMLReader2.html" target="_top"><B>FRAMES</B></A>
<A HREF="GraphMLReader2.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>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2010 null. All Rights Reserved.
</BODY>
</HTML>
| tobyclemson/msci-project | vendor/jung-2.0.1/doc/edu/uci/ics/jung/io/graphml/class-use/GraphMLReader2.html | HTML | mit | 6,127 |
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class OrganizationType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('organizationName')
->add('organizationShortName')
->add('organizationPhone')
->add('organizationDescription')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Organization'
));
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_organization';
}
}
| Gordondalos/ereport-two | src/AppBundle/Form/OrganizationType.php | PHP | mit | 995 |
using System;
namespace Frog.Orm
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class PrimaryKeyAttribute : Attribute
{
public string Name { get; set; }
}
}
| suneg/frogdotnet | Frog.Orm/PrimaryKeyAttribute.cs | C# | mit | 208 |
import * as React from './dfvReact'
import { dfvFront } from "./dfvFront";
export interface PopWindowPara {
/**
* 是否不覆盖全屏
*/
notCover?: boolean;
/**
* 是否显示红色背景的错误提示框
*/
isErr?: boolean;
/**
* 自动关闭时间,为0则不自动关闭
*/
closeTime?: number;
}
export class dfvWindow {
//主窗口
private dialog: HTMLDivElement | undefined;
//cover层
private divCover: HTMLDivElement | undefined;
//内容层
private divContent: HTMLDivElement | undefined;
static coverZ = 999;
constructor() {
dfvWindow.coverZ++;
}
/**
* 添加一个黑色半透明的遮盖层
* @returns {dfvWindow}
*/
addCover() {
if (!this.divCover) {
this.divCover = document.createElement("div");
this.divCover.className = "cover_div cover_black"
this.divCover.style.zIndex = dfvWindow.coverZ + "";
document.body.appendChild(this.divCover);
}
return this;
}
/**
* 处理PopWindowPara参数
* @param para
* @returns {dfvWindow}
*/
procParas(para: PopWindowPara) {
if (para && para.closeTime! > 0) {
this.autoClose(para.closeTime)
}
this.isError = para.isErr!!;
if (!para.notCover)
this.addCover();
return this;
}
/**
* 是否显示红色错误提示样式
* @type {boolean}
*/
isError = false;
/**
* 显示窗口
* @param title 标题
* @param content 内容
* @returns {dfvWindow}
*/
public show(title: string | HTMLElement, content?: string | HTMLElement | null) {
if (this.dialog)
return this;
let c1 = this.isError ? "ba_tra_red" : "ba_tra_blue"
let c2 = this.isError ? "icon_err" : "icon_close"
this.dialog =
<div className={"pop_border anim_in " + c1}>
{
this.divContent =
<div className="pop_cont">
<div className="vmid pad5">
{title}
</div>
{content ? <div style="margin-top: 10px">{content}</div> : null}
</div>
}
<div className="absol_close">
<tt onclick={() => this.onButtonCancelClick()}
className={"rotate_hover " + c2} />
</div>
</div>
this.dialog!.style.zIndex = (dfvWindow.coverZ + 1) + "";
document.body.appendChild(this.dialog!);
this.reSize();
this.resizeTime = setInterval(this.reSize, 200);
return this;
}
/**
* 显示带一个【确定】按钮的窗口
* @param title
* @param content
* @param onOk 按钮回调
* @returns {dfvWindow}
*/
public showWithOk(title: string | HTMLElement,
content: string | HTMLElement | null,
onOk: (e: HTMLElement) => void) {
this.show(title, this.okWindow(content, onOk))
return this;
}
/**
* 关闭按钮点击事件回调
*/
onButtonCancelClick = () => {
this.close();
}
/**
* 将窗口设为自动关闭
* @param time 自动关闭时间:毫秒
* @returns {dfvWindow}
*/
autoClose(time: number = 3000) {
setTimeout(() => {
this.close()
}, time);
return this;
}
/**
* 关闭窗口
*/
close = () => {
try {
clearInterval(this.resizeTime);
//窗口已关闭
if (!this.divContent || !this.dialog) {
return;
}
if (this.divCover) {
try {
document.body.removeChild(this.divCover);
} catch (e) {
}
}
this.divCover = null as any;
this.divContent = null as any;
let dia = this.dialog;
this.dialog = undefined;
if (window.history.pushState != null) {
dia.className += " anim_out";
setTimeout(() => {
//窗口已关闭
try {
document.body.removeChild(dia);
} catch (e) {
}
}, 300)
} else {
try {
document.body.removeChild(dia);
} catch (e) {
}
}
} catch (e) {
dfvFront.onCatchError(e)
}
}
/**
* 修正窗口大小与位置
*/
private reSize = () => {
if (!this.dialog || !this.divContent)
return;
if (this.dialog.offsetWidth < document.documentElement!.clientWidth) {
let w = document.documentElement!.clientWidth - this.dialog.offsetWidth;
this.dialog.style.marginLeft = ((w >> 1) & (~3)) + "px";
}
this.divContent.style.maxWidth = document.documentElement!.clientWidth - 40 + "px";
if (this.dialog.offsetHeight < document.documentElement!.clientHeight) {
let h = (Math.floor((document.documentElement!.clientHeight - this.dialog.offsetHeight) / 3));
h = h & (~3);
this.dialog.style.marginTop = h + "px";
}
this.divContent.style.maxHeight = document.documentElement!.clientHeight - 45 + "px";
}
private resizeTime: any;
/**
* 确定按钮的文字
* @type {string}
*/
buttonOkText = "确定";
private okWindow(content: string | HTMLElement | null, onOk: (e: HTMLElement) => void) {
return (
<div>
<div>
{content}
</div>
<div class="h_m">
<button class="button_blue pad6-12 mar5t font_0 bold" onclick={e => onOk(e.currentTarget)}>
{this.buttonOkText}
</button>
</div>
</div>
)
}
} | rxaa/dfv | src/public/dfvWindow.tsx | TypeScript | mit | 6,167 |
namespace Teleimot.Web.Api.Mapping
{
using AutoMapper;
public interface IHaveCustomMappings
{
void CreateMappings(IConfiguration configuration);
}
}
| EmilPopov/C-Sharp | Web Services and Cloud/Exam/Teleimot_Exam2015/Web/Teleimot.Web.Api/Mapping/IHaveCustomMappings.cs | C# | mit | 177 |
module.exports.default = undefined;
| webpack/webpack-cli | test/build/config/undefined-default/webpack.config.js | JavaScript | mit | 36 |
var tpl = [
'<div id="{uuid}" class="datepicker ui-d-n">',
' <div class="datepicker__mask"></div>',
' <div class="datepicker__main">',
' <div class="datepicker__header">',
' <div class="datepicker__time-toggle"></div>',
' <div class="datepicker__time-selector-list">',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_year_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_year_text">{year}年</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_year_next">></a>',
' </div>',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_month_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_month_text">{month}月</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_month_next" >></a>',
' </div>',
' </div>',
' </div>',
' <div class="datepicker__panel">',
' <ul class="datepicker__week-list">',
' <li class="datepicker__week-item">日</li>',
' <li class="datepicker__week-item">一</li>',
' <li class="datepicker__week-item">二</li>',
' <li class="datepicker__week-item">三</li>',
' <li class="datepicker__week-item">四</li>',
' <li class="datepicker__week-item">五</li>',
' <li class="datepicker__week-item">六</li>',
' </ul>',
' <div class="datepicker__day-wrap">',
' <ul class="datepicker__day-list datepicker__day-list-curr">',
' {all_days}',
' </ul>',
' </div>',
' </div>',
' ',
' <div class="datepicker__footer">',
' <div class="datepicker__btn" id="_j_confirm_btn">确定</div>',
' <div class="datepicker__btn" id="_j_cancel_btn">取消</div>',
' </div>',
' </div>',
'</div>'
].join("");
module.exports = tpl;
| yuanzm/simple-date-picker | lib/datepicker_tpl.js | JavaScript | mit | 2,048 |
<?php
namespace Nf;
class Db
{
const FETCH_ASSOC = 2;
const FETCH_NUM = 3;
const FETCH_OBJ = 5;
const FETCH_COLUMN = 7;
private static $_connections = array();
public static $_forceStoreConnectionInInstance = null;
public static function factory($config)
{
if (! is_array($config)) {
// convert to an array
$conf = array();
$conf['adapter'] = $config->adapter;
$conf['params'] = (array) $config->params;
$conf['profiler'] = (array) $config->profiler;
} else {
$conf = $config;
}
$adapterName = get_class() . '\\Adapter\\' . $conf['adapter'];
$dbAdapter = new $adapterName($conf['params']);
$dbAdapter->setProfilerConfig($conf['profiler']);
return $dbAdapter;
}
public static function getConnection($configName, $alternateHostname = null, $alternateDatabase = null, $storeInInstance = true)
{
$config = \Nf\Registry::get('config');
if (!isset($config->db->$configName)) {
throw new \Exception('The adapter "' . $configName . '" is not defined in the config file');
}
if (self::$_forceStoreConnectionInInstance !== null) {
$storeInInstance = self::$_forceStoreConnectionInInstance;
}
$defaultHostname = $config->db->$configName->params->hostname;
$defaultDatabase = $config->db->$configName->params->database;
$hostname = ($alternateHostname !== null) ? $alternateHostname : $defaultHostname;
$database = ($alternateDatabase !== null) ? $alternateDatabase : $defaultDatabase;
if (isset($config->db->$configName->params->port)) {
$port = $config->db->$configName->params->port;
} else {
$port = null;
}
// if the connection has already been created and if we store the connection in memory for future use
if (isset(self::$_connections[$configName . '-' . $hostname . '-' . $database]) && $storeInInstance) {
return self::$_connections[$configName . '-' . $hostname . '-' . $database];
} else {
// optional profiler config
$profilerConfig = isset($config->db->$configName->profiler) ? (array)$config->db->$configName->profiler : null;
if ($profilerConfig != null) {
$profilerConfig['name'] = $configName;
}
// or else we create a new connection
$dbConfig = array(
'adapter' => $config->db->$configName->adapter,
'params' => array(
'hostname' => $hostname,
'port' => $port,
'username' => $config->db->$configName->params->username,
'password' => $config->db->$configName->params->password,
'database' => $database,
'charset' => $config->db->$configName->params->charset
),
'profiler' => $profilerConfig
);
// connection with the factory method
$dbConnection = self::factory($dbConfig);
if ($storeInInstance) {
self::$_connections[$configName . '-' . $hostname . '-' . $database] = $dbConnection;
}
return $dbConnection;
}
}
}
| jarnix/nofussframework | Nf/Db.php | PHP | mit | 3,365 |
/**
* Created by Administrator on 2015/2/3.
*/
var Task = require('../models/task') ;
//add task
exports.addTask = function(req,res){
var title = req.body.title,
content = req.body.content,
date = req.body.date,
duration = req.body.duration,
done = req.body.done,
frequency = req.body.frequency ;
Task.addTask(title,content,date,duration,frequency,done,function(task){
res.json({'status':1,'task':task}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//update task
exports.updateTask = function(req,res){
var id = req.params.task_id,
title = req.body.title,
content = req.body.content,
date = req.body.date,
duration = req.body.duration,
frequency = req.body.frequency,
done = req.body.done;
Task.updateTask(id,title,content,date,duration,frequency,done,function(task){
res.json({'status':1,'task':task}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//get all tasks
exports.getAllTasks = function(req,res){
Task.findAll(function(tasks){
console.log(tasks.length) ;
res.json({'status':1,'tasks':tasks}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//get task by id
exports.getTaskById = function(req,res){
var id = req.params.task_id ;
Task.findById(id,function(task){
res.json({'status':1,'task':task}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//delete task by id
exports.deleteTask = function(req,res){
var id = req.params.task_id ;
Task.delete(id,function(task){
res.json({'status':1,'task':task}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
/*
Task.addTask(title,content,date,duration,frequency,
function(task){
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
date;
//add task records
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , continue to next day
if(i % (frequency + 1) === 0)
continue ;
//take current date into consideration,so i must reduce 1
date = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.addTaskRecord(task_id,date,0,null,
function(obect,error){
//if error happened , remove all records related to task
TaskRecord.deleteTaskRecordByTaskId(task_id) ;
res.json({'status':0,'message':error}) ;
}) ;
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
*/
/*
Task.updateTask(id,title,content,date,duration,frequency,
function(task){
//update task records
if(reset){
//update task records by resetting all done record
//delete the old records by task id
TaskRecord.deleteTaskRecordByTaskId(id,function(){
//add new task records after delete old task records
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
intDate;
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , continue to next day
if(i % (frequency + 1) === 0)
continue ;
//take current date into consideration,so i must reduce 1
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.addTaskRecord(task_id,intDate,0,null,
function(object,error){
//if error happened , remove all records related to task
TaskRecord.deleteTaskRecordByTaskId(task_id) ;
res.json({'status':0,'message':error}) ;
}) ;
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}else{
//update task records by overriding the old record
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
intDate;
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , delete the exist record
if(i % (frequency + 1) === 0){
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.findByTaskIdAndDate(task_id,intDate,function(records){
//exist a record,so delete the exist record
if(records.length !== 0)
records[0].destroy() ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}else{
//take current date into consideration,so i must reduce 1
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
//not exist a record so add new record
TaskRecord.findByTaskIdAndDate(task_id,intDate,function(records){
if(records.length === 0){
TaskRecord.addTaskRecord(task_id,intDate,0) ;
}
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
*/ | lakb248/CouplesWallet | controllers/taskController.js | JavaScript | mit | 6,193 |
<?php namespace App\Models\Soundcloud;
use App\Models\SocialModel;
class User extends SocialModel {
protected $table = 'social_soundcloud_users';
}
| rex/prex.io | app/Models/Soundcloud/User.php | PHP | mit | 153 |
(function () {
'use strict';
angular
.module('password', [
'ngMaterial',
/*@@DIST-TEMPLATE-CACHE*/
'ngRoute',
'password.analytics',
'password.title',
'password.nav',
'password.welcome',
'password.forgot',
'password.recovery',
'password.change',
'password.profile',
'password.mfa',
'password.reset',
'password.help',
'password.logo'
]);
})();
| silinternational/idp-pw-ui | app/password.module.js | JavaScript | mit | 513 |
# message-socket
> A TCP client socket with customizable message parsing, automatic restoration of lost connections, outgoing message queueing, and more
[![NPM Version][npm-image]][npm-url]
[](LICENSE.md)
message-socket is a Node.js library that makes writing raw TCP clients much easier. Two features are primarily responsible for this ease of use: customizable incoming message parsing, and queueing of outgoing messages during lost connections.
But those aren't the `MessageSocket`'s only tricks! Just like plain `net.Socket` objects, `MessageSocket`s can act as as duplex streams, but they can also be easily converted to `Observable`s of incoming messages.
## Getting Started
message-socket is distributed through NPM:
```sh
npm install message-socket
# or, if you prefer:
yarn add message-socket
```
## Examples
For these examples, assume that `echo.example.com` is an [echo server](https://en.wikipedia.org/wiki/Echo_Protocol). If you need one to test with, try this:
```sh
sudo socat PIPE TCP-LISTEN:7,fork
```
By default, `MessageSocket` will treat the entire incoming buffer as a single message encoded in utf8. However, this behavior can be easily customized by providing either a `RegExp` or a parsing function. The encoding can also be changed, or removed entirely if you need a binary `Buffer`.
```javascript
import MessageSocket from 'message-socket';
const sock = new MessageSocket('echo.example.com', 7);
sock.on('data', function(message) {
console.dir(message)
});
sock.send("My message");
sock.close();
// 'My message' is printed to the console
```
In this example, the 'data' event is fired twice because the `RegExp` matches twice on the given buffer.
```javascript
import MessageSocket from 'message-socket';
let sock = new MessageSocket('echo.example.com', 7, /([^:]+):/g);
sock.on('data', function(message) {
console.dir(message) # prints 'My message'
});
sock.send("My:message:");
sock.close();
// 'My' is printed to the console
// 'message' is printed to the console.
```
The final constructor argument is an optional encoding to be used instead of `utf8`; passing `null` will cause the socket to return binary `Buffer` objects instead of strings.
If a simple `RegExp` isn't enough to parse your messages, you an provide a parsing function:
```javascript
function parseMessage(buffer) {
// Do the actual parsing work
// ...
// for the below, assume:
// - messages is an array of parsed messages
// - leftovers is whatever data was left at the end of the buffer that does not represent an entire message
return [ messages, leftovers ];
}
```
Another helpful feature of the `MessageSocket` is that it can help you weather temporary connection losses without losing messages. If the underlying network connection should happen to get closed, outgoing messages will start going into a queue. Each attempt to send another message will trigger an attempt to reconnect. Upon successful reconnection, pending messages will be sent. As of now, this behavior is not configurable, but future enhancements could include controlling the size and lifetime of the queue, or disabling it entirely.
A `MessageSocket` can also be easily converted to an `Observable` of messages:
```javascript
import MessageSocket from 'message-socket';
const sock = new MessageSocket('echo.example.com', 7);
sock
.asObservable()
.subscribe(
msg => console.dir(msg)
)
sock.send("My message");
sock.close();
// 'My message' is printed to the console
```
Or with a more feature-rich Observable library:
```javascript
import MessageSocket from 'message-socket';
import { Observable } from 'rxjs';
const sock = new MessageSocket('echo.example.com', 7);
Observable
.from(
sock
)
.map(x => x.toUpperCase()
.subscribe(
msg => console.dir(msg)
)
sock.send("My message");
sock.close();
// 'MY MESSAGE' is printed to the console
```
## Compatibility
`message-socket` is built to support Node.js version 6.0 or higher.
## Contributing
Contributions are of course always welcome. If you find problems, please report them in the [Issue Tracker](http://www.github.com/forty2/message-socket/issues/). If you've made an improvement, open a [pull request](http://www.github.com/forty2/message-socket/pulls).
Getting set up for development is very easy:
```sh
git clone <your fork>
cd message-socket
yarn
```
And the development workflow is likewise straightforward:
```sh
# make a change to the src/ file, then...
yarn build
node dist/index.js
# or if you want to clean up all the leftover build products:
yarn run clean
```
## Release History
* 1.0.4
* Minor debugging updates
* 1.0.0
* The first release.
## Meta
Zach Bean – zb@forty2.com
Distributed under the MIT license. See [LICENSE](LICENSE.md) for more detail.
[npm-image]: https://img.shields.io/npm/v/message-socket.svg?style=flat
[npm-url]: https://npmjs.org/package/message-socket
| forty2/message-socket | README.md | Markdown | mit | 5,016 |
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<meta http-equiv="refresh" content="5; url={{.SiteName}}/">
<title>Creating Site - Renfish</title>
{{template "Header" .}}
</head>
<body>
{{template "Topbar" .}}
<div class="body-content">
Creating Site...
</div>
<br>
<br>
{{template "Bottombar"}}
</body>
</html>
| bjwbell/renfish | setup.html | HTML | mit | 522 |
<?php
namespace LaravelBox\Commands\Files;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use LaravelBox\Factories\ApiResponseFactory;
class DownloadFileCommand extends AbstractFileCommand
{
private $downloadPath;
public function __construct(string $token, string $local, string $remote)
{
$this->downloadPath = $local;
$this->token = $token;
$this->fileId = parent::getFileId($remote);
$this->folderId = parent::getFolderId(dirname($remote));
}
public function execute()
{
$fileId = $this->fileId;
$token = $this->token;
$url = "https://api.box.com/2.0/files/${fileId}/content";
$options = [
'sink' => fopen($this->downloadPath, 'w'),
'headers' => [
'Authorization' => "Bearer ${token}",
],
];
try {
$client = new Client();
$resp = $client->request('GET', $url, $options);
return ApiResponseFactory::build($resp);
} catch (ClientException $e) {
return ApiResponseFactory::build($e);
} catch (ServerException $e) {
return ApiResponseFactory::build($e);
} catch (TransferException $e) {
return ApiResponseFactory($e);
} catch (RequestException $e) {
return ApiResponseFactory($e);
}
}
}
| ryanvade/laravel-box | src/LaravelBox/Commands/Files/DownloadFileCommand.php | PHP | mit | 1,523 |
/*
* Copyright © 2012-2013 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Daniel Vetter <daniel.vetter@ffwll.ch>
*
*/
/*
* Testcase: Check whether prime import/export works on the same device
*
* ... but with different fds, i.e. the wayland usecase.
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <inttypes.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include "drm.h"
#include "ioctl_wrappers.h"
#include "drmtest.h"
#include "igt_debugfs.h"
#define BO_SIZE (16*1024)
static char counter;
volatile int pls_die = 0;
static void
check_bo(int fd1, uint32_t handle1, int fd2, uint32_t handle2)
{
char *ptr1, *ptr2;
int i;
ptr1 = gem_mmap(fd1, handle1, BO_SIZE, PROT_READ | PROT_WRITE);
ptr2 = gem_mmap(fd2, handle2, BO_SIZE, PROT_READ | PROT_WRITE);
igt_assert(ptr1);
/* check whether it's still our old object first. */
for (i = 0; i < BO_SIZE; i++) {
igt_assert(ptr1[i] == counter);
igt_assert(ptr2[i] == counter);
}
counter++;
memset(ptr1, counter, BO_SIZE);
igt_assert(memcmp(ptr1, ptr2, BO_SIZE) == 0);
munmap(ptr1, BO_SIZE);
munmap(ptr2, BO_SIZE);
}
static void test_with_fd_dup(void)
{
int fd1, fd2;
uint32_t handle, handle_import;
int dma_buf_fd1, dma_buf_fd2;
counter = 0;
fd1 = drm_open_any();
fd2 = drm_open_any();
handle = gem_create(fd1, BO_SIZE);
dma_buf_fd1 = prime_handle_to_fd(fd1, handle);
gem_close(fd1, handle);
dma_buf_fd2 = dup(dma_buf_fd1);
close(dma_buf_fd1);
handle_import = prime_fd_to_handle(fd2, dma_buf_fd2);
check_bo(fd2, handle_import, fd2, handle_import);
close(dma_buf_fd2);
check_bo(fd2, handle_import, fd2, handle_import);
close(fd1);
close(fd2);
}
static void test_with_two_bos(void)
{
int fd1, fd2;
uint32_t handle1, handle2, handle_import;
int dma_buf_fd;
counter = 0;
fd1 = drm_open_any();
fd2 = drm_open_any();
handle1 = gem_create(fd1, BO_SIZE);
handle2 = gem_create(fd1, BO_SIZE);
dma_buf_fd = prime_handle_to_fd(fd1, handle1);
handle_import = prime_fd_to_handle(fd2, dma_buf_fd);
close(dma_buf_fd);
gem_close(fd1, handle1);
dma_buf_fd = prime_handle_to_fd(fd1, handle2);
handle_import = prime_fd_to_handle(fd2, dma_buf_fd);
check_bo(fd1, handle2, fd2, handle_import);
gem_close(fd1, handle2);
close(dma_buf_fd);
check_bo(fd2, handle_import, fd2, handle_import);
close(fd1);
close(fd2);
}
static void test_with_one_bo_two_files(void)
{
int fd1, fd2;
uint32_t handle_import, handle_open, handle_orig, flink_name;
int dma_buf_fd1, dma_buf_fd2;
fd1 = drm_open_any();
fd2 = drm_open_any();
handle_orig = gem_create(fd1, BO_SIZE);
dma_buf_fd1 = prime_handle_to_fd(fd1, handle_orig);
flink_name = gem_flink(fd1, handle_orig);
handle_open = gem_open(fd2, flink_name);
dma_buf_fd2 = prime_handle_to_fd(fd2, handle_open);
handle_import = prime_fd_to_handle(fd2, dma_buf_fd2);
/* dma-buf selfimporting an flink bo should give the same handle */
igt_assert(handle_import == handle_open);
close(fd1);
close(fd2);
close(dma_buf_fd1);
close(dma_buf_fd2);
}
static void test_with_one_bo(void)
{
int fd1, fd2;
uint32_t handle, handle_import1, handle_import2, handle_selfimport;
int dma_buf_fd;
fd1 = drm_open_any();
fd2 = drm_open_any();
handle = gem_create(fd1, BO_SIZE);
dma_buf_fd = prime_handle_to_fd(fd1, handle);
handle_import1 = prime_fd_to_handle(fd2, dma_buf_fd);
check_bo(fd1, handle, fd2, handle_import1);
/* reimport should give us the same handle so that userspace can check
* whether it has that bo already somewhere. */
handle_import2 = prime_fd_to_handle(fd2, dma_buf_fd);
igt_assert(handle_import1 == handle_import2);
/* Same for re-importing on the exporting fd. */
handle_selfimport = prime_fd_to_handle(fd1, dma_buf_fd);
igt_assert(handle == handle_selfimport);
/* close dma_buf, check whether nothing disappears. */
close(dma_buf_fd);
check_bo(fd1, handle, fd2, handle_import1);
gem_close(fd1, handle);
check_bo(fd2, handle_import1, fd2, handle_import1);
/* re-import into old exporter */
dma_buf_fd = prime_handle_to_fd(fd2, handle_import1);
/* but drop all references to the obj in between */
gem_close(fd2, handle_import1);
handle = prime_fd_to_handle(fd1, dma_buf_fd);
handle_import1 = prime_fd_to_handle(fd2, dma_buf_fd);
check_bo(fd1, handle, fd2, handle_import1);
/* Completely rip out exporting fd. */
close(fd1);
check_bo(fd2, handle_import1, fd2, handle_import1);
}
static int get_object_count(void)
{
FILE *file;
int ret, scanned;
int device = drm_get_card();
char *path;
igt_drop_caches_set(DROP_RETIRE);
ret = asprintf(&path, "/sys/kernel/debug/dri/%d/i915_gem_objects", device);
igt_assert(ret != -1);
file = fopen(path, "r");
scanned = fscanf(file, "%i objects", &ret);
igt_assert(scanned == 1);
return ret;
}
static void *thread_fn_reimport_vs_close(void *p)
{
struct drm_gem_close close_bo;
int *fds = p;
int fd = fds[0];
int dma_buf_fd = fds[1];
uint32_t handle;
while (!pls_die) {
handle = prime_fd_to_handle(fd, dma_buf_fd);
close_bo.handle = handle;
ioctl(fd, DRM_IOCTL_GEM_CLOSE, &close_bo);
}
return (void *)0;
}
static void test_reimport_close_race(void)
{
pthread_t *threads;
int r, i, num_threads;
int fds[2];
int obj_count;
void *status;
uint32_t handle;
int fake;
/* Allocate exit handler fds in here so that we dont screw
* up the counts */
fake = drm_open_any();
obj_count = get_object_count();
num_threads = sysconf(_SC_NPROCESSORS_ONLN);
threads = calloc(num_threads, sizeof(pthread_t));
fds[0] = drm_open_any();
igt_assert(fds[0] >= 0);
handle = gem_create(fds[0], BO_SIZE);
fds[1] = prime_handle_to_fd(fds[0], handle);
for (i = 0; i < num_threads; i++) {
r = pthread_create(&threads[i], NULL,
thread_fn_reimport_vs_close,
(void *)(uintptr_t)fds);
igt_assert(r == 0);
}
sleep(5);
pls_die = 1;
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], &status);
igt_assert(status == 0);
}
close(fds[0]);
close(fds[1]);
obj_count = get_object_count() - obj_count;
igt_info("leaked %i objects\n", obj_count);
close(fake);
igt_assert(obj_count == 0);
}
static void *thread_fn_export_vs_close(void *p)
{
struct drm_prime_handle prime_h2f;
struct drm_gem_close close_bo;
int fd = (uintptr_t)p;
uint32_t handle;
while (!pls_die) {
/* We want to race gem close against prime export on handle one.*/
handle = gem_create(fd, 4096);
if (handle != 1)
gem_close(fd, handle);
/* raw ioctl since we expect this to fail */
/* WTF: for gem_flink_race I've unconditionally used handle == 1
* here, but with prime it seems to help a _lot_ to use
* something more random. */
prime_h2f.handle = 1;
prime_h2f.flags = DRM_CLOEXEC;
prime_h2f.fd = -1;
ioctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime_h2f);
close_bo.handle = 1;
ioctl(fd, DRM_IOCTL_GEM_CLOSE, &close_bo);
close(prime_h2f.fd);
}
return (void *)0;
}
static void test_export_close_race(void)
{
pthread_t *threads;
int r, i, num_threads;
int fd;
int obj_count;
void *status;
obj_count = get_object_count();
num_threads = sysconf(_SC_NPROCESSORS_ONLN);
threads = calloc(num_threads, sizeof(pthread_t));
fd = drm_open_any();
igt_assert(fd >= 0);
for (i = 0; i < num_threads; i++) {
r = pthread_create(&threads[i], NULL,
thread_fn_export_vs_close,
(void *)(uintptr_t)fd);
igt_assert(r == 0);
}
sleep(5);
pls_die = 1;
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], &status);
igt_assert(status == 0);
}
close(fd);
obj_count = get_object_count() - obj_count;
igt_info("leaked %i objects\n", obj_count);
igt_assert(obj_count == 0);
}
static void test_llseek_size(void)
{
int fd, i;
uint32_t handle;
int dma_buf_fd;
counter = 0;
fd = drm_open_any();
for (i = 0; i < 10; i++) {
int bufsz = 4096 << i;
handle = gem_create(fd, bufsz);
dma_buf_fd = prime_handle_to_fd(fd, handle);
gem_close(fd, handle);
igt_assert(prime_get_size(dma_buf_fd) == bufsz);
close(dma_buf_fd);
}
close(fd);
}
static void test_llseek_bad(void)
{
int fd;
uint32_t handle;
int dma_buf_fd;
counter = 0;
fd = drm_open_any();
handle = gem_create(fd, BO_SIZE);
dma_buf_fd = prime_handle_to_fd(fd, handle);
gem_close(fd, handle);
igt_require(lseek(dma_buf_fd, 0, SEEK_END) >= 0);
igt_assert(lseek(dma_buf_fd, -1, SEEK_END) == -1 && errno == EINVAL);
igt_assert(lseek(dma_buf_fd, 1, SEEK_SET) == -1 && errno == EINVAL);
igt_assert(lseek(dma_buf_fd, BO_SIZE, SEEK_SET) == -1 && errno == EINVAL);
igt_assert(lseek(dma_buf_fd, BO_SIZE + 1, SEEK_SET) == -1 && errno == EINVAL);
igt_assert(lseek(dma_buf_fd, BO_SIZE - 1, SEEK_SET) == -1 && errno == EINVAL);
close(dma_buf_fd);
close(fd);
}
igt_main
{
struct {
const char *name;
void (*fn)(void);
} tests[] = {
{ "with_one_bo", test_with_one_bo },
{ "with_one_bo_two_files", test_with_one_bo_two_files },
{ "with_two_bos", test_with_two_bos },
{ "with_fd_dup", test_with_fd_dup },
{ "export-vs-gem_close-race", test_export_close_race },
{ "reimport-vs-gem_close-race", test_reimport_close_race },
{ "llseek-size", test_llseek_size },
{ "llseek-bad", test_llseek_bad },
};
int i;
for (i = 0; i < ARRAY_SIZE(tests); i++) {
igt_subtest(tests[i].name)
tests[i].fn();
}
}
| rib/intel-gpu-tools | tests/prime_self_import.c | C | mit | 10,481 |
<section>
<div class="div-select-up-animal">
<h1>Selecciona el animal que quieres actualizar:
<select ng-model="updAnimal.animalSelected" ng-change="updAnimal.editAnimal(updAnimal.animalSelected)">
<option ng-repeat="item in updAnimal.allAnimals" ng-value="{{item.id}}">{{item.name}}</option>
</select>
</h1>
</div>
<div class="frm-UpdAnimal" ng-show="updAnimal.animalSelected">
<h3>Modificar el animal: {{updAnimal.animalToUpdate.name}}</h3>
<div class="div-img-detail">
Nombre animal:
<input type="text" value="{{updAnimal.animalToUpdate.name}}" ng-model="updAnimal.nameUpdAnimal" label="Animal" ng-class="{ 'has-error' : !updAnimal.nameUpdAnimal && updAnimal.formSend}">
<br><br>
Tipo Animal:
<select ng-model="updAnimal.typeUpdAnimal" ng-class="{ 'has-error' : !updAnimal.typeUpdAnimal && updAnimal.formSend }">
<option value="mamiferos">Mamiferos</option>
<option value="otros">Otros</option>
</select>
<br><br>
Imagen:
<input type="text" value="{{updAnimal.animalToUpdate.img}}" ng-model="updAnimal.imgUpdAnimal" label="Animal" ng-class="{ 'has-error' : !updAnimal.imgUpdAnimal && updAnimal.formSend}">
<br><br>
<div>
<div class="txt-error" ng-show="!showMsg && updAnimal.formSend">ERROR <br> Debe introducir todos los datos.</div>
</div>
<div class="button-bar">
<button ng-click="updAnimal.updAnimal()">Confirmar</button>
<button ng-click="updAnimal.goToMain()">Cancelar</button>
</div>
</div>
</div>
</section> | daniberc/TheAnimalShop | src/app/components/updAnimal/upd-animal-template.html | HTML | mit | 1,760 |
pyrdiff
=======
Python rdiff/rsync implementation (for experimental/learning purposes only)
| therealmik/pyrdiff | README.md | Markdown | mit | 93 |
<?php
/*
* This file is part of KoolKode BPMN.
*
* (c) Martin Schröder <m.schroeder2007@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types = 1);
namespace KoolKode\BPMN\Runtime\Behavior;
use KoolKode\BPMN\Engine\AbstractBoundaryActivity;
use KoolKode\BPMN\Engine\VirtualExecution;
use KoolKode\BPMN\Runtime\Command\CreateMessageSubscriptionCommand;
use KoolKode\Process\Node;
/**
* Message catch event bound to an event scope.
*
* @author Martin Schröder
*/
class MessageBoundaryEventBehavior extends AbstractBoundaryActivity
{
protected $message;
public function __construct(string $activityId, string $attachedTo, string $message)
{
parent::__construct($activityId, $attachedTo);
$this->message = $message;
}
/**
* {@inheritdoc}
*/
public function processSignal(VirtualExecution $execution, ?string $signal, array $variables = [], array $delegation = []): void
{
if ($signal !== $this->message) {
throw new \RuntimeException(\sprintf('Boundary event awaits message "%s", unable to process signal "%s"', $this->message, $signal));
}
$this->passVariablesToExecution($execution, $variables);
parent::processSignal($execution, $signal, $variables);
}
/**
* {@inheritdoc}
*/
public function createEventSubscriptions(VirtualExecution $execution, string $activityId, ?Node $node = null): void
{
$execution->getEngine()->executeCommand(new CreateMessageSubscriptionCommand($this->message, $execution, $activityId, $node, true));
}
}
| koolkode/bpmn | src/Runtime/Behavior/MessageBoundaryEventBehavior.php | PHP | mit | 1,724 |
const greetings = {
morning: ['God morgon!', 'Kaffe?', 'Ha en bra dag!', 'Hoppas du får en bra dag!', 'Sovit gott?'],
afternoon: ['Ganska fin du!', 'Trevlig eftermiddag!', 'Eftermiddags kaffe?', 'Glömde väl inte att fika?'],
evening: ['Trevlig kväll!', 'Ser bra ut!', 'Myskväll?!'],
};
module.exports = {
getMessage: function(callback) {
const d = new Date();
var hour = d.getHours();
if (hour >= 5 && hour < 12) {
return greetings.morning[Math.floor(Math.random() * greetings.morning.length)];
} else if (hour >= 12 && hour < 18) {
return greetings.afternoon[Math.floor(Math.random() * greetings.afternoon.length)];
} else if (hour >= 18 || (hour >= 0 && hour < 5)) {
return greetings.evening[Math.floor(Math.random() * greetings.evening.length)];
} else {
return 'Something wrong, hour is: ' + hour;
}
},
};
| jakkra/SmartMirror | util/messages.js | JavaScript | mit | 879 |
/* Copyright (c) 2017, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file test_hs_cell.c
* \brief Test hidden service cell functionality.
*/
#define HS_INTROPOINT_PRIVATE
#define HS_SERVICE_PRIVATE
#include "test.h"
#include "test_helpers.h"
#include "log_test_helpers.h"
#include "crypto_ed25519.h"
#include "hs_cell.h"
#include "hs_intropoint.h"
#include "hs_service.h"
/* Trunnel. */
#include "hs/cell_establish_intro.h"
/** We simulate the creation of an outgoing ESTABLISH_INTRO cell, and then we
* parse it from the receiver side. */
static void
test_gen_establish_intro_cell(void *arg)
{
(void) arg;
ssize_t ret;
char circ_nonce[DIGEST_LEN] = {0};
uint8_t buf[RELAY_PAYLOAD_SIZE];
trn_cell_establish_intro_t *cell_in = NULL;
crypto_rand(circ_nonce, sizeof(circ_nonce));
/* Create outgoing ESTABLISH_INTRO cell and extract its payload so that we
attempt to parse it. */
{
/* We only need the auth key pair here. */
hs_service_intro_point_t *ip = service_intro_point_new(NULL, 0);
/* Auth key pair is generated in the constructor so we are all set for
* using this IP object. */
ret = hs_cell_build_establish_intro(circ_nonce, ip, buf);
service_intro_point_free(ip);
tt_u64_op(ret, OP_GT, 0);
}
/* Check the contents of the cell */
{
/* First byte is the auth key type: make sure its correct */
tt_int_op(buf[0], OP_EQ, HS_INTRO_AUTH_KEY_TYPE_ED25519);
/* Next two bytes is auth key len */
tt_int_op(ntohs(get_uint16(buf+1)), OP_EQ, ED25519_PUBKEY_LEN);
/* Skip to the number of extensions: no extensions */
tt_int_op(buf[35], OP_EQ, 0);
/* Skip to the sig len. Make sure it's the size of an ed25519 sig */
tt_int_op(ntohs(get_uint16(buf+35+1+32)), OP_EQ, ED25519_SIG_LEN);
}
/* Parse it as the receiver */
{
ret = trn_cell_establish_intro_parse(&cell_in, buf, sizeof(buf));
tt_u64_op(ret, OP_GT, 0);
ret = verify_establish_intro_cell(cell_in,
(const uint8_t *) circ_nonce,
sizeof(circ_nonce));
tt_u64_op(ret, OP_EQ, 0);
}
done:
trn_cell_establish_intro_free(cell_in);
}
/* Mocked ed25519_sign_prefixed() function that always fails :) */
static int
mock_ed25519_sign_prefixed(ed25519_signature_t *signature_out,
const uint8_t *msg, size_t msg_len,
const char *prefix_str,
const ed25519_keypair_t *keypair) {
(void) signature_out;
(void) msg;
(void) msg_len;
(void) prefix_str;
(void) keypair;
return -1;
}
/** We simulate a failure to create an ESTABLISH_INTRO cell */
static void
test_gen_establish_intro_cell_bad(void *arg)
{
(void) arg;
ssize_t cell_len = 0;
trn_cell_establish_intro_t *cell = NULL;
char circ_nonce[DIGEST_LEN] = {0};
hs_service_intro_point_t *ip = NULL;
MOCK(ed25519_sign_prefixed, mock_ed25519_sign_prefixed);
crypto_rand(circ_nonce, sizeof(circ_nonce));
setup_full_capture_of_logs(LOG_WARN);
/* Easiest way to make that function fail is to mock the
ed25519_sign_prefixed() function and make it fail. */
cell = trn_cell_establish_intro_new();
tt_assert(cell);
ip = service_intro_point_new(NULL, 0);
cell_len = hs_cell_build_establish_intro(circ_nonce, ip, NULL);
service_intro_point_free(ip);
expect_log_msg_containing("Unable to make signature for "
"ESTABLISH_INTRO cell.");
teardown_capture_of_logs();
tt_i64_op(cell_len, OP_EQ, -1);
done:
trn_cell_establish_intro_free(cell);
UNMOCK(ed25519_sign_prefixed);
}
struct testcase_t hs_cell_tests[] = {
{ "gen_establish_intro_cell", test_gen_establish_intro_cell, TT_FORK,
NULL, NULL },
{ "gen_establish_intro_cell_bad", test_gen_establish_intro_cell_bad, TT_FORK,
NULL, NULL },
END_OF_TESTCASES
};
| hexxcointakeover/hexxcoin | src/tor/src/test/test_hs_cell.c | C | mit | 3,900 |
# class DesignComponent
class Mucomo::Model::DesignComponent
# @todo participant, meta, description
# this include adds the attributes id, name, title to this class.
include Mucomo::Model::HasIdentifiers
attr_accessor :media_type # media_type's range is a restricted vocabulary, see XML schema file
attr_accessor :required # boolean
attr_reader :design
def initialize
@required = true
@media_type = "undefined"
end
def required?
@required
end
def design=(new_design)
@design = new_design
@design.add_design_component(self) unless @design.contains_design_component?(self)
end
# @todo access to associated allocations
include Mucomo::Model::BelongsToCorpus
end | pmenke/mucomo | lib/mucomo/model/design_component.rb | Ruby | mit | 733 |
.component {
padding-top: 20px;
}
.currenttotal {
text-align: center;
}
| justone/leftovers | frontend/resources/public/css/app.css | CSS | mit | 77 |
module I18n
module Backend
class Simple
protected
def pluralize(locale, entry, count)
return entry unless entry.is_a?(Hash) and count
key = :zero if count == 0 && entry.has_key?(:zero)
locale_pluralize = lookup(locale, :pluralize)
if locale_pluralize && locale_pluralize.respond_to?(:call)
key ||= locale_pluralize.call(count)
else
key ||= default_pluralizer(count)
end
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
entry[key]
end
def default_pluralizer(count)
count == 1 ? :one : :other
end
end
end
end
| romanvbabenko/ukrainian | lib/ukrainian/backend/simple.rb | Ruby | mit | 678 |
package io.variability.jhipster.security;
import io.variability.jhipster.config.Constants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of AuditorAware based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
String userName = SecurityUtils.getCurrentUserLogin();
return (userName != null ? userName : Constants.SYSTEM_ACCOUNT);
}
}
| axel-halin/Thesis-JHipster | FML-brute/jhipsters/uaa/src/main/java/io/variability/jhipster/security/SpringSecurityAuditorAware.java | Java | mit | 548 |
import auth from '../auth';
import clone from 'clone';
import storage from './storage';
async function addBlockOrItem(dbConn, token, codeObj, props, type) {
let user = await auth.getUser(token);
console.log(`Adding new ${type} for user ${user.login}`);
let add;
let newType = {
code: codeObj,
name: props.name,
icon: 'code',
owner: user.login
};
if(type == 'item') {
add = storage.addItemType;
newType.crosshairIcon = props.crosshairIcon;
newType.adjacentActive = props.adjacentActive;
} else {
add = storage.addBlockType;
newType.material = props.material;
}
await add(dbConn, newType);
return newType;
}
async function updateBlockOrItemCode(dbConn, token, id, codeObj, type) {
let user = await auth.getUser(token);
console.log(`Updating ${type} ${id} for user ${user.login}`);
let get, add, update;
if(type == 'item') {
get = storage.getItemType;
add = storage.addItemType;
update = storage.updateItemType;
} else {
get = storage.getBlockType;
add = storage.addBlockType;
update = storage.updateBlockType;
}
let original = await get(dbConn, id);
if(original.owner != user.login) {
throw new Error(`${type} ${id} belongs to ${original.owner} - ${user.login} doesn't have access.`);
}
let updated = clone(original);
updated.code = codeObj;
delete updated.newerVersion;
await add(dbConn, updated);
original.newerVersion = updated.id;
await update(dbConn, original);
return updated;
}
export default {
async getToolbar(dbConn, token) {
let user = await auth.getUser(token);
return await storage.getToolbar(dbConn, user.login);
},
async setToolbarItem(dbConn, token, position, type, id) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, {type, id});
},
async removeToolbarItem(dbConn, token, position) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, null);
},
async getAll(dbConn) {
let itemTypes = await storage.getAllItemTypes(dbConn);
let blockTypes = await storage.getAllBlockTypes(dbConn);
return {
itemTypes,
blockTypes
};
},
async getItemTypes(dbConn, token, ids) {
return await storage.getItemTypes(dbConn, ids);
},
async getBlockTypes(dbConn, token, ids) {
return await storage.getBlockTypes(dbConn, ids);
},
async updateBlockCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'block');
},
async updateItemCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'item');
},
async addBlockType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'block');
},
async addItemType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'item');
}
};
| UnboundVR/metavrse-server | src/inventory/controller.js | JavaScript | mit | 2,973 |
<?php
/**
* Main DAV server class
*
* @package Sabre
* @subpackage DAV
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_DAV_Server {
/**
* Inifinity is used for some request supporting the HTTP Depth header and indicates that the operation should traverse the entire tree
*/
const DEPTH_INFINITY = -1;
/**
* Nodes that are files, should have this as the type property
*/
const NODE_FILE = 1;
/**
* Nodes that are directories, should use this value as the type property
*/
const NODE_DIRECTORY = 2;
/**
* XML namespace for all SabreDAV related elements
*/
const NS_SABREDAV = 'http://sabredav.org/ns';
/**
* The tree object
*
* @var Sabre_DAV_Tree
*/
public $tree;
/**
* The base uri
*
* @var string
*/
protected $baseUri = null;
/**
* httpResponse
*
* @var Sabre_HTTP_Response
*/
public $httpResponse;
/**
* httpRequest
*
* @var Sabre_HTTP_Request
*/
public $httpRequest;
/**
* The list of plugins
*
* @var array
*/
protected $plugins = array();
/**
* This array contains a list of callbacks we should call when certain events are triggered
*
* @var array
*/
protected $eventSubscriptions = array();
/**
* This is a default list of namespaces.
*
* If you are defining your own custom namespace, add it here to reduce
* bandwidth and improve legibility of xml bodies.
*
* @var array
*/
public $xmlNamespaces = array(
'DAV:' => 'd',
'http://sabredav.org/ns' => 's',
);
/**
* The propertymap can be used to map properties from
* requests to property classes.
*
* @var array
*/
public $propertyMap = array(
'{DAV:}resourcetype' => 'Sabre_DAV_Property_ResourceType',
);
public $protectedProperties = array(
// RFC4918
'{DAV:}getcontentlength',
'{DAV:}getetag',
'{DAV:}getlastmodified',
'{DAV:}lockdiscovery',
'{DAV:}resourcetype',
'{DAV:}supportedlock',
// RFC4331
'{DAV:}quota-available-bytes',
'{DAV:}quota-used-bytes',
// RFC3744
'{DAV:}supported-privilege-set',
'{DAV:}current-user-privilege-set',
'{DAV:}acl',
'{DAV:}acl-restrictions',
'{DAV:}inherited-acl-set',
);
/**
* This is a flag that allow or not showing file, line and code
* of the exception in the returned XML
*
* @var bool
*/
public $debugExceptions = false;
/**
* This property allows you to automatically add the 'resourcetype' value
* based on a node's classname or interface.
*
* The preset ensures that {DAV:}collection is automaticlly added for nodes
* implementing Sabre_DAV_ICollection.
*
* @var array
*/
public $resourceTypeMapping = array(
'Sabre_DAV_ICollection' => '{DAV:}collection',
);
/**
* Sets up the server
*
* If a Sabre_DAV_Tree object is passed as an argument, it will
* use it as the directory tree. If a Sabre_DAV_INode is passed, it
* will create a Sabre_DAV_ObjectTree and use the node as the root.
*
* If nothing is passed, a Sabre_DAV_SimpleCollection is created in
* a Sabre_DAV_ObjectTree.
*
* If an array is passed, we automatically create a root node, and use
* the nodes in the array as top-level children.
*
* @param Sabre_DAV_Tree|Sabre_DAV_INode|null $treeOrNode The tree object
*/
public function __construct($treeOrNode = null) {
if ($treeOrNode instanceof Sabre_DAV_Tree) {
$this->tree = $treeOrNode;
} elseif ($treeOrNode instanceof Sabre_DAV_INode) {
$this->tree = new Sabre_DAV_ObjectTree($treeOrNode);
} elseif (is_array($treeOrNode)) {
// If it's an array, a list of nodes was passed, and we need to
// create the root node.
foreach($treeOrNode as $node) {
if (!($node instanceof Sabre_DAV_INode)) {
throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode');
}
}
$root = new Sabre_DAV_SimpleCollection('root', $treeOrNode);
$this->tree = new Sabre_DAV_ObjectTree($root);
} elseif (is_null($treeOrNode)) {
$root = new Sabre_DAV_SimpleCollection('root');
$this->tree = new Sabre_DAV_ObjectTree($root);
} else {
throw new Sabre_DAV_Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre_DAV_Tree, Sabre_DAV_INode, an array or null');
}
$this->httpResponse = new Sabre_HTTP_Response();
$this->httpRequest = new Sabre_HTTP_Request();
}
/**
* Starts the DAV Server
*
* @return void
*/
public function exec() {
try {
$this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri());
} catch (Exception $e) {
$DOM = new DOMDocument('1.0','utf-8');
$DOM->formatOutput = true;
$error = $DOM->createElementNS('DAV:','d:error');
$error->setAttribute('xmlns:s',self::NS_SABREDAV);
$DOM->appendChild($error);
$error->appendChild($DOM->createElement('s:exception',get_class($e)));
$error->appendChild($DOM->createElement('s:message',$e->getMessage()));
if ($this->debugExceptions) {
$error->appendChild($DOM->createElement('s:file',$e->getFile()));
$error->appendChild($DOM->createElement('s:line',$e->getLine()));
$error->appendChild($DOM->createElement('s:code',$e->getCode()));
$error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString()));
}
$error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION));
if($e instanceof Sabre_DAV_Exception) {
$httpCode = $e->getHTTPCode();
$e->serialize($this,$error);
$headers = $e->getHTTPHeaders($this);
} else {
$httpCode = 500;
$headers = array();
}
$headers['Content-Type'] = 'application/xml; charset=utf-8';
$this->httpResponse->sendStatus($httpCode);
$this->httpResponse->setHeaders($headers);
$this->httpResponse->sendBody($DOM->saveXML());
}
}
/**
* Sets the base server uri
*
* @param string $uri
* @return void
*/
public function setBaseUri($uri) {
// If the baseUri does not end with a slash, we must add it
if ($uri[strlen($uri)-1]!=='/')
$uri.='/';
$this->baseUri = $uri;
}
/**
* Returns the base responding uri
*
* @return string
*/
public function getBaseUri() {
if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri();
return $this->baseUri;
}
/**
* This method attempts to detect the base uri.
* Only the PATH_INFO variable is considered.
*
* If this variable is not set, the root (/) is assumed.
*
* @return string
*/
public function guessBaseUri() {
$pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO');
$uri = $this->httpRequest->getRawServerValue('REQUEST_URI');
// If PATH_INFO is found, we can assume it's accurate.
if (!empty($pathInfo)) {
// We need to make sure we ignore the QUERY_STRING part
if ($pos = strpos($uri,'?'))
$uri = substr($uri,0,$pos);
// PATH_INFO is only set for urls, such as: /example.php/path
// in that case PATH_INFO contains '/path'.
// Note that REQUEST_URI is percent encoded, while PATH_INFO is
// not, Therefore they are only comparable if we first decode
// REQUEST_INFO as well.
$decodedUri = Sabre_DAV_URLUtil::decodePath($uri);
// A simple sanity check:
if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) {
$baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo));
return rtrim($baseUri,'/') . '/';
}
throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.');
}
// The last fallback is that we're just going to assume the server root.
return '/';
}
/**
* Adds a plugin to the server
*
* For more information, console the documentation of Sabre_DAV_ServerPlugin
*
* @param Sabre_DAV_ServerPlugin $plugin
* @return void
*/
public function addPlugin(Sabre_DAV_ServerPlugin $plugin) {
$this->plugins[$plugin->getPluginName()] = $plugin;
$plugin->initialize($this);
}
/**
* Returns an initialized plugin by it's name.
*
* This function returns null if the plugin was not found.
*
* @param string $name
* @return Sabre_DAV_ServerPlugin
*/
public function getPlugin($name) {
if (isset($this->plugins[$name]))
return $this->plugins[$name];
// This is a fallback and deprecated.
foreach($this->plugins as $plugin) {
if (get_class($plugin)===$name) return $plugin;
}
return null;
}
/**
* Returns all plugins
*
* @return array
*/
public function getPlugins() {
return $this->plugins;
}
/**
* Subscribe to an event.
*
* When the event is triggered, we'll call all the specified callbacks.
* It is possible to control the order of the callbacks through the
* priority argument.
*
* This is for example used to make sure that the authentication plugin
* is triggered before anything else. If it's not needed to change this
* number, it is recommended to ommit.
*
* @param string $event
* @param callback $callback
* @param int $priority
* @return void
*/
public function subscribeEvent($event, $callback, $priority = 100) {
if (!isset($this->eventSubscriptions[$event])) {
$this->eventSubscriptions[$event] = array();
}
while(isset($this->eventSubscriptions[$event][$priority])) $priority++;
$this->eventSubscriptions[$event][$priority] = $callback;
ksort($this->eventSubscriptions[$event]);
}
/**
* Broadcasts an event
*
* This method will call all subscribers. If one of the subscribers returns false, the process stops.
*
* The arguments parameter will be sent to all subscribers
*
* @param string $eventName
* @param array $arguments
* @return bool
*/
public function broadcastEvent($eventName,$arguments = array()) {
if (isset($this->eventSubscriptions[$eventName])) {
foreach($this->eventSubscriptions[$eventName] as $subscriber) {
$result = call_user_func_array($subscriber,$arguments);
if ($result===false) return false;
}
}
return true;
}
/**
* Handles a http request, and execute a method based on its name
*
* @param string $method
* @param string $uri
* @return void
*/
public function invokeMethod($method, $uri) {
$method = strtoupper($method);
if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return;
// Make sure this is a HTTP method we support
$internalMethods = array(
'OPTIONS',
'GET',
'HEAD',
'DELETE',
'PROPFIND',
'MKCOL',
'PUT',
'PROPPATCH',
'COPY',
'MOVE',
'REPORT'
);
if (in_array($method,$internalMethods)) {
call_user_func(array($this,'http' . $method), $uri);
} else {
if ($this->broadcastEvent('unknownMethod',array($method, $uri))) {
// Unsupported method
throw new Sabre_DAV_Exception_NotImplemented('There was no handler found for this "' . $method . '" method');
}
}
}
// {{{ HTTP Method implementations
/**
* HTTP OPTIONS
*
* @param string $uri
* @return void
*/
protected function httpOptions($uri) {
$methods = $this->getAllowedMethods($uri);
$this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods)));
$features = array('1','3', 'extended-mkcol');
foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
$this->httpResponse->setHeader('DAV',implode(', ',$features));
$this->httpResponse->setHeader('MS-Author-Via','DAV');
$this->httpResponse->setHeader('Accept-Ranges','bytes');
$this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION);
$this->httpResponse->setHeader('Content-Length',0);
$this->httpResponse->sendStatus(200);
}
/**
* HTTP GET
*
* This method simply fetches the contents of a uri, like normal
*
* @param string $uri
* @return bool
*/
protected function httpGet($uri) {
$node = $this->tree->getNodeForPath($uri,0);
if (!$this->checkPreconditions(true)) return false;
if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects');
$body = $node->get();
// Converting string into stream, if needed.
if (is_string($body)) {
$stream = fopen('php://temp','r+');
fwrite($stream,$body);
rewind($stream);
$body = $stream;
}
/*
* TODO: getetag, getlastmodified, getsize should also be used using
* this method
*/
$httpHeaders = $this->getHTTPHeaders($uri);
/* ContentType needs to get a default, because many webservers will otherwise
* default to text/html, and we don't want this for security reasons.
*/
if (!isset($httpHeaders['Content-Type'])) {
$httpHeaders['Content-Type'] = 'application/octet-stream';
}
if (isset($httpHeaders['Content-Length'])) {
$nodeSize = $httpHeaders['Content-Length'];
// Need to unset Content-Length, because we'll handle that during figuring out the range
unset($httpHeaders['Content-Length']);
} else {
$nodeSize = null;
}
$this->httpResponse->setHeaders($httpHeaders);
$range = $this->getHTTPRange();
$ifRange = $this->httpRequest->getHeader('If-Range');
$ignoreRangeHeader = false;
// If ifRange is set, and range is specified, we first need to check
// the precondition.
if ($nodeSize && $range && $ifRange) {
// if IfRange is parsable as a date we'll treat it as a DateTime
// otherwise, we must treat it as an etag.
try {
$ifRangeDate = new DateTime($ifRange);
// It's a date. We must check if the entity is modified since
// the specified date.
if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true;
else {
$modified = new DateTime($httpHeaders['Last-Modified']);
if($modified > $ifRangeDate) $ignoreRangeHeader = true;
}
} catch (Exception $e) {
// It's an entity. We can do a simple comparison.
if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true;
elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true;
}
}
// We're only going to support HTTP ranges if the backend provided a filesize
if (!$ignoreRangeHeader && $nodeSize && $range) {
// Determining the exact byte offsets
if (!is_null($range[0])) {
$start = $range[0];
$end = $range[1]?$range[1]:$nodeSize-1;
if($start >= $nodeSize)
throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')');
if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')');
if($end >= $nodeSize) $end = $nodeSize-1;
} else {
$start = $nodeSize-$range[1];
$end = $nodeSize-1;
if ($start<0) $start = 0;
}
// New read/write stream
$newStream = fopen('php://temp','r+');
stream_copy_to_stream($body, $newStream, $end-$start+1, $start);
rewind($newStream);
$this->httpResponse->setHeader('Content-Length', $end-$start+1);
$this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize);
$this->httpResponse->sendStatus(206);
$this->httpResponse->sendBody($newStream);
} else {
if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize);
$this->httpResponse->sendStatus(200);
$this->httpResponse->sendBody($body);
}
}
/**
* HTTP HEAD
*
* This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body
* This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again
*
* @param string $uri
* @return void
*/
protected function httpHead($uri) {
$node = $this->tree->getNodeForPath($uri);
/* This information is only collection for File objects.
* Ideally we want to throw 405 Method Not Allowed for every
* non-file, but MS Office does not like this
*/
if ($node instanceof Sabre_DAV_IFile) {
$headers = $this->getHTTPHeaders($this->getRequestUri());
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/octet-stream';
}
$this->httpResponse->setHeaders($headers);
}
$this->httpResponse->sendStatus(200);
}
/**
* HTTP Delete
*
* The HTTP delete method, deletes a given uri
*
* @param string $uri
* @return void
*/
protected function httpDelete($uri) {
if (!$this->broadcastEvent('beforeUnbind',array($uri))) return;
$this->tree->delete($uri);
$this->broadcastEvent('afterUnbind',array($uri));
$this->httpResponse->sendStatus(204);
$this->httpResponse->setHeader('Content-Length','0');
}
/**
* WebDAV PROPFIND
*
* This WebDAV method requests information about an uri resource, or a list of resources
* If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value
* If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory)
*
* The request body contains an XML data structure that has a list of properties the client understands
* The response body is also an xml document, containing information about every uri resource and the requested properties
*
* It has to return a HTTP 207 Multi-status status code
*
* @param string $uri
* @return void
*/
protected function httpPropfind($uri) {
// $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input'));
$requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true));
$depth = $this->getHTTPDepth(1);
// The only two options for the depth of a propfind is 0 or 1
if ($depth!=0) $depth = 1;
$newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth);
// This is a multi-status response
$this->httpResponse->sendStatus(207);
$this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
// Normally this header is only needed for OPTIONS responses, however..
// iCal seems to also depend on these being set for PROPFIND. Since
// this is not harmful, we'll add it.
$features = array('1','3', 'extended-mkcol');
foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
$this->httpResponse->setHeader('DAV',implode(', ',$features));
$data = $this->generateMultiStatus($newProperties);
$this->httpResponse->sendBody($data);
}
/**
* WebDAV PROPPATCH
*
* This method is called to update properties on a Node. The request is an XML body with all the mutations.
* In this XML body it is specified which properties should be set/updated and/or deleted
*
* @param string $uri
* @return void
*/
protected function httpPropPatch($uri) {
$newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true));
$result = $this->updateProperties($uri, $newProperties);
$this->httpResponse->sendStatus(207);
$this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
$this->httpResponse->sendBody(
$this->generateMultiStatus(array($result))
);
}
/**
* HTTP PUT method
*
* This HTTP method updates a file, or creates a new one.
*
* If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content
*
* @param string $uri
* @return bool
*/
protected function httpPut($uri) {
$body = $this->httpRequest->getBody();
// Intercepting Content-Range
if ($this->httpRequest->getHeader('Content-Range')) {
/**
Content-Range is dangerous for PUT requests: PUT per definition
stores a full resource. draft-ietf-httpbis-p2-semantics-15 says
in section 7.6:
An origin server SHOULD reject any PUT request that contains a
Content-Range header field, since it might be misinterpreted as
partial content (or might be partial content that is being mistakenly
PUT as a full representation). Partial content updates are possible
by targeting a separately identified resource with state that
overlaps a portion of the larger resource, or by using a different
method that has been specifically defined for partial updates (for
example, the PATCH method defined in [RFC5789]).
This clarifies RFC2616 section 9.6:
The recipient of the entity MUST NOT ignore any Content-*
(e.g. Content-Range) headers that it does not understand or implement
and MUST return a 501 (Not Implemented) response in such cases.
OTOH is a PUT request with a Content-Range currently the only way to
continue an aborted upload request and is supported by curl, mod_dav,
Tomcat and others. Since some clients do use this feature which results
in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject
all PUT requests with a Content-Range for now.
*/
throw new Sabre_DAV_Exception_NotImplemented('PUT with Content-Range is not allowed.');
}
// Intercepting the Finder problem
if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) {
/**
Many webservers will not cooperate well with Finder PUT requests,
because it uses 'Chunked' transfer encoding for the request body.
The symptom of this problem is that Finder sends files to the
server, but they arrive as 0-length files in PHP.
If we don't do anything, the user might think they are uploading
files successfully, but they end up empty on the server. Instead,
we throw back an error if we detect this.
The reason Finder uses Chunked, is because it thinks the files
might change as it's being uploaded, and therefore the
Content-Length can vary.
Instead it sends the X-Expected-Entity-Length header with the size
of the file at the very start of the request. If this header is set,
but we don't get a request body we will fail the request to
protect the end-user.
*/
// Only reading first byte
$firstByte = fread($body,1);
if (strlen($firstByte)!==1) {
throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.');
}
// The body needs to stay intact, so we copy everything to a
// temporary stream.
$newBody = fopen('php://temp','r+');
fwrite($newBody,$firstByte);
stream_copy_to_stream($body, $newBody);
rewind($newBody);
$body = $newBody;
}
if ($this->tree->nodeExists($uri)) {
$node = $this->tree->getNodeForPath($uri);
// Checking If-None-Match and related headers.
if (!$this->checkPreconditions()) return;
// If the node is a collection, we'll deny it
if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.');
if (!$this->broadcastEvent('beforeWriteContent',array($uri, $node, &$body))) return false;
$etag = $node->put($body);
$this->broadcastEvent('afterWriteContent',array($uri, $node));
$this->httpResponse->setHeader('Content-Length','0');
if ($etag) $this->httpResponse->setHeader('ETag',$etag);
$this->httpResponse->sendStatus(204);
} else {
$etag = null;
// If we got here, the resource didn't exist yet.
if (!$this->createFile($this->getRequestUri(),$body,$etag)) {
// For one reason or another the file was not created.
return;
}
$this->httpResponse->setHeader('Content-Length','0');
if ($etag) $this->httpResponse->setHeader('ETag', $etag);
$this->httpResponse->sendStatus(201);
}
}
/**
* WebDAV MKCOL
*
* The MKCOL method is used to create a new collection (directory) on the server
*
* @param string $uri
* @return void
*/
protected function httpMkcol($uri) {
$requestBody = $this->httpRequest->getBody(true);
if ($requestBody) {
$contentType = $this->httpRequest->getHeader('Content-Type');
if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) {
// We must throw 415 for unsupported mkcol bodies
throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type');
}
$dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody);
if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') {
// We must throw 415 for unsupported mkcol bodies
throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.');
}
$properties = array();
foreach($dom->firstChild->childNodes as $childNode) {
if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue;
$properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap));
}
if (!isset($properties['{DAV:}resourcetype']))
throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property');
$resourceType = $properties['{DAV:}resourcetype']->getValue();
unset($properties['{DAV:}resourcetype']);
} else {
$properties = array();
$resourceType = array('{DAV:}collection');
}
$result = $this->createCollection($uri, $resourceType, $properties);
if (is_array($result)) {
$this->httpResponse->sendStatus(207);
$this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
$this->httpResponse->sendBody(
$this->generateMultiStatus(array($result))
);
} else {
$this->httpResponse->setHeader('Content-Length','0');
$this->httpResponse->sendStatus(201);
}
}
/**
* WebDAV HTTP MOVE method
*
* This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo
*
* @param string $uri
* @return void
*/
protected function httpMove($uri) {
$moveInfo = $this->getCopyAndMoveInfo();
// If the destination is part of the source tree, we must fail
if ($moveInfo['destination']==$uri)
throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.');
if ($moveInfo['destinationExists']) {
if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false;
$this->tree->delete($moveInfo['destination']);
$this->broadcastEvent('afterUnbind',array($moveInfo['destination']));
}
if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false;
if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false;
$this->tree->move($uri,$moveInfo['destination']);
$this->broadcastEvent('afterUnbind',array($uri));
$this->broadcastEvent('afterBind',array($moveInfo['destination']));
// If a resource was overwritten we should send a 204, otherwise a 201
$this->httpResponse->setHeader('Content-Length','0');
$this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201);
}
/**
* WebDAV HTTP COPY method
*
* This method copies one uri to a different uri, and works much like the MOVE request
* A lot of the actual request processing is done in getCopyMoveInfo
*
* @param string $uri
* @return bool
*/
protected function httpCopy($uri) {
$copyInfo = $this->getCopyAndMoveInfo();
// If the destination is part of the source tree, we must fail
if ($copyInfo['destination']==$uri)
throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.');
if ($copyInfo['destinationExists']) {
if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false;
$this->tree->delete($copyInfo['destination']);
}
if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false;
$this->tree->copy($uri,$copyInfo['destination']);
$this->broadcastEvent('afterBind',array($copyInfo['destination']));
// If a resource was overwritten we should send a 204, otherwise a 201
$this->httpResponse->setHeader('Content-Length','0');
$this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201);
}
/**
* HTTP REPORT method implementation
*
* Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253)
* It's used in a lot of extensions, so it made sense to implement it into the core.
*
* @param string $uri
* @return void
*/
protected function httpReport($uri) {
$body = $this->httpRequest->getBody(true);
$dom = Sabre_DAV_XMLUtil::loadDOMDocument($body);
$reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild);
if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) {
// If broadcastEvent returned true, it means the report was not supported
throw new Sabre_DAV_Exception_ReportNotImplemented();
}
}
// }}}
// {{{ HTTP/WebDAV protocol helpers
/**
* Returns an array with all the supported HTTP methods for a specific uri.
*
* @param string $uri
* @return array
*/
public function getAllowedMethods($uri) {
$methods = array(
'OPTIONS',
'GET',
'HEAD',
'DELETE',
'PROPFIND',
'PUT',
'PROPPATCH',
'COPY',
'MOVE',
'REPORT'
);
// The MKCOL is only allowed on an unmapped uri
try {
$this->tree->getNodeForPath($uri);
} catch (Sabre_DAV_Exception_NotFound $e) {
$methods[] = 'MKCOL';
}
// We're also checking if any of the plugins register any new methods
foreach($this->plugins as $plugin) $methods = array_merge($methods, $plugin->getHTTPMethods($uri));
array_unique($methods);
return $methods;
}
/**
* Gets the uri for the request, keeping the base uri into consideration
*
* @return string
*/
public function getRequestUri() {
return $this->calculateUri($this->httpRequest->getUri());
}
/**
* Calculates the uri for a request, making sure that the base uri is stripped out
*
* @param string $uri
* @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri
* @return string
*/
public function calculateUri($uri) {
if ($uri[0]!='/' && strpos($uri,'://')) {
$uri = parse_url($uri,PHP_URL_PATH);
}
$uri = str_replace('//','/',$uri);
if (strpos($uri,$this->getBaseUri())===0) {
return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/');
// A special case, if the baseUri was accessed without a trailing
// slash, we'll accept it as well.
} elseif ($uri.'/' === $this->getBaseUri()) {
return '';
} else {
throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')');
}
}
/**
* Returns the HTTP depth header
*
* This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object
* It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existent
*
* @param mixed $default
* @return int
*/
public function getHTTPDepth($default = self::DEPTH_INFINITY) {
// If its not set, we'll grab the default
$depth = $this->httpRequest->getHeader('Depth');
if (is_null($depth)) return $default;
if ($depth == 'infinity') return self::DEPTH_INFINITY;
// If its an unknown value. we'll grab the default
if (!ctype_digit($depth)) return $default;
return (int)$depth;
}
/**
* Returns the HTTP range header
*
* This method returns null if there is no well-formed HTTP range request
* header or array($start, $end).
*
* The first number is the offset of the first byte in the range.
* The second number is the offset of the last byte in the range.
*
* If the second offset is null, it should be treated as the offset of the last byte of the entity
* If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity
*
* @return array|null
*/
public function getHTTPRange() {
$range = $this->httpRequest->getHeader('range');
if (is_null($range)) return null;
// Matching "Range: bytes=1234-5678: both numbers are optional
if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null;
if ($matches[1]==='' && $matches[2]==='') return null;
return array(
$matches[1]!==''?$matches[1]:null,
$matches[2]!==''?$matches[2]:null,
);
}
/**
* Returns information about Copy and Move requests
*
* This function is created to help getting information about the source and the destination for the
* WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions
*
* The returned value is an array with the following keys:
* * destination - Destination path
* * destinationExists - Whether or not the destination is an existing url (and should therefore be overwritten)
*
* @return array
*/
public function getCopyAndMoveInfo() {
// Collecting the relevant HTTP headers
if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied');
$destination = $this->calculateUri($this->httpRequest->getHeader('Destination'));
$overwrite = $this->httpRequest->getHeader('Overwrite');
if (!$overwrite) $overwrite = 'T';
if (strtoupper($overwrite)=='T') $overwrite = true;
elseif (strtoupper($overwrite)=='F') $overwrite = false;
// We need to throw a bad request exception, if the header was invalid
else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F');
list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination);
try {
$destinationParent = $this->tree->getNodeForPath($destinationDir);
if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection');
} catch (Sabre_DAV_Exception_NotFound $e) {
// If the destination parent node is not found, we throw a 409
throw new Sabre_DAV_Exception_Conflict('The destination node is not found');
}
try {
$destinationNode = $this->tree->getNodeForPath($destination);
// If this succeeded, it means the destination already exists
// we'll need to throw precondition failed in case overwrite is false
if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite');
} catch (Sabre_DAV_Exception_NotFound $e) {
// Destination didn't exist, we're all good
$destinationNode = false;
}
// These are the three relevant properties we need to return
return array(
'destination' => $destination,
'destinationExists' => $destinationNode==true,
'destinationNode' => $destinationNode,
);
}
/**
* Returns a list of properties for a path
*
* This is a simplified version getPropertiesForPath.
* if you aren't interested in status codes, but you just
* want to have a flat list of properties. Use this method.
*
* @param string $path
* @param array $propertyNames
*/
public function getProperties($path, $propertyNames) {
$result = $this->getPropertiesForPath($path,$propertyNames,0);
return $result[0][200];
}
/**
* A kid-friendly way to fetch properties for a node's children.
*
* The returned array will be indexed by the path of the of child node.
* Only properties that are actually found will be returned.
*
* The parent node will not be returned.
*
* @param string $path
* @param array $propertyNames
* @return array
*/
public function getPropertiesForChildren($path, $propertyNames) {
$result = array();
foreach($this->getPropertiesForPath($path,$propertyNames,1) as $k=>$row) {
// Skipping the parent path
if ($k === 0) continue;
$result[$row['href']] = $row[200];
}
return $result;
}
/**
* Returns a list of HTTP headers for a particular resource
*
* The generated http headers are based on properties provided by the
* resource. The method basically provides a simple mapping between
* DAV property and HTTP header.
*
* The headers are intended to be used for HEAD and GET requests.
*
* @param string $path
* @return array
*/
public function getHTTPHeaders($path) {
$propertyMap = array(
'{DAV:}getcontenttype' => 'Content-Type',
'{DAV:}getcontentlength' => 'Content-Length',
'{DAV:}getlastmodified' => 'Last-Modified',
'{DAV:}getetag' => 'ETag',
);
$properties = $this->getProperties($path,array_keys($propertyMap));
$headers = array();
foreach($propertyMap as $property=>$header) {
if (!isset($properties[$property])) continue;
if (is_scalar($properties[$property])) {
$headers[$header] = $properties[$property];
// GetLastModified gets special cased
} elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) {
$headers[$header] = Sabre_HTTP_Util::toHTTPDate($properties[$property]->getTime());
}
}
return $headers;
}
/**
* Returns a list of properties for a given path
*
* The path that should be supplied should have the baseUrl stripped out
* The list of properties should be supplied in Clark notation. If the list is empty
* 'allprops' is assumed.
*
* If a depth of 1 is requested child elements will also be returned.
*
* @param string $path
* @param array $propertyNames
* @param int $depth
* @return array
*/
public function getPropertiesForPath($path, $propertyNames = array(), $depth = 0) {
if ($depth!=0) $depth = 1;
$returnPropertyList = array();
$parentNode = $this->tree->getNodeForPath($path);
$nodes = array(
$path => $parentNode
);
if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) {
foreach($this->tree->getChildren($path) as $childNode)
$nodes[$path . '/' . $childNode->getName()] = $childNode;
}
// If the propertyNames array is empty, it means all properties are requested.
// We shouldn't actually return everything we know though, and only return a
// sensible list.
$allProperties = count($propertyNames)==0;
foreach($nodes as $myPath=>$node) {
$currentPropertyNames = $propertyNames;
$newProperties = array(
'200' => array(),
'404' => array(),
);
if ($allProperties) {
// Default list of propertyNames, when all properties were requested.
$currentPropertyNames = array(
'{DAV:}getlastmodified',
'{DAV:}getcontentlength',
'{DAV:}resourcetype',
'{DAV:}quota-used-bytes',
'{DAV:}quota-available-bytes',
'{DAV:}getetag',
'{DAV:}getcontenttype',
);
}
// If the resourceType was not part of the list, we manually add it
// and mark it for removal. We need to know the resourcetype in order
// to make certain decisions about the entry.
// WebDAV dictates we should add a / and the end of href's for collections
$removeRT = false;
if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) {
$currentPropertyNames[] = '{DAV:}resourcetype';
$removeRT = true;
}
$result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties));
// If this method explicitly returned false, we must ignore this
// node as it is inaccessible.
if ($result===false) continue;
if (count($currentPropertyNames) > 0) {
if ($node instanceof Sabre_DAV_IProperties)
$newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames);
}
foreach($currentPropertyNames as $prop) {
if (isset($newProperties[200][$prop])) continue;
switch($prop) {
case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break;
case '{DAV:}getcontentlength' :
if ($node instanceof Sabre_DAV_IFile) {
$size = $node->getSize();
if (!is_null($size)) {
$newProperties[200][$prop] = (int)$node->getSize();
}
}
break;
case '{DAV:}quota-used-bytes' :
if ($node instanceof Sabre_DAV_IQuota) {
$quotaInfo = $node->getQuotaInfo();
$newProperties[200][$prop] = $quotaInfo[0];
}
break;
case '{DAV:}quota-available-bytes' :
if ($node instanceof Sabre_DAV_IQuota) {
$quotaInfo = $node->getQuotaInfo();
$newProperties[200][$prop] = $quotaInfo[1];
}
break;
case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break;
case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break;
case '{DAV:}supported-report-set' :
$reports = array();
foreach($this->plugins as $plugin) {
$reports = array_merge($reports, $plugin->getSupportedReportSet($myPath));
}
$newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports);
break;
case '{DAV:}resourcetype' :
$newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType();
foreach($this->resourceTypeMapping as $className => $resourceType) {
if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType);
}
break;
}
// If we were unable to find the property, we will list it as 404.
if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null;
}
$this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties));
$newProperties['href'] = trim($myPath,'/');
// Its is a WebDAV recommendation to add a trailing slash to collectionnames.
// Apple's iCal also requires a trailing slash for principals (rfc 3744).
// Therefore we add a trailing / for any non-file. This might need adjustments
// if we find there are other edge cases.
if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/';
// If the resourcetype property was manually added to the requested property list,
// we will remove it again.
if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']);
$returnPropertyList[] = $newProperties;
}
return $returnPropertyList;
}
/**
* This method is invoked by sub-systems creating a new file.
*
* Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin).
* It was important to get this done through a centralized function,
* allowing plugins to intercept this using the beforeCreateFile event.
*
* This method will return true if the file was actually created
*
* @param string $uri
* @param resource $data
* @param string $etag
* @return bool
*/
public function createFile($uri,$data, &$etag = null) {
list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri);
if (!$this->broadcastEvent('beforeBind',array($uri))) return false;
$parent = $this->tree->getNodeForPath($dir);
if (!$this->broadcastEvent('beforeCreateFile',array($uri, &$data, $parent))) return false;
$etag = $parent->createFile($name,$data);
$this->tree->markDirty($dir);
$this->broadcastEvent('afterBind',array($uri));
$this->broadcastEvent('afterCreateFile',array($uri, $parent));
return true;
}
/**
* This method is invoked by sub-systems creating a new directory.
*
* @param string $uri
* @return void
*/
public function createDirectory($uri) {
$this->createCollection($uri,array('{DAV:}collection'),array());
}
/**
* Use this method to create a new collection
*
* The {DAV:}resourcetype is specified using the resourceType array.
* At the very least it must contain {DAV:}collection.
*
* The properties array can contain a list of additional properties.
*
* @param string $uri The new uri
* @param array $resourceType The resourceType(s)
* @param array $properties A list of properties
* @return array|null
*/
public function createCollection($uri, array $resourceType, array $properties) {
list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri);
// Making sure {DAV:}collection was specified as resourceType
if (!in_array('{DAV:}collection', $resourceType)) {
throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection');
}
// Making sure the parent exists
try {
$parent = $this->tree->getNodeForPath($parentUri);
} catch (Sabre_DAV_Exception_NotFound $e) {
throw new Sabre_DAV_Exception_Conflict('Parent node does not exist');
}
// Making sure the parent is a collection
if (!$parent instanceof Sabre_DAV_ICollection) {
throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection');
}
// Making sure the child does not already exist
try {
$parent->getChild($newName);
// If we got here.. it means there's already a node on that url, and we need to throw a 405
throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists');
} catch (Sabre_DAV_Exception_NotFound $e) {
// This is correct
}
if (!$this->broadcastEvent('beforeBind',array($uri))) return;
// There are 2 modes of operation. The standard collection
// creates the directory, and then updates properties
// the extended collection can create it directly.
if ($parent instanceof Sabre_DAV_IExtendedCollection) {
$parent->createExtendedCollection($newName, $resourceType, $properties);
} else {
// No special resourcetypes are supported
if (count($resourceType)>1) {
throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.');
}
$parent->createDirectory($newName);
$rollBack = false;
$exception = null;
$errorResult = null;
if (count($properties)>0) {
try {
$errorResult = $this->updateProperties($uri, $properties);
if (!isset($errorResult[200])) {
$rollBack = true;
}
} catch (Sabre_DAV_Exception $e) {
$rollBack = true;
$exception = $e;
}
}
if ($rollBack) {
if (!$this->broadcastEvent('beforeUnbind',array($uri))) return;
$this->tree->delete($uri);
// Re-throwing exception
if ($exception) throw $exception;
return $errorResult;
}
}
$this->tree->markDirty($parentUri);
$this->broadcastEvent('afterBind',array($uri));
}
/**
* This method updates a resource's properties
*
* The properties array must be a list of properties. Array-keys are
* property names in clarknotation, array-values are it's values.
* If a property must be deleted, the value should be null.
*
* Note that this request should either completely succeed, or
* completely fail.
*
* The response is an array with statuscodes for keys, which in turn
* contain arrays with propertynames. This response can be used
* to generate a multistatus body.
*
* @param string $uri
* @param array $properties
* @return array
*/
public function updateProperties($uri, array $properties) {
// we'll start by grabbing the node, this will throw the appropriate
// exceptions if it doesn't.
$node = $this->tree->getNodeForPath($uri);
$result = array(
200 => array(),
403 => array(),
424 => array(),
);
$remainingProperties = $properties;
$hasError = false;
// Running through all properties to make sure none of them are protected
if (!$hasError) foreach($properties as $propertyName => $value) {
if(in_array($propertyName, $this->protectedProperties)) {
$result[403][$propertyName] = null;
unset($remainingProperties[$propertyName]);
$hasError = true;
}
}
if (!$hasError) {
// Allowing plugins to take care of property updating
$hasError = !$this->broadcastEvent('updateProperties',array(
&$remainingProperties,
&$result,
$node
));
}
// If the node is not an instance of Sabre_DAV_IProperties, every
// property is 403 Forbidden
if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) {
$hasError = true;
foreach($properties as $propertyName=> $value) {
$result[403][$propertyName] = null;
}
$remainingProperties = array();
}
// Only if there were no errors we may attempt to update the resource
if (!$hasError) {
if (count($remainingProperties)>0) {
$updateResult = $node->updateProperties($remainingProperties);
if ($updateResult===true) {
// success
foreach($remainingProperties as $propertyName=>$value) {
$result[200][$propertyName] = null;
}
} elseif ($updateResult===false) {
// The node failed to update the properties for an
// unknown reason
foreach($remainingProperties as $propertyName=>$value) {
$result[403][$propertyName] = null;
}
} elseif (is_array($updateResult)) {
// The node has detailed update information
// We need to merge the results with the earlier results.
foreach($updateResult as $status => $props) {
if (is_array($props)) {
if (!isset($result[$status]))
$result[$status] = array();
$result[$status] = array_merge($result[$status], $updateResult[$status]);
}
}
} else {
throw new Sabre_DAV_Exception('Invalid result from updateProperties');
}
$remainingProperties = array();
}
}
foreach($remainingProperties as $propertyName=>$value) {
// if there are remaining properties, it must mean
// there's a dependency failure
$result[424][$propertyName] = null;
}
// Removing empty array values
foreach($result as $status=>$props) {
if (count($props)===0) unset($result[$status]);
}
$result['href'] = $uri;
return $result;
}
/**
* This method checks the main HTTP preconditions.
*
* Currently these are:
* * If-Match
* * If-None-Match
* * If-Modified-Since
* * If-Unmodified-Since
*
* The method will return true if all preconditions are met
* The method will return false, or throw an exception if preconditions
* failed. If false is returned the operation should be aborted, and
* the appropriate HTTP response headers are already set.
*
* Normally this method will throw 412 Precondition Failed for failures
* related to If-None-Match, If-Match and If-Unmodified Since. It will
* set the status to 304 Not Modified for If-Modified_since.
*
* If the $handleAsGET argument is set to true, it will also return 304
* Not Modified for failure of the If-None-Match precondition. This is the
* desired behaviour for HTTP GET and HTTP HEAD requests.
*
* @param bool $handleAsGET
* @return bool
*/
public function checkPreconditions($handleAsGET = false) {
$uri = $this->getRequestUri();
$node = null;
$lastMod = null;
$etag = null;
if ($ifMatch = $this->httpRequest->getHeader('If-Match')) {
// If-Match contains an entity tag. Only if the entity-tag
// matches we are allowed to make the request succeed.
// If the entity-tag is '*' we are only allowed to make the
// request succeed if a resource exists at that url.
try {
$node = $this->tree->getNodeForPath($uri);
} catch (Sabre_DAV_Exception_NotFound $e) {
throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match');
}
// Only need to check entity tags if they are not *
if ($ifMatch!=='*') {
// There can be multiple etags
$ifMatch = explode(',',$ifMatch);
$haveMatch = false;
foreach($ifMatch as $ifMatchItem) {
// Stripping any extra spaces
$ifMatchItem = trim($ifMatchItem,' ');
$etag = $node->getETag();
if ($etag===$ifMatchItem) {
$haveMatch = true;
}
}
if (!$haveMatch) {
throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match');
}
}
}
if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) {
// The If-None-Match header contains an etag.
// Only if the ETag does not match the current ETag, the request will succeed
// The header can also contain *, in which case the request
// will only succeed if the entity does not exist at all.
$nodeExists = true;
if (!$node) {
try {
$node = $this->tree->getNodeForPath($uri);
} catch (Sabre_DAV_Exception_NotFound $e) {
$nodeExists = false;
}
}
if ($nodeExists) {
$haveMatch = false;
if ($ifNoneMatch==='*') $haveMatch = true;
else {
// There might be multiple etags
$ifNoneMatch = explode(',', $ifNoneMatch);
$etag = $node->getETag();
foreach($ifNoneMatch as $ifNoneMatchItem) {
// Stripping any extra spaces
$ifNoneMatchItem = trim($ifNoneMatchItem,' ');
if ($etag===$ifNoneMatchItem) $haveMatch = true;
}
}
if ($haveMatch) {
if ($handleAsGET) {
$this->httpResponse->sendStatus(304);
return false;
} else {
throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match');
}
}
}
}
if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) {
// The If-Modified-Since header contains a date. We
// will only return the entity if it has been changed since
// that date. If it hasn't been changed, we return a 304
// header
// Note that this header only has to be checked if there was no If-None-Match header
// as per the HTTP spec.
$date = Sabre_HTTP_Util::parseHTTPDate($ifModifiedSince);
if ($date) {
if (is_null($node)) {
$node = $this->tree->getNodeForPath($uri);
}
$lastMod = $node->getLastModified();
if ($lastMod) {
$lastMod = new DateTime('@' . $lastMod);
if ($lastMod <= $date) {
$this->httpResponse->sendStatus(304);
$this->httpResponse->setHeader('Last-Modified', Sabre_HTTP_Util::toHTTPDate($lastMod));
return false;
}
}
}
}
if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) {
// The If-Unmodified-Since will allow allow the request if the
// entity has not changed since the specified date.
$date = Sabre_HTTP_Util::parseHTTPDate($ifUnmodifiedSince);
// We must only check the date if it's valid
if ($date) {
if (is_null($node)) {
$node = $this->tree->getNodeForPath($uri);
}
$lastMod = $node->getLastModified();
if ($lastMod) {
$lastMod = new DateTime('@' . $lastMod);
if ($lastMod > $date) {
throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since');
}
}
}
}
return true;
}
// }}}
// {{{ XML Readers & Writers
/**
* Generates a WebDAV propfind response body based on a list of nodes
*
* @param array $fileProperties The list with nodes
* @return string
*/
public function generateMultiStatus(array $fileProperties) {
$dom = new DOMDocument('1.0','utf-8');
//$dom->formatOutput = true;
$multiStatus = $dom->createElement('d:multistatus');
$dom->appendChild($multiStatus);
// Adding in default namespaces
foreach($this->xmlNamespaces as $namespace=>$prefix) {
$multiStatus->setAttribute('xmlns:' . $prefix,$namespace);
}
foreach($fileProperties as $entry) {
$href = $entry['href'];
unset($entry['href']);
$response = new Sabre_DAV_Property_Response($href,$entry);
$response->serialize($this,$multiStatus);
}
return $dom->saveXML();
}
/**
* This method parses a PropPatch request
*
* PropPatch changes the properties for a resource. This method
* returns a list of properties.
*
* The keys in the returned array contain the property name (e.g.: {DAV:}displayname,
* and the value contains the property value. If a property is to be removed the value
* will be null.
*
* @param string $body xml body
* @return array list of properties in need of updating or deletion
*/
public function parsePropPatchRequest($body) {
//We'll need to change the DAV namespace declaration to something else in order to make it parsable
$dom = Sabre_DAV_XMLUtil::loadDOMDocument($body);
$newProperties = array();
foreach($dom->firstChild->childNodes as $child) {
if ($child->nodeType !== XML_ELEMENT_NODE) continue;
$operation = Sabre_DAV_XMLUtil::toClarkNotation($child);
if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue;
$innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap);
foreach($innerProperties as $propertyName=>$propertyValue) {
if ($operation==='{DAV:}remove') {
$propertyValue = null;
}
$newProperties[$propertyName] = $propertyValue;
}
}
return $newProperties;
}
/**
* This method parses the PROPFIND request and returns its information
*
* This will either be a list of properties, or an empty array; in which case
* an {DAV:}allprop was requested.
*
* @param string $body
* @return array
*/
public function parsePropFindRequest($body) {
// If the propfind body was empty, it means IE is requesting 'all' properties
if (!$body) return array();
$dom = Sabre_DAV_XMLUtil::loadDOMDocument($body);
$elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0);
return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem));
}
// }}}
}
| harrydeluxe/mongofilesystem | example/dav/protected/lib/Sabre/DAV/Server.php | PHP | mit | 68,178 |
<?php
use Stecman\Passnote\Object\ReadableEncryptedContent;
use Stecman\Passnote\Object\ReadableEncryptedContentTrait;
class ObjectController extends ControllerBase
{
public static function getObjectUrl(StoredObject $object)
{
return 'object/' . $object->getUuid();
}
public function indexAction($uuid)
{
$object = $this->getObjectById($uuid);
if ($object) {
$content = $this->decryptContent($object);
$this->view->setVar('object', $object);
$this->view->setVar('decrypted_content', $content);
} else {
$this->handleAs404('Object not found');
}
}
public function findAction()
{
$query = $this->request->getPost('query', 'trim');
echo $query;
}
public function versionsAction($uuid)
{
$object = $this->getObjectById($uuid);
if ($object) {
$versions = [];
$differ = new \SebastianBergmann\Diff\Differ('');
$prevContent = '';
foreach ($object->versions as $version) {
$nextContent = $this->decryptContent($version);
$diff = $differ->diff($prevContent, $nextContent);
$prevContent = $nextContent;
$version->_diff = $this->formatDiff($diff);
$versions[] = $version;
}
$object->_diff = $this->formatDiff($differ->diff(
$prevContent,
$this->decryptContent($object)
));
$versions[] = $object;
krsort($versions);
$this->view->setLayout('object');
$this->view->setVar('object', $object);
$this->view->setVar('versions', $versions);
} else {
$this->handleAs404('Object not found');
}
}
public function showVersionAction($objectUuid, $versionUuid)
{
$version = $this->getObjectVersion($objectUuid, $versionUuid);
if ($version) {
$content = $this->decryptContent($version);
$this->view->setVar('object', $version->master);
$this->view->setVar('version', $version);
$this->view->setVar('next_version', $version->getSibling(ObjectVersion::NEWER_VERSION));
$this->view->setVar('prev_version', $version->getSibling(ObjectVersion::OLDER_VERSION));
$this->view->setVar('decrypted_content', $content);
} else {
$this->handleAs404('Object or version not found');
}
}
public function editAction($uuid)
{
$object = $this->getObjectById($uuid);
$form = new ObjectForm(null, Security::getCurrentUser());
if ($object) {
$content = $this->decryptContent($object);
$form->setBody($content);
$form->setEntity($object);
$this->view->setVar('object', $object);
}
$this->view->setVar('form', $form);
if ($this->request->isPost() && $form->isValid($_POST)) {
if (!$this->security->checkToken()) {
$this->flash->error('Invalid security token. Please try submitting the form again.');
return;
}
$savedObject = $form->handleSubmit();
$this->response->redirect( self::getObjectUrl($savedObject) );
}
}
public function deleteAction($objectUuid, $versionUuid = null)
{
if ($versionUuid) {
$object = $this->getObjectVersion($objectUuid, $versionUuid);
} else {
$object = $this->getObjectById($objectUuid);
}
$this->view->setVar('object', $object);
$this->view->setVar('isVersion', $object instanceof ObjectVersion);
if (!$object) {
return $this->handleAs404('Object not found');
}
if ($this->request->isPost()) {
if (!$this->security->checkToken()) {
$this->flash->error('Invalid security token. Please try submitting the form again.');
return;
}
$object->delete();
$this->flashSession->success("Deleted object $objectUuid");
$this->response->redirect('');
}
}
protected function decryptContent(ReadableEncryptedContent $object)
{
$user = Security::getCurrentUser();
if ($object->getKeyId() === $user->accountKey_id) {
$keyService = new \Stecman\Passnote\AccountKeyService();
return $keyService->decryptObject($object);
} else {
// Prompt for decryption passphrase
}
}
/**
* @param string $uuid
* @return \StoredObject
*/
protected function getObjectById($uuid)
{
return StoredObject::findFirst([
'uuid = :uuid: AND user_id = :user_id:',
'bind' => [
'uuid' => $uuid,
'user_id' => Security::getCurrentUserId()
]
]);
}
protected function formatDiff($diff)
{
$diff = preg_replace('/(^-.*$)/m', '<span class="diff-del">$1</span>', $diff);
$diff = preg_replace('/(^\+.*$)/m', '<span class="diff-add">$1</span>', $diff);
return $diff;
}
/**
* Fetch an object version from the database
*
* @param string $objectUuid
* @param string $versionUuid
* @return ObjectVersion|null
*/
protected function getObjectVersion($objectUuid, $versionUuid) {
return $this->modelsManager->executeQuery(
'SELECT ObjectVersion.* FROM ObjectVersion'
.' LEFT JOIN StoredObject Object ON ObjectVersion.object_id = Object.id'
.' WHERE ObjectVersion.uuid = :version_uuid: AND Object.uuid = :object_uuid: AND Object.user_id = :user_id:',
[
'version_uuid' => $versionUuid,
'object_uuid' => $objectUuid,
'user_id' => Security::getCurrentUserId()
]
)->getFirst();
}
}
| stecman/passnote | app/controllers/ObjectController.php | PHP | mit | 6,009 |
import { globalShortcut } from 'electron'
import playbackControls from '../actions/playbackControls'
function initGlobalShortcuts () {
globalShortcut.register('MediaNextTrack', playbackControls.clickNextSong)
globalShortcut.register('MediaPreviousTrack', playbackControls.clickPreviousSong)
globalShortcut.register('MediaStop', playbackControls.clickPlayPause)
globalShortcut.register('MediaPlayPause', playbackControls.clickPlayPause)
}
export default initGlobalShortcuts
| ashokfernandez/kiste | src/shortcuts/initGlobalShortcuts.js | JavaScript | mit | 483 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.automation.fluent.models.ConnectionInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The response model for the list connection operation. */
@Fluent
public final class ConnectionListResult {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ConnectionListResult.class);
/*
* Gets or sets a list of connection.
*/
@JsonProperty(value = "value")
private List<ConnectionInner> value;
/*
* Gets or sets the next link.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: Gets or sets a list of connection.
*
* @return the value value.
*/
public List<ConnectionInner> value() {
return this.value;
}
/**
* Set the value property: Gets or sets a list of connection.
*
* @param value the value value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withValue(List<ConnectionInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: Gets or sets the next link.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: Gets or sets the next link.
*
* @param nextLink the nextLink value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| Azure/azure-sdk-for-java | sdk/automation/azure-resourcemanager-automation/src/main/java/com/azure/resourcemanager/automation/models/ConnectionListResult.java | Java | mit | 2,244 |
#
# The MIT License(MIT)
#
# Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# =
module Copyleaks
class AuthExipredException < StandardError
attr_reader :reason
def initialize
@reason = 'Authentication Expired. Need to login again'
end
end
end
| Copyleaks/Ruby-Plagiarism-Checker | lib/copyleaks/models/exceptions/auth_exipred_exception.rb | Ruby | mit | 1,349 |
<?php
/**
* Přidá parametr lang=LANG_CODE za každý odkaz na stránce
*
* @param String $link upravovaný odkaz
* @return String upravený $link
*/
function icom_edit_permalink($link) {
if (icom_is_permalink_struct()) {
return ICOM_ABSPATH . icom_current_lang() . "/" . str_replace(ICOM_ABSPATH, "", $link);
} else {
return ICOM_ABSPATH . str_replace(ICOM_ABSPATH, "", $link) . "&lang=" . icom_current_lang();
}
}
/**
* Zjistí aktuálně nastavený jazyk pro zobrazování stránek
* @return String lang_code
*/
function icom_current_lang() {
global $icom_lang_selected_front, $icom_lang_default_front;
$lang = get_query_var('lang');
if (empty($lang) && !empty($_GET['lang'])) {
$lang = $_GET['lang'];
}
if (empty($lang)) return $icom_lang_default_front;
$lang_exists = preg_grep("/" . $lang . "/i", $icom_lang_selected_front); // musí být regulárem namísto in_array(), kvůli case-insensitive
if (!empty($lang_exists)) {
return $lang;
} else {
return $icom_lang_default_front;
}
}
/**
* Pokud je jazyk ulozen v URL vrati TRUE, jinak FALSE
* #not used
* @return boolean
*/
function icom_lang_in_url() {
$l1 = get_query_var('lang');
$l2 = $_GET['lang'];
if ((isset($l1) && !empty($l1)) || (isset($l2) && !empty($l2))) {
return TRUE;
} else {
return FALSE;
}
}
/**
* Vybere z DB stranky ktere nejsou v aktualne zvolenem jazyce
* nebo maji priznak PREVIEW
*
* @global wpdb $wpdb
* @return int[] ID vyloucenych stranek
*/
function icom_get_exclude_pages() {
global $wpdb;
$current_lang = icom_current_lang();
$pages_for_exclude = $wpdb->get_results(" SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE lang != '" . $current_lang . "' OR preview = '1'");
foreach ($pages_for_exclude as $page) {
$exclude_pages[] = $page->id_post;
}
return $exclude_pages;
}
/**
* Vyloučí z výpisu stránky podle aktuálně zvoleného jazyka
*
* Slouzi nejspise k zobrazeni menu na frontendu
*/
function icom_exclude_pages($query) {
$exclude_pages = icom_get_exclude_pages();
$query->set('post__not_in', $exclude_pages);
return $query;
}
/**
* Zjisti jestli jsou nastavene cool URL (mod_rewrite)
*
* @return boolean
*/
function icom_is_permalink_struct() {
$structure = get_option('permalink_structure');
if (empty($structure)) {
return false;
} else {
return true;
}
}
/**
* Vrátí strukturu url dle toho jestli jsou nebo nejsou nastaveny permalinky
* @param $lang
* @param $page
* @return boolean
*/
function icom_get_permalink_struct($lang, $page) {
$permalink = icom_is_permalink_struct();
if ($permalink == false)
return array('permalink' => false, 'value' => '?&' . $page . '&lang=' . $lang);
else
return array('permalink' => true, 'value' => $lang . "/" . $page);
}
/**
* Question: Co dela tahle funkce a k cemu se pouziva??
*
* Zjisti jestli je dana stranka (z tabulky posts) typu 'page'
* @return boolean
*/
/*
function icom_get_type($type) {
switch ($type) {
case "post":
break;
default:
if (get_query_var('page_id') || get_query_var('pagename'))
return true;
else if (!get_query_var('p') && !get_query_var('name'))
return true;
else
return false;
break;
}
}
*/
/**
* Zjisti typ(post, page, ...) stranky [post_type] podle ID
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_type($id) {
global $wpdb;
return $wpdb->get_var("SELECT post_type FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
}
/**
* Zjistí post_status (publish, draft, ...) stránky
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_status($id){
global $wpdb;
return $wpdb->get_var("SELECT post_status FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
}
/**
* Zjisti jazyk stranky podle jejiho ID
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_lang($id) {
global $wpdb;
return $wpdb->get_var("SELECT lang FROM " . $wpdb->prefix . "icom_translations WHERE id_post = " . $id . "");
}
/**
* Sestavi permalink pro stranky typu post. Pokud je zjisteny jiny typ (napr. pages),
* tak fce vrati get_permalink()
*
* @global wpdb $wpdb
* @global string $icom_lang_default_front
* @param int $id
* @return string $permalink
*/
function icom_get_post_permalink($id) {
global $wpdb, $icom_lang_default_front;
$lang = icom_get_post_lang($id);
if (!isset($lang) || empty($lang)) {
$lang = $icom_lang_default_front;
}
/* TO-DO: zde je ješte potřeba dodělat aby to vracelo jazyk v případě, že nejsou povolené COOL URL
*/
if (icom_get_post_type($id) !== "post") {
$permalink = get_permalink($id);
if ((stripos($permalink, $lang)) !== FALSE) {
return $permalink;
} else if ((stripos($permalink, ICOM_HOST)) !== FALSE) {
return substr_replace($permalink, $lang . "/", strlen(ICOM_HOST), 0);
} else {
return NULL;
}
}
$slug = $wpdb->get_var("SELECT post_name FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
$permalink = rtrim(str_replace("/wp-admin/", "", ICOM_ABSPATH), "/");
$permalink = rtrim($permalink, "/") . "/" . $lang . "/" . $slug . "/";
return $permalink;
}
/**
* Ziska ID aktualni stranky stranky
* @return type
*/
function icom_get_post_id() {
global $wpdb, $icom_lang_default;
if (get_query_var('p')) {
return get_query_var('p');
} else if (get_query_var('page_id')) {
return get_query_var('page_id');
} else if (get_query_var('icompage') || get_query_var('pagename') || get_query_var('name')) {
$query_string = get_query_var('icompage');
if (empty($query_string)) $query_string = get_query_var('pagename');
if (empty($query_string)) $query_string = get_query_var('name');
$slug_parts = explode("/", $query_string);
$slug_count = count($slug_parts);
$post_name = $slug_parts[$slug_count - 1]; // ziska ID stranky ze slugu (post_name)
//zkusi ziskat ID stranky z tabulky [icom_transtations]
//podle aktualniho jazyka a podle [post_name] z tabulky [posts]
if (stripos($post_name, "preview-page") !== false)
$where = "t.preview = '1'";
else
$where = "t.lang = %s AND t.preview = '0'";
$qry = "SELECT id_post FROM " . $wpdb->prefix . "icom_translations t, " . $wpdb->prefix . "posts p WHERE p.id = t.id_post AND post_name = '" . $post_name . "' AND (" . $where . ") ORDER BY t.id DESC";
$id = $wpdb->get_var($wpdb->prepare($qry, icom_current_lang()));
//pokud neexistuje stranka v tab. [icom_transtations] tzn. neni dostupna v hledanem jazyce
//zkusi ziskat ID nejake stranky se stejnym slugem z tabulky [posts]
if (is_null($id)) {
$id = $wpdb->get_var($wpdb->prepare($qry, $icom_lang_default));
}
if (is_null($id))
return -1;
else
return $id;
} else {
return null;
}
}
/**
* Pokud ID stranky a jazyk nejsou shodne (podle tabulky icom_translations),
* tak se pokusi ziskat ID stranky v danem jazyce a presmerovat na ni.
* Kdyz neni zadne ID nalezene nepresmeruje.
*
* @global wpdb $wpdb
* @param WP_Query $query
* @return WP_Query
*/
function icom_load_page_by_lang($query) {
global $wpdb, $icom_lang_default;
if (!$query->is_main_query()) {
return $query;
}
$is_permalink = icom_is_permalink_struct(); // TRUE pokud se pouzivaji COOL URL
$current_lang = icom_current_lang(); // Jazyk aktualne uvedeny v URL
$last_lang = get_option("icom_language_last"); // Jazyk, ktery byl v URL naposledy (nevim kvuli cemu jsme ho museli zavest)
$is_homepage = false;
$is_page = false;
$is_preview = false;
$id = icom_get_post_id(); // ID aktualni stranky
$id_homepage = get_option('page_on_front'); // ID homepage
// pokud se jedná o preview stránku (která se používá při PR), jen přesměruje na správný jazyk
$preview = $wpdb->get_var("SELECT lang FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . $id . "' AND preview = '1'");
if ($preview && empty(get_query_var('lang'))) {
$query->set('lang', $preview);
wp_redirect(icom_get_post_permalink($id) . "?icom-previewHash=" . $_GET['icom-previewHash'] . "&icom-targetLang" . $_GET['icom-targetLang']);
exit();
}
$link_homepage = get_permalink($id);
// pokud se jedná o úvodní stránku defaultního jazyka a nemá v sobě jazyk
if ($is_permalink == true && $id == $id_homepage && ICOM_ABSPATH != $link_homepage) {
wp_redirect($link_homepage);
exit();
}
// 404ka
if ($id == -1) {
if ($id_homepage > 0) {
$query->is_404 = TRUE;
$query->is_post_page = FALSE;
} else {
$query->is_404 = FALSE;
$query->is_post_page = TRUE;
$id = null;
}
// $id je NULL pokud v URL není ID ani slug
} else if (!isset($id)) {
$is_homepage = true;
//zjistim ID postu na zaklade jazyka a ID homepage stranky
$id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE lang = '" . $current_lang . "' AND id_post_orig = '" . $id_homepage . "' AND preview = '0'");
//jelikož homepage je na specifický adrese /[LANG]/,
//tak WP řeknu: to není homepage, ale obyčejná page, tak přestan dělat problémy
if (isset($id)) {
$query->is_home = FALSE;
$query->is_page = TRUE;
$query->set("p", $id);
$query->set("page_id", $id);
//pokud homepage ve zvolenem jazyce neexistuje, je potreba vratit 404 Not Found
} else {
$query->is_home = FALSE;
$query->is_404 = FALSE;
$query->is_post_page = TRUE;
}
} else {
$is_page = (icom_get_post_type($id) == "post" ? false : true);
$query->is_home = FALSE;
$query->is_404 = FALSE;
$query->is_admin = FALSE;
if ($is_page == false) {
$query->is_page = FALSE;
$query->is_single = TRUE;
$query->set("p", $id);
$query->set("page_id", 0);
} else {
$query->is_page = TRUE;
$query->is_single = FALSE;
$query->set("p", 0);
$query->set("page_id", $id);
}
$query->is_archive = FALSE;
$query->is_preview = get_query_var('preview');
$query->is_date = FALSE;
$query->is_year = FALSE;
$query->is_month = FALSE;
$query->is_time = FALSE;
$query->is_author = FALSE;
$query->is_category = FALSE;
$query->is_tag = FALSE;
$query->is_tax = FALSE;
$query->is_search = FALSE;
$query->is_feed = FALSE;
$query->is_comment_feed = FALSE;
$query->is_trackback = FALSE;
$query->is_comments_popup = FALSE;
$query->is_attachment = FALSE;
$query->is_singular = TRUE;
$query->is_robots = FALSE;
$query->is_paged = FALSE;
}
$url_array = explode("?", ICOM_ACTUAL);
$link = icom_get_post_permalink($id);
$post_status = icom_get_post_status($id); // draft, publish, future, ...
// pokud jsou nastaveny permalinky a je v url ?lang=jazyk, přesměrujeme, aby tam nebyl
// anebo pokud tam není a měl by být (může se stát u default_jazyka)
if ($id != null && $link != null && $is_permalink == true && (isset($_GET['p']) || isset($_GET['page_id']) || isset($_GET['lang']) || $url_array[0] != $link) && $post_status != "draft") {
$url = "?" . $url_array[1];
$url = preg_replace("/[?|&]p(=[^&]*)?/", "", $url);
$url = preg_replace("/[?|&]lang(=[^&]*)?/", "", $url);
$url = preg_replace("/[?|&]page_id(=[^&]*)?/", "", $url);
//$url = trim($url, "&");
//$url = preg_replace("/[&]+/", "&", $url);
$url = trim($link . "?" . $url, "?");
wp_redirect($url);
exit();
}
// ziskani zaznamu stranky z ICOM_TRANSLATION
$post = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . icom_save_db($id) . "'");
// Pokud se jazyk stranky, kterou chceme nacist (zobrazit) neshodujes jazykem uvedenym v URL
if ($id != null && $is_permalink == true && strcasecmp($post->lang, $current_lang) != 0) {
// ziskani noveho ID pro presmerovani
if ($post->id_post_parent == 0) {
$new_post_id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE (id_post_orig = '" . icom_save_db($id) . "' OR id_post_parent = '" . icom_save_db($id) . "') AND lang = '" . $current_lang . "' AND preview = '0'");
} else {
$new_post_id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE (id_post_orig = '" . $post->id_post_parent . "' OR id_post_parent = '" . $post->id_post_parent . "') AND lang = '" . $current_lang . "' AND preview = '0'");
}
// presmerovani na novou stranku, se spravnym jazykem
if (isset($new_post_id)) {
update_last_lang_option($current_lang);
wp_redirect(icom_get_post_permalink($new_post_id));
exit();
}
} else if ($id != null && strcasecmp($last_lang, $current_lang) != 0) {
update_last_lang_option($current_lang);
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
/*
if ($is_page == true) {
$query->set('page_id', $id);
} else if ($query->is_main_query()) {
$query->set('p', $id);
}
*/
} else if ($id != null) {
echo "aaa";
update_last_lang_option($current_lang);
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
}
// pokud jsou vypnuty permalinky
if ($is_permalink == false) {
$id2 = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE id_post_parent = '" . $id . "' AND lang = '" . $current_lang . "' AND preview = '0'");
if (!isset($id2)) {
$parent = $wpdb->get_var("SELECT id_post_parent FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . $id . "' AND lang = '" . $current_lang . "' AND preview = '0'");
if (!isset($parent)) $id = null;
} else {
$id = $id2;
}
if (isset($id)) {
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
} else {
$query->is_404 = TRUE;
}
}
if ($id == null) $query->is_404 = TRUE;
return $query;
}
/**
* Aktualizuje polozku 'icom_last_lang' v databazi
* @param String $lang
*/
function update_last_lang_option($lang) {
update_option("icom_language_last", $lang);
}
// přidání nového tagu %lang%, který se pak používá ve struktuře permalinků v nastavení
function icom_lang_rewrite_tag() {
add_rewrite_tag('%lang%', '^([a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2})?)');
add_rewrite_tag('%icompage%', '([-a-zA-Z_]+)$');
}
// přidání htaccess pravidla, pro odchycení jazyka (ten musí být ve tvaru (aaz-aazz?-az?)
function icom_lang_rewrite_rule() {
add_rewrite_rule('^([a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2})?)/(.+)', 'index.php?lang=$matches[1]&icompage=$matches[4]', 'top');
}
| idiomaCoLtd/StreamAPI-wordpress-plugin | stream-api_loading_pages.php | PHP | mit | 15,619 |
/**
* @package EntegreJS
* @subpackage Widgets
* @subpackage fontawesome
* @author James Linden <kodekrash@gmail.com>
* @copyright 2016 James Linden
* @license MIT
*/
E.widget.fontawesome = class extends E.factory.node {
constructor( icon ) {
super( 'i' );
this.attr( 'class', `fa fa-${icon.toString().toLowerCase()}` );
}
static css() {
return 'https:/' + '/maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
}
size( size ) {
if( !E.empty( size ) ) {
var sizes = [ 'lg', '2x', '3x', '4x', '5x' ];
size = size.toString().toLowerCase();
if( sizes.includes( size ) ) {
this.attr( 'class', `fa-${size}` );
}
}
return this;
}
fixedwidth() {
this.attr( 'class', 'fa-fw' );
return this;
}
border() {
this.attr( 'class', 'fa-border' );
return this;
}
rotate( angle ) {
angle = parseInt( angle );
if( angle >= 0 && angle <= 360 ) {
this.attr( 'class', `fa-rotate-${angle}` );
}
return this;
}
flip( dir ) {
if( !E.empty( dir ) ) {
switch( dir.toString().toLowerCase() ) {
case 'h':
case 'horz':
dir = 'horizontal';
break;
case 'v':
case 'vert':
dir = 'vertical';
break;
}
if( dir in [ 'horizontal', 'vertical' ] ) {
this.attr( 'class', `fa-flip-${dir}` );
}
}
return this;
}
};
| entegreio/entegre-js | src/widget/fontawesome.js | JavaScript | mit | 1,327 |
import unittest
from app.commands.file_command import FileCommand
class TestFileCommand(unittest.TestCase):
def setUp(self):
self.window = WindowSpy()
self.settings = PluginSettingsStub()
self.sublime = SublimeSpy()
self.os_path = OsPathSpy()
# SUT
self.command = FileCommand(self.settings, self.os_path, self.sublime)
def test_open_source_file(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_works_with_backslashes(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('C:\\path\\to\\root\\tests\\unit\\path\\to\\fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_works_for_network_paths(self):
self.settings.tests_folder = 'tests'
self.command.open_source_file('\\\\server\\dev\\root\\tests\\unit\\Service\\SearchParametersMapperTest.php',
self.window)
self.assertEqual('\\\\server\\dev\\root\\Service\\SearchParametersMapper.php', self.window.file_to_open)
def test_open_source_file_works_for_network_paths_and_complex_tests_folder(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('\\\\server\\dev\\root\\tests\\unit\\Service\\SearchParametersMapperTest.php',
self.window)
self.assertEqual('\\\\server\\dev\\root\\Service\\SearchParametersMapper.php', self.window.file_to_open)
def test_open_source_file_when_tests_folder_is_not_unit_test_folder(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests_folder'
self.command.open_source_file('C:/path/to/root/tests_folder/unit/path/to/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_remove_only_first_appearance_of_tests_folder_in_path(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests'
self.command.open_source_file('C:/path/to/root/tests/unit/path/to/tests/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/tests/file.php', self.window.file_to_open)
def test_open_source_file_when_tests_folder_is_not_unit_test_folder_remove_only_unit_folder_after_test_path(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests_folder'
self.command.open_source_file('C:/path/to/root/tests_folder/unit/path/to/unit/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/unit/file.php', self.window.file_to_open)
def test_if_source_file_exists_return_true(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
actual = self.command.source_file_exists('C:\\path\\to\\root\\tests\\unit\\path\\to\\fileTest.php')
self.assertTrue(actual)
self.assertEqual('C:/path/to/root/path/to/file.php', self.os_path.isfile_received_filepath)
def test_source_file_does_not_exist_if_file_already_is_a_source_file(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
actual = self.command.source_file_exists('root\path\src\Gallery\ImageType.php')
self.assertFalse(actual)
def test_if_source_file_does_not_exist_return_false(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = False
self.assertFalse(self.command.source_file_exists('C:/path/to/root/path/to/fileTest.php'))
self.assertEqual('C:/path/to/root/path/to/file.php', self.os_path.isfile_received_filepath)
def test_if_source_file_is_none_return_false(self):
""" This case is possible when currently opened tab in sublime is untitled (i.e. not yet created) file """
self.assertFalse(self.command.source_file_exists(None))
def test_if_test_file_is_none_return_false(self):
""" This case is possible when currently opened tab in sublime is untitled (i.e. not yet created) file """
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests/unit'
self.assertFalse(self.command.test_file_exists(None, self.window))
def test_open_file(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests/unit'
self.command.open_test_file('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window.file_to_open)
def test_correct_file_name_sent_to_os_is_file_method(self):
self.window.project_root = 'C:/path/to/root'
self.settings.root = ''
self.settings.tests_folder = 'tests/unit'
self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
def test_file_exists_ignores_trailing_slash_in_root_path(self):
self.window.project_root = 'C:/path/to/root/'
self.settings.root = ''
self.settings.tests_folder = 'tests/unit'
self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
def test_if_test_file_exists_return_true(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
self.assertTrue(self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window))
def test_test_file_exists_returns_true_if_test_file_is_input(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
self.assertTrue(self.command.test_file_exists('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window))
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath,
'Expected test file filepath as parameter to isfile')
def test_if_test_file_does_not_exist_return_false(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = False
self.assertFalse(self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window))
def test_replace_back_slashes_with_forward_slashes(self):
self.window.project_root = 'C:\\path\\to\\root'
self.settings.root = ''
self.settings.tests_folder = 'tests\\unit'
self.command.test_file_exists('C:\\path\\to\\root\\path\\to\\file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
class PluginSettingsStub:
pass
class WindowSpy:
def __init__(self):
self.file_to_open = None
self.project_root = None
def folders(self):
return [self.project_root]
def open_file(self, file_to_open):
self.file_to_open = file_to_open
class OsPathSpy:
def __init__(self):
self.is_file_returns = None
self.isfile_received_filepath = None
def isfile(self, filepath):
self.isfile_received_filepath = filepath
return self.is_file_returns
class SublimeSpy:
pass
| ldgit/remote-phpunit | tests/app/commands/test_file_command.py | Python | mit | 7,821 |
# keyclic_sdk_api.model.FeedbackLinksImagesIriTemplate
## Load the model package
```dart
import 'package:keyclic_sdk_api/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**mapping** | [**FeedbackLinksImageIriTemplateMapping**](FeedbackLinksImageIriTemplateMapping.md) | | [optional] [default to null]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
| Keyclic/keyclic-sdk | dart/doc/FeedbackLinksImagesIriTemplate.md | Markdown | mit | 544 |
<?php
/**
* Created by PhpStorm.
* User: Lien
* Date: 27/04/2017
* Time: 16:43
*/
use app\models\ModelEvents;
class ModelEventsTest extends PHPUnit_Framework_TestCase
{
} | Alevyr/WebAdvancedCodeIgniter2017 | application/test/models/ModelEventsTest.php | PHP | mit | 179 |
//https://omegaup.com/arena/problem/El-Arreglo-de-Nieves
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
struct inf
{
int p, v;
};
int nums, totes, mint, stval;
int nlist[1000005], tol[1000005], tor[1000005], seen[1000005];
inf lastnp[1000005];
int main()
{
scanf("%d", &nums);
for(int i=1; i<=nums; i++)
scanf("%d", &nlist[i]);
for(int i=1; i<=nums; i++)
{
while(stval && lastnp[stval].v%nlist[i]==0)
stval--;
if(stval)
tol[i]=lastnp[stval].p+1;
else
tol[i]=1;
stval++;
lastnp[stval]={i, nlist[i]};
}
stval=0;
for(int i=nums; i; i--)
{
while(stval && lastnp[stval].v%nlist[i]==0)
stval--;
if(stval)
tor[i]=lastnp[stval].p-1;
else
tor[i]=nums;
stval++;
lastnp[stval]={i, nlist[i]};
}
for(int i=1; i<=nums; i++)
{
if(tor[i]-tol[i]+1>tor[totes]-tol[totes]+1)
totes=i;
}
for(int i=1; i<=nums; i++)
{
if(tor[i]-tol[i]+1==tor[totes]-tol[totes]+1 && !seen[tol[i]])
seen[tol[i]]=1, mint++;
}
printf("%d %d\n", mint, tor[totes]-tol[totes]);
for(int i=1; i<=nums; i++)
{
if(seen[i])
printf("%d ", i);
}
printf("\n");
return 0;
}
| JFAlexanderS/Contest-Archive | OmegaUp/El-Arreglo-de-Nieves.cpp | C++ | mit | 1,363 |
/*
* Class Name: Constantes
* Name: Daniel Arevalo
* Date: 13/03/2016
* Version: 1.0
*/
package co.edu.uniandes.ecos.tarea4.util;
/**
* Clase utilitaria de constantes
* @author Daniel
*/
public class Constantes {
public static final String LOC_METHOD_DATA = "LOC/Method Data";
public static final String PGS_CHAPTER = "Pgs/Chapter";
public static final String CLASS_NAME = "Class Name";
public static final String PAGES = "Pages";
}
| darevalor/Ecos-Tarea4 | src/main/java/co/edu/uniandes/ecos/tarea4/util/Constantes.java | Java | mit | 600 |
<?php
if (!class_exists('Paymentwall_Config'))
include(getcwd() . '/components/gateways/lib/paymentwall-php/lib/paymentwall.php');
/**
* Paymentwall
*
* @copyright Copyright (c) 2015, Paymentwall, Inc.
* @link http://www.paymentwall.com/ Paymentwall
*/
class Brick extends NonmerchantGateway
{
/**
* @var string The version of this Gateway
*/
private static $version = "1.0.0";
/**
* @var string The authors of this Gateway
*/
private static $authors = array(array('name' => "Paymentwall, Inc.", 'url' => "https://www.paymentwall.com"));
/**
* @var array An array of meta data for this Gateway
*/
private $meta;
/**
* Construct a new merchant Gateway
*/
public function __construct()
{
// Load components required by this module
Loader::loadComponents($this, array("Input"));
// Load the language required by this module
Language::loadLang("brick", null, dirname(__FILE__) . DS . "language" . DS);
}
/**
* Initial Paymentwall settings
*/
public function initPaymentwallConfigs()
{
Paymentwall_Config::getInstance()->set(array(
'public_key' => $this->meta['test_mode'] ? $this->meta['public_test_key'] : $this->meta['public_key'],
'private_key' => $this->meta['test_mode'] ? $this->meta['private_test_key'] : $this->meta['private_key']
));
}
/**
* Attempt to install this Gateway
*/
public function install()
{
// Ensure that the system has support for the JSON extension
if (!function_exists("json_decode")) {
$errors = array(
'json' => array(
'required' => Language::_("Brick.!error.json_required", true)
)
);
$this->Input->setErrors($errors);
}
}
/**
* Returns the name of this Gateway
*
* @return string The common name of this Gateway
*/
public function getName()
{
return Language::_("Brick.name", true);
}
/**
* Returns the version of this Gateway
*
* @return string The current version of this Gateway
*/
public function getVersion()
{
return self::$version;
}
/**
* Returns the name and URL for the authors of this Gateway
*
* @return array The name and URL of the authors of this Gateway
*/
public function getAuthors()
{
return self::$authors;
}
/**
* Return all currencies supported by this Gateway
*
* @return array A numerically indexed array containing all currency codes (ISO 4217 format) this Gateway supports
*/
public function getCurrencies()
{
$currencies = array();
$record = new Record();
$result = $record->select("code")->from("currencies")->fetchAll();
foreach ($result as $currency) {
$currencies[] = $currency->code;
}
unset($record);
return $currencies;
}
/**
* Sets the currency code to be used for all subsequent payments
*
* @param string $currency The ISO 4217 currency code to be used for subsequent payments
*/
public function setCurrency($currency)
{
$this->currency = $currency;
}
public function getSignupUrl()
{
return "https://api.paymentwall.com/pwaccount/signup?source=blesta&mode=merchant";
}
/**
* Create and return the view content required to modify the settings of this gateway
*
* @param array $meta An array of meta (settings) data belonging to this gateway
* @return string HTML content containing the fields to update the meta data for this gateway
*/
public function getSettings(array $meta = null)
{
$this->view = $this->makeView("settings", "default", str_replace(ROOTWEBDIR, "", dirname(__FILE__) . DS));
// Load the helpers required for this view
Loader::loadHelpers($this, array("Form", "Html"));
$this->view->set("meta", $meta);
return $this->view->fetch();
}
/**
* Validates the given meta (settings) data to be updated for this Gateway
*
* @param array $meta An array of meta (settings) data to be updated for this Gateway
* @return array The meta data to be updated in the database for this Gateway, or reset into the form on failure
*/
public function editSettings(array $meta)
{
// Verify meta data is valid
$rules = array(
'public_key' => array(
'empty' => array(
'rule' => "isEmpty",
'negate' => true,
'message' => Language::_("Brick.!error.public_key.valid", true),
'post_format' => 'trim'
)
),
'private_key' => array(
'empty' => array(
'rule' => "isEmpty",
'negate' => true,
'message' => Language::_("Brick.!error.private_key.valid", true),
'post_format' => 'trim'
)
),
'test_mode' => array(
'valid' => array(
'if_set' => true,
'rule' => array("in_array", array("true", "false")),
'message' => Language::_("Brick.!error.test_mode.valid", true)
)
)
);
// Set checkbox if not set
if (!isset($meta['test_mode']))
$meta['test_mode'] = "false";
$this->Input->setRules($rules);
// Validate the given meta data to ensure it meets the requirements
$this->Input->validates($meta);
// Return the meta data, no changes required regardless of success or failure for this Gateway
return $meta;
}
/**
* Returns an array of all fields to encrypt when storing in the database
*
* @return array An array of the field names to encrypt when storing in the database
*/
public function encryptableFields()
{
return array(
"public_key",
"private_key",
"public_test_key",
"private_test_key",
);
}
/**
* Sets the meta data for this particular Gateway
*
* @param array $meta An array of meta data to set for this Gateway
*/
public function setMeta(array $meta = null)
{
$this->meta = $meta;
}
/**
* @param $contact
* @return array
*/
private function prepareUserProfileData($contact)
{
return array(
'customer[city]' => $contact->city,
'customer[state]' => $contact->state,
'customer[address]' => $contact->address1,
'customer[country]' => $contact->country,
'customer[zip]' => $contact->zip,
'customer[username]' => $contact->email,
'customer[firstname]' => $contact->first_name,
'customer[lastname]' => $contact->last_name,
);
}
/**
* Validates the incoming POST/GET response from the gateway to ensure it is
* legitimate and can be trusted.
*
* @param array $get The GET data for this request
* @param array $post The POST data for this request
* @return array An array of transaction data, sets any errors using Input if the data fails to validate
* - client_id The ID of the client that attempted the payment
* - amount The amount of the payment
* - currency The currency of the payment
* - invoices An array of invoices and the amount the payment should be applied to (if any) including:
* - id The ID of the invoice to apply to
* - amount The amount to apply to the invoice
* - status The status of the transaction (approved, declined, void, pending, reconciled, refunded, returned)
* - reference_id The reference ID for gateway-only use with this transaction (optional)
* - transaction_id The ID returned by the gateway to identify this transaction
* - parent_transaction_id The ID returned by the gateway to identify this transaction's original transaction (in the case of refunds)
*/
public function validate(array $get, array $post)
{
if(!isset($get['data'])) return false;
$data = $this->decodeData($get['data']);
unset($get['data']);
list($company_id, $payment_method) = $get;
if ($payment_method != 'brick') return false;
$brick = $post['brick'];
$this->initPaymentwallConfigs();
$status = 'error';
$cardInfo = array(
'email' => $data['email'],
'amount' => $data['amount'],
'currency' => $data['currency'],
'description' => $data['description'],
'token' => $brick['token'],
'fingerprint' => $brick['fingerprint'],
);
$charge = new Paymentwall_Charge();
$charge->create($cardInfo);
$response = json_decode($charge->getPublicData(), true);
if ($charge->isSuccessful()) {
if ($charge->isCaptured()) {
// deliver a product
$status = 'approved';
} elseif ($charge->isUnderReview()) {
// decide on risk charge
$status = 'pending';
}
} else {
$_SESSION['brick_errors'] = $response['error']['message'];
}
return array(
'client_id' => $data['client_id'],
'amount' => $data['amount'],
'currency' => $data['currency'],
'status' => $status,
'reference_id' => null,
'transaction_id' => $charge->getId() ? $charge->getId() : false,
'parent_transaction_id' => null,
'invoices' => $data['invoices'] // optional
);
}
/**
* Returns data regarding a success transaction. This method is invoked when
* a client returns from the non-merchant gateway's web site back to Blesta.
*
* @param array $get The GET data for this request
* @param array $post The POST data for this request
* @return array An array of transaction data, may set errors using Input if the data appears invalid
* - client_id The ID of the client that attempted the payment
* - amount The amount of the payment
* - currency The currency of the payment
* - invoices An array of invoices and the amount the payment should be applied to (if any) including:
* - id The ID of the invoice to apply to
* - amount The amount to apply to the invoice
* - status The status of the transaction (approved, declined, void, pending, reconciled, refunded, returned)
* - transaction_id The ID returned by the gateway to identify this transaction
* - parent_transaction_id The ID returned by the gateway to identify this transaction's original transaction
*/
public function success(array $get, array $post)
{
if(isset($_SESSION['brick_errors']) && $_SESSION['brick_errors']){
$this->Input->setErrors(array(
array(
'general' => $_SESSION['brick_errors']
)
));
unset($_SESSION['brick_errors']);
}
return array(
'client_id' => $this->ifSet($post['client_id']),
'amount' => $this->ifSet($post['total']),
'currency' => $this->ifSet($post['currency_code']),
'invoices' => null,
'status' => "approved",
'transaction_id' => $this->ifSet($post['order_number']),
'parent_transaction_id' => null
);
}
/**
* Returns all HTML markup required to render an authorization and capture payment form
*
* @param array $contact_info An array of contact info including:
* - id The contact ID
* - client_id The ID of the client this contact belongs to
* - user_id The user ID this contact belongs to (if any)
* - contact_type The type of contact
* - contact_type_id The ID of the contact type
* - first_name The first name on the contact
* - last_name The last name on the contact
* - title The title of the contact
* - company The company name of the contact
* - address1 The address 1 line of the contact
* - address2 The address 2 line of the contact
* - city The city of the contact
* - state An array of state info including:
* - code The 2 or 3-character state code
* - name The local name of the country
* - country An array of country info including:
* - alpha2 The 2-character country code
* - alpha3 The 3-character country code
* - name The english name of the country
* - alt_name The local name of the country
* - zip The zip/postal code of the contact
* @param float $amount The amount to charge this contact
* @param array $invoice_amounts An array of invoices, each containing:
* - id The ID of the invoice being processed
* - amount The amount being processed for this invoice (which is included in $amount)
* @param array $options An array of options including:
* - description The Description of the charge
* - return_url The URL to redirect users to after a successful payment
* - recur An array of recurring info including:
* - amount The amount to recur
* - term The term to recur
* - period The recurring period (day, week, month, year, onetime) used in conjunction with term in order to determine the next recurring payment
* @return string HTML markup required to render an authorization and capture payment form
*/
public function buildProcess(array $contact_info, $amount, array $invoice_amounts = null, array $options = null)
{
$this->initPaymentwallConfigs();
$post_to = Configure::get("Blesta.gw_callback_url") . Configure::get("Blesta.company_id") . "/brick/";
$fields = array();
$contact = false;
// Set contact email address and phone number
if ($this->ifSet($contact_info['id'], false)) {
Loader::loadModels($this, array("Contacts"));
$contact = $this->Contacts->get($contact_info['id']);
} else {
return "Contact information invalid!";
}
$data = array(
'public_key' => Paymentwall_Config::getInstance()->getPublicKey(),
'amount' => $amount,
'merchant' => $this->ifSet($this->meta['merchant_name'], 'Blesta'),
'product_name' => $options['description'],
'currency' => $this->currency
);
$post_to .= "?data=" . $this->encodeData(array(
'client_id' => $contact->client_id,
'amount' => $amount,
'currency' => $this->currency,
'invoices' => $invoice_amounts,
'email' => $contact->email,
'description' => $options['description'],
));
$this->view = $this->makeView("process", "default", str_replace(ROOTWEBDIR, "", dirname(__FILE__) . DS));
$this->view->set("data", $data);
$this->view->set("post_to", $post_to);
$this->view->set("fields", $fields);
return $this->view->fetch();
}
/**
* @param array $data
* @return string
*/
private function encodeData($data = array())
{
return base64_encode(serialize($data));
}
/**
* @param $strData
* @return mixed
*/
private function decodeData($strData)
{
return unserialize(base64_decode($strData));
}
}
| paymentwall/module-blesta | src/components/gateways/nonmerchant/brick/brick.php | PHP | mit | 16,335 |
package org.butioy.framework.security;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Created with IntelliJ IDEA.
* Author butioy
* Date 2015-09-18 22:33
*/
public class XSSHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
public XSSHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
}
/**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if(StringUtils.isNotBlank(value)) {
value = xssEncode(value);
}
return value;
}
/**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if( StringUtils.isNotBlank(value) ) {
value = xssEncode(value);
}
return value;
}
/**
* 将容易引起xss漏洞的参数全部使用StringEscapeUtils转义
* @param value
* @return
*/
private static String xssEncode(String value) {
if (value == null || value.isEmpty()) {
return value;
}
value = StringEscapeUtils.escapeHtml4(value);
value = StringEscapeUtils.escapeEcmaScript(value);
return value;
}
/**
* 获取最原始的request
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request的静态方法
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
if (request instanceof XSSHttpServletRequestWrapper) {
return ((XSSHttpServletRequestWrapper) request).getOrgRequest();
}
return request;
}
}
| butioy/webIM | butioy-framework-src/org/butioy/framework/security/XSSHttpServletRequestWrapper.java | Java | mit | 2,507 |
#include <Esp.h>
#include "FS.h"
#ifdef ESP32
#include <SPIFFS.h>
#endif
#include "iotsaFilesUpload.h"
#ifdef IOTSA_WITH_WEB
void IotsaFilesUploadMod::setup() {
}
static File _uploadFile;
static bool _uploadOK;
void
IotsaFilesUploadMod::uploadHandler() {
if (needsAuthentication("uploadfiles")) return;
HTTPUpload& upload = server->upload();
_uploadOK = false;
if(upload.status == UPLOAD_FILE_START){
String _uploadfilename = "/data/" + upload.filename;
IFDEBUG IotsaSerial.print("Uploading ");
IFDEBUG IotsaSerial.println(_uploadfilename);
if(SPIFFS.exists(_uploadfilename)) SPIFFS.remove(_uploadfilename);
_uploadFile = SPIFFS.open(_uploadfilename, "w");
//DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
} else if(upload.status == UPLOAD_FILE_WRITE){
if(_uploadFile) _uploadFile.write(upload.buf, upload.currentSize);
//DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END){
if(_uploadFile) {
_uploadFile.close();
_uploadOK = true;
}
//DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
}
}
void
IotsaFilesUploadMod::uploadOkHandler() {
String message;
if (_uploadOK) {
IFDEBUG IotsaSerial.println("upload ok");
server->send(200, "text/plain", "OK");
} else {
IFDEBUG IotsaSerial.println("upload failed");
server->send(403, "text/plain", "FAIL");
}
}
void IotsaFilesUploadMod::uploadFormHandler() {
if (needsAuthentication("uploadfiles")) return;
String message = "<form method='POST' action='/upload' enctype='multipart/form-data'>Select file to upload:<input type='file' name='blob'><br>Filename:<input name='filename'><br><input type='submit' value='Update'></form>";
server->send(200, "text/html", message);
}
void IotsaFilesUploadMod::serverSetup() {
server->on("/upload", HTTP_POST, std::bind(&IotsaFilesUploadMod::uploadOkHandler, this), std::bind(&IotsaFilesUploadMod::uploadHandler, this));
server->on("/upload", HTTP_GET, std::bind(&IotsaFilesUploadMod::uploadFormHandler, this));
}
String IotsaFilesUploadMod::info() {
return "<p>See <a href=\"/upload\">/upload</a> for uploading new files.</p>";
}
void IotsaFilesUploadMod::loop() {
}
#endif // IOTSA_WITH_WEB | cwi-dis/iotsa | src/iotsaFilesUpload.cpp | C++ | mit | 2,362 |
<?php
declare(strict_types=1);
/*
* This file is part of the humbug/php-scoper package.
*
* Copyright (c) 2017 Théo FIDRY <theo.fidry@gmail.com>,
* Pádraic Brady <padraic.brady@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
'meta' => [
'title' => 'Static method call statement of a class imported with a use statement in a namespace',
// Default values. If not specified will be the one used
'prefix' => 'Humbug',
'whitelist' => [],
'exclude-namespaces' => [],
'expose-global-constants' => true,
'expose-global-classes' => false,
'expose-global-functions' => true,
'exclude-constants' => [],
'exclude-classes' => [],
'exclude-functions' => [],
'registered-classes' => [],
'registered-functions' => [],
],
'Static method call statement of a class belonging to the global namespace imported via a use statement' => <<<'PHP'
<?php
namespace {
class Foo {}
}
namespace A {
use Foo;
Foo::main();
}
----
<?php
namespace Humbug;
class Foo
{
}
namespace Humbug\A;
use Humbug\Foo;
Foo::main();
PHP
,
'FQ static method call statement of a class belonging to the global namespace imported via a use statement' => <<<'PHP'
<?php
namespace {
class Foo {}
}
namespace A {
use Foo;
\Foo::main();
}
----
<?php
namespace Humbug;
class Foo
{
}
namespace Humbug\A;
use Humbug\Foo;
\Humbug\Foo::main();
PHP
,
'Static method call statement of a class belonging to the global namespace which has been whitelisted' => <<<'PHP'
<?php
namespace A;
use Closure;
Closure::bind();
----
<?php
namespace Humbug\A;
use Closure;
Closure::bind();
PHP
,
'FQ static method call statement of a class belonging to the global namespace which has been whitelisted' => <<<'PHP'
<?php
namespace A;
use Closure;
\Closure::bind();
----
<?php
namespace Humbug\A;
use Closure;
\Closure::bind();
PHP
,
];
| webmozart/php-scoper | specs/static-method/namespace-two-parts-with-single-level-use.php | PHP | mit | 2,100 |
<?php
class Auth_Model extends CoreApp\DataModel {
public function __construct() {
parent::__construct();
$this->PDO = $this->database->PDOConnection(CoreApp\AppConfig::getData("database=>autchenticationDB"));
$this->database->PDOClose();
}
public function getLocation($la, $lo) {
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($la).','.trim($lo).'&sensor=false';
$json = @file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
}
else{
$location = "We're not able to get your position.";
}
//Print address
echo $location;
}
public function newAttemptUser($data) {
//Creating the new Attempt User
$a = new CoreApp\AttemptUser();
//Setting it's properties
$a->aemail = $data["ema"];
$a->apassword = $data["passw"];
$a->devicekey = $data["dk"];
$a->lalo = $data["lalo"];
//XSS, INJECTION ECT...
$a->prepareCredentials();
//return to the attemptuser
return $a;
}
}
| LetsnetHungary/letsnet | App/_models/Auth_Model.php | PHP | mit | 1,452 |
package lua
type lValueArraySorter struct {
L *LState
Fn *LFunction
Values []LValue
}
func (lv lValueArraySorter) Len() int {
return len(lv.Values)
}
func (lv lValueArraySorter) Swap(i, j int) {
lv.Values[i], lv.Values[j] = lv.Values[j], lv.Values[i]
}
func (lv lValueArraySorter) Less(i, j int) bool {
if lv.Fn != nil {
lv.L.Push(lv.Fn)
lv.L.Push(lv.Values[i])
lv.L.Push(lv.Values[j])
lv.L.Call(2, 1)
return LVAsBool(lv.L.reg.Pop())
}
return lessThan(lv.L, lv.Values[i], lv.Values[j])
}
func newLTable(acap int, hcap int) *LTable {
if acap < 0 {
acap = 0
}
if hcap < 0 {
hcap = 0
}
tb := <able{
array: make([]LValue, 0, acap),
dict: make(map[LValue]LValue, hcap),
keys: nil,
k2i: nil,
Metatable: LNil,
}
return tb
}
func (tb *LTable) Len() int {
var prev LValue = LNil
for i := len(tb.array) - 1; i >= 0; i-- {
v := tb.array[i]
if prev == LNil && v != LNil {
return i + 1
}
prev = v
}
return 0
}
func (tb *LTable) Append(value LValue) {
tb.array = append(tb.array, value)
}
func (tb *LTable) Insert(i int, value LValue) {
if i > len(tb.array) {
tb.RawSetInt(i, value)
return
}
if i <= 0 {
tb.RawSet(LNumber(i), value)
return
}
i -= 1
tb.array = append(tb.array, LNil)
copy(tb.array[i+1:], tb.array[i:])
tb.array[i] = value
}
func (tb *LTable) MaxN() int {
for i := len(tb.array) - 1; i >= 0; i-- {
if tb.array[i] != LNil {
return i
}
}
return 0
}
func (tb *LTable) Remove(pos int) {
i := pos - 1
larray := len(tb.array)
switch {
case i >= larray:
return
case i == larray-1 || i < 0:
tb.array = tb.array[:larray-1]
default:
copy(tb.array[i:], tb.array[i+1:])
tb.array[larray-1] = nil
tb.array = tb.array[:larray-1]
}
}
func (tb *LTable) RawSet(key LValue, value LValue) {
switch v := key.(type) {
case LNumber:
if isArrayKey(v) {
index := int(v) - 1
alen := len(tb.array)
switch {
case index == alen:
tb.array = append(tb.array, value)
case index > alen:
for i := 0; i < (index - alen); i++ {
tb.array = append(tb.array, LNil)
}
tb.array = append(tb.array, value)
case index < alen:
tb.array[index] = value
}
return
}
}
tb.dict[key] = value
}
func (tb *LTable) RawSetInt(key int, value LValue) {
if key < 1 || key >= MaxArrayIndex {
tb.dict[LNumber(key)] = value
return
}
index := key - 1
alen := len(tb.array)
switch {
case index == alen:
tb.array = append(tb.array, value)
case index > alen:
for i := 0; i < (index - alen); i++ {
tb.array = append(tb.array, LNil)
}
tb.array = append(tb.array, value)
case index < alen:
tb.array[index] = value
}
}
func (tb *LTable) RawSetH(key LValue, value LValue) {
tb.dict[key] = value
}
func (tb *LTable) RawGet(key LValue) LValue {
switch v := key.(type) {
case LNumber:
if isArrayKey(v) {
index := int(v) - 1
if index >= len(tb.array) {
return LNil
}
return tb.array[index]
}
}
if v, ok := tb.dict[key]; ok {
return v
}
return LNil
}
func (tb *LTable) RawGetInt(key int) LValue {
index := int(key) - 1
if index >= len(tb.array) {
return LNil
}
return tb.array[index]
}
func (tb *LTable) RawGetH(key LValue) LValue {
if v, ok := tb.dict[key]; ok {
return v
}
return LNil
}
func (tb *LTable) ForEach(cb func(LValue, LValue)) {
for i, v := range tb.array {
if v != LNil {
cb(LNumber(i+1), v)
}
}
for k, v := range tb.dict {
if v != LNil {
cb(k, v)
}
}
}
func (tb *LTable) Next(key LValue) (LValue, LValue) {
// TODO: inefficient way
if key == LNil {
tb.keys = nil
tb.k2i = nil
key = LNumber(0)
}
if tb.keys == nil {
tb.keys = make([]LValue, len(tb.dict))
tb.k2i = make(map[LValue]int)
i := 0
for k, _ := range tb.dict {
tb.keys[i] = k
tb.k2i[k] = i
i++
}
}
if kv, ok := key.(LNumber); ok && isInteger(kv) && int(kv) >= 0 {
index := int(kv)
for ; index < len(tb.array); index++ {
if v := tb.array[index]; v != LNil {
return LNumber(index + 1), v
}
}
if index == len(tb.array) {
if len(tb.dict) == 0 {
tb.keys = nil
tb.k2i = nil
return LNil, LNil
}
key = tb.keys[0]
if v := tb.dict[key]; v != LNil {
return key, v
}
}
}
for i := tb.k2i[key] + 1; i < len(tb.dict); i++ {
key = tb.keys[i]
if v := tb.dict[key]; v != LNil {
return key, v
}
}
tb.keys = nil
tb.k2i = nil
return LNil, LNil
}
| evanphx/gopher-lua | table.go | GO | mit | 4,410 |
require("kaoscript/register");
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
var Shape = require("../export/export.class.default.ks")().Shape;
function foobar() {
if(arguments.length === 1 && Type.isString(arguments[0])) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isString(x)) {
throw new TypeError("'x' is not of type 'String'");
}
return x;
}
else if(arguments.length === 1) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isClassInstance(x, Shape)) {
throw new TypeError("'x' is not of type 'Shape'");
}
return x;
}
else {
throw new SyntaxError("Wrong number of arguments");
}
};
return {
foobar: foobar
};
}; | kaoscript/kaoscript | test/fixtures/compile/export/export.filter.func.import.js | JavaScript | mit | 914 |
/**
* Node class
* @param {object} value
* @constructor
*/
class Node {
constructor(value) {
this._data = value;
}
value() {
return this._data;
}
}
export default Node;
| jvalen/dstruct-algorithms-examples-js | src/Node/Node.js | JavaScript | mit | 190 |
There is no magic for Rails' `enum` in fixtures. If you want to use the string value (which is the entire point of using the enum), you need to ERB it up. Something like
{% highlight yaml %}
michael:
name: Michael Bluth
occupation: <%= Person.occupations[:actor] %> # because 'actor' won't do it
{% endhighlight %}
| danott/today-i-learned | _posts/2015-02-02-today-i-learned.md | Markdown | mit | 320 |
<!DOCTYPE html>
<html lang="en">
<head>
@include('includes.head')
</head>
<body>
<div id="wrapper">
<header>
@include('includes.navbar')
</header>
<div class="container">
<div class="row">
<!-- main content -->
<div id="content" class="col-md-9">
@yield('content')
</div>
<!-- sidebar content -->
<div id="sidebarRight" class="col-md-3 sidebar">
@include('includes/messages')
@yield('sidebarRight')
</div>
</div>
</div>
</div>
<footer id="footer">
@include('includes.footer')
</footer>
</body>
</html>
| GrupaZero/platform_l4 | app/views/layouts/sidebarRight.blade.php | PHP | mit | 671 |
package com.felhr.usbmassstorageforandroid.bulkonlytests;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import com.felhr.usbmassstorageforandroid.bulkonly.UsbFacade;
import com.felhr.usbmassstorageforandroid.bulkonly.UsbFacadeInterface;
import android.hardware.usb.UsbEndpoint;
import android.test.InstrumentationTestCase;
import android.util.Log;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.junit.Before;
/**
* Created by Felipe Herranz(felhr85@gmail.com) on 17/12/14.
*/
public class UsbFacadeTest extends InstrumentationTestCase
{
private UsbFacade usbFacade;
// Mocked Usb objects
@Mock
private UsbDeviceConnection mConnection;
private UsbDevice mDevice;
private UsbInterface ifaceMocked;
private UsbEndpoint mockedInEndpoint;
private UsbEndpoint mockedOutEndpoint;
@Before
public void setUp()
{
System.setProperty("dexmaker.dexcache",
getInstrumentation().getTargetContext().getCacheDir().getPath());
initUsb(0);
}
@Test
public void testOpenDevice()
{
assertEquals(true, usbFacade.openDevice());
}
@Test
public void testSendCommand()
{
usbFacade.openDevice();
waitXtime(1000);
changeBulkMethod(31);
usbFacade.sendCommand(new byte[31]);
waitXtime(1000);
}
@Test
public void testSendData()
{
usbFacade.openDevice();
changeBulkMethod(10);
usbFacade.sendData(new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09});
}
@Test
public void testRequestCsw()
{
usbFacade.openDevice();
waitXtime(1000); // A handler must be declared inside a thread. This prevents a nullPointer
usbFacade.requestCsw();
}
@Test
public void testRequestData()
{
usbFacade.openDevice();
waitXtime(1000);
usbFacade.requestData(50);
}
private void initUsb(int bulkResponse)
{
mConnection = Mockito.mock(UsbDeviceConnection.class);
mDevice = Mockito.mock(UsbDevice.class);
// UsbInterface Mass storage device, Must be injected using a setter.
ifaceMocked = Mockito.mock(UsbInterface.class);
Mockito.when(ifaceMocked.getInterfaceClass()).thenReturn(UsbConstants.USB_CLASS_MASS_STORAGE);
Mockito.when(ifaceMocked.getInterfaceSubclass()).thenReturn(0x06);
Mockito.when(ifaceMocked.getInterfaceProtocol()).thenReturn(0x50);
Mockito.when(ifaceMocked.getEndpointCount()).thenReturn(0);
// UsbEndpoints IN,OUT. Must be injected using a setter
mockedInEndpoint = Mockito.mock(UsbEndpoint.class);
mockedOutEndpoint = Mockito.mock(UsbEndpoint.class);
// UsbDeviceConnection mocked methods
Mockito.when(mConnection.claimInterface(ifaceMocked, true)).thenReturn(true);
Mockito.when(mConnection.bulkTransfer(Mockito.any(UsbEndpoint.class), Mockito.any(byte[].class) ,Mockito.anyInt(), Mockito.anyInt())).thenReturn(bulkResponse);
// UsbDevice mocked methods
Mockito.when(mDevice.getInterfaceCount()).thenReturn(1);
// Initialize and inject dependencies
usbFacade = new UsbFacade(mDevice, mConnection);
usbFacade.setCallback(mCallback);
usbFacade.injectInterface(ifaceMocked);
usbFacade.injectInEndpoint(mockedInEndpoint);
usbFacade.injectOutEndpoint(mockedOutEndpoint);
}
private void changeBulkMethod(int response)
{
Mockito.when(mConnection.bulkTransfer(Mockito.any(UsbEndpoint.class), Mockito.any(byte[].class) , Mockito.anyInt(), Mockito.anyInt())).thenReturn(response);
}
private synchronized void waitXtime(long millis)
{
try
{
wait(millis);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
private UsbFacadeInterface mCallback = new UsbFacadeInterface()
{
@Override
public void cbwResponse(int response)
{
Log.d("UsbFacadeTest", "cbwResponse: " + String.valueOf(response));
}
@Override
public void cswData(byte[] data)
{
Log.d("UsbFacadeTest", "cswData: " + String.valueOf(data.length));
}
@Override
public void dataFromHost(int response)
{
Log.d("UsbFacadeTest", "Data from Host response: " + String.valueOf(response));
}
@Override
public void dataToHost(byte[] data)
{
Log.d("UsbFacadeTest", "Length buffer: " + String.valueOf(data.length));
}
};
}
| felHR85/Pincho-Usb-Mass-Storage-for-Android | src/androidTest/java/com/felhr/usbmassstorageforandroid/bulkonlytests/UsbFacadeTest.java | Java | mit | 4,796 |
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use MongoDB\Driver\Manager;
use Monolog\Test\TestCase;
use Monolog\Formatter\NormalizerFormatter;
class MongoDBHandlerTest extends TestCase
{
public function testConstructorShouldThrowExceptionForInvalidMongo()
{
$this->expectException(\InvalidArgumentException::class);
new MongoDBHandler(new \stdClass, 'db', 'collection');
}
public function testHandleWithLibraryClient()
{
if (!(class_exists('MongoDB\Client'))) {
$this->markTestSkipped('mongodb/mongodb not installed');
}
$mongodb = $this->getMockBuilder('MongoDB\Client')
->disableOriginalConstructor()
->getMock();
$collection = $this->getMockBuilder('MongoDB\Collection')
->disableOriginalConstructor()
->getMock();
$mongodb->expects($this->once())
->method('selectCollection')
->with('db', 'collection')
->will($this->returnValue($collection));
$record = $this->getRecord();
$expected = $record;
$expected['datetime'] = $record['datetime']->format(NormalizerFormatter::SIMPLE_DATE);
$collection->expects($this->once())
->method('insertOne')
->with($expected);
$handler = new MongoDBHandler($mongodb, 'db', 'collection');
$handler->handle($record);
}
public function testHandleWithDriverManager()
{
if (!(class_exists('MongoDB\Driver\Manager'))) {
$this->markTestSkipped('ext-mongodb not installed');
}
/* This can become a unit test once ManagerInterface can be mocked.
* See: https://jira.mongodb.org/browse/PHPC-378
*/
$mongodb = new Manager('mongodb://localhost:27017');
$handler = new MongoDBHandler($mongodb, 'test', 'monolog');
$record = $this->getRecord();
try {
$handler->handle($record);
} catch (\RuntimeException $e) {
$this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
}
}
}
| pomaxa/monolog | tests/Monolog/Handler/MongoDBHandlerTest.php | PHP | mit | 2,373 |
import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export const customRegistrySupport = true;
export const defaultRegistryUrls = ['https://gitlab.com'];
export const registryStrategy = 'first';
const cacheNamespace = 'datasource-gitlab';
function getCacheKey(depHost: string, repo: string): string {
const type = 'tags';
return `${depHost}:${repo}:${type}`;
}
export async function getReleases({
registryUrl: depHost,
lookupName: repo,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
getCacheKey(depHost, repo)
);
// istanbul ignore if
if (cachedResult) {
return cachedResult;
}
const urlEncodedRepo = encodeURIComponent(repo);
// tag
const url = URL.resolve(
depHost,
`/api/v4/projects/${urlEncodedRepo}/repository/tags?per_page=100`
);
const gitlabTags = (
await gitlabApi.getJson<GitlabTag[]>(url, {
paginate: true,
})
).body;
const dependency: ReleaseResult = {
sourceUrl: URL.resolve(depHost, repo),
releases: null,
};
dependency.releases = gitlabTags.map(({ name, commit }) => ({
version: name,
gitRef: name,
releaseTimestamp: commit?.created_at,
}));
const cacheMinutes = 10;
await packageCache.set(
cacheNamespace,
getCacheKey(depHost, repo),
dependency,
cacheMinutes
);
return dependency;
}
| singapore/renovate | lib/datasource/gitlab-tags/index.ts | TypeScript | mit | 1,669 |
var AllDrinks =
[{"drinkName": "Alexander",
"recipe": "Shake all ingredients with ice and strain contents into a cocktail glass. Sprinkle nutmeg on top and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Gin_Alexander_%284371721753%29.jpg/220px-Gin_Alexander_%284371721753%29.jpg",
"alcohol": ["Brandy","Liqueur",],
"ingredients": ["1 oz cognac","1 oz white crème de cacao","1 oz light cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 8, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 2, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Americano",
"recipe": "Pour the Campari and vermouth over ice into glass, add a splash of soda water and garnish with half orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Americano_cocktail_at_Nightwood_Restaurant.jpg/220px-Americano_cocktail_at_Nightwood_Restaurant.jpg",
"alcohol": ["Vermouth","Liqueur",], "ingredients": ["1 oz Campari","1 oz red vermouth","A splash of soda water",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 7, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 7}
}
},
{"drinkName": "Aperol Spritz",
"recipe": "Add 3 parts prosecco, 2 parts Aperol and top up with soda water, garnish with a slice of orange and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Aperol_Spritz_2014a.jpg/220px-Aperol_Spritz_2014a.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 parts Prosecco","2 parts Aperol","1 part Soda Water",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 5}
}
},
{"drinkName": "Appletini",
"recipe": "Mix in a shaker, then pour into a chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Appletini.jpg/220px-Appletini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Apple schnapps / Calvados","½ oz (1 part) Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 3, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Aviation",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Aviation_Cocktail.jpg/220px-Aviation_Cocktail.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 7, "wSleep": 5}}},
{"drinkName": "B-52",
"recipe": "Layer ingredients into a shot glass. Serve with a stirrer.",
"image": "https://upload.wikimedia.org/wikipedia/commons/3/3a/Cocktail_B52.jpg",
"alcohol": ["Liqueur","Brandy",],
"ingredients": ["¾ oz Kahlúa","¾ oz Baileys Irish Cream","¾ oz Grand Marnier",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 6, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 7, "wSleep": 6}
}
},
{"drinkName": "Bellini",
"recipe": "Pour peach purée into chilled flute, add sparkling wine. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3½ oz (2 parts) Prosecco","2 oz (1 part) fresh peach purée",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 5, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bijou",
"recipe": "Stir in mixing glass with ice and strain",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Bijou_Cocktail.jpg/220px-Bijou_Cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 part gin","1 part green Chartreuse","1 part sweet vermouth","Dash orange bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 4, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 0, "tAft": 3, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Black Russian",
"recipe": "Pour the ingredients into an old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Blackrussian.jpg/220px-Blackrussian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 3, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Black Velvet",
"recipe": "fill a tall champagne flute, halfway with chilled sparkling wine and float stout beer on top of the wine",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/f/f4/Black_Velvet_Cocktail_Layered.jpg/220px-Black_Velvet_Cocktail_Layered.jpg",
"alcohol": ["Champagne","Wine",],
"ingredients": ["Beer","Sparkling wine",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Bloody Mary",
"recipe": "Add dashes of Worcestershire Sauce, Tabasco, salt and pepper into highball glass, then pour all ingredients into highball with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Bloody_Mary.jpg/220px-Bloody_Mary.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","3 oz (6 parts) Tomato juice","½ oz (1 part) Lemon juice","2 to 3 dashes of Worcestershire Sauce","Tabasco","Celery salt","Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Blue Hawaii",
"recipe": "Combine all ingredients with ice, stir or shake, then pour into a hurricane glass with the ice. Garnish with pineapple or orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Bluehawaiian.jpg/220px-Bluehawaiian.jpg",
"alcohol": ["Vodka","Rum","Liqueur",],
"ingredients": ["3/4 oz light rum","3/4 oz vodka","1/2 oz Curaçao","3 oz pineapple juice","1 oz Sweet and Sour",],
"drinkRating": {
"weatherValue": {"wCold": 0, "wMod": 3, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 2, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Blue Lagoon",
"recipe": "pour vodka and blue curacao in a shaker with ice, shake well & strain into ice filled highball glass, top with lemonade, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg/220px-Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1 oz Blue Curacao","3½ oz Lemonade","1 orange slice.","Ice cubes",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bramble",
"recipe": "Fill glass with crushed ice. Build gin, lemon juice and simple syrup over. Stir, and then pour blackberry liqueur over in a circular fashion to create marbling effect. Garnish with two blackberries and lemon slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Bramble_Cocktail1.jpg/220px-Bramble_Cocktail1.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz simple syrup","½ oz Creme de Mure(blackberry liqueur)",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 3}
}
},
{"drinkName": "Brandy Alexander",
"recipe": "Shake and strain into a chilled cocktail glass. Sprinkle with fresh ground nutmeg.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Brandy_alexander.jpg/220px-Brandy_alexander.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1 oz (1 part) Cognac","1 oz (1 part) Crème de cacao (brown)","1 oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bronx",
"recipe": "Pour into cocktail shaker all ingredients with ice cubes, shake well. Strain in chilled cocktail or martini glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Bronx_%28cocktail%29.jpg/220px-Bronx_%28cocktail%29.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 oz (6 parts) Gin","½ oz (3 parts) Sweet Red Vermouth","½ oz (2 parts) Dry Vermouth","½ oz (3 parts) Orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bucks Fizz",
"recipe": "* Pour the orange juice into glass and top up Champagne. Stir gently, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg/220px-Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg",
"alcohol": ["Champagne",],
"ingredients": ["2 oz (1 part) orange juice","3½ oz (2 parts) Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 7, "wSleep": 5}
}
},
{"drinkName": "Casesar",
"recipe": "Worcestershire Sauce, Sriracha or lime Cholula, lemon juice, olive juice, salt and pepper. Rim with celery salt, fill pint glass with ice - add ingredients - shake passionately & garnish. ",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Caesar_Cocktail.JPG/220px-Caesar_Cocktail.JPG",
"alcohol": ["Vodka",],
"ingredients": ["3 parts Vodka","9 Clamato juice", "Cap of Lemon juice", "2 to 3 dashes of Worcestershire Sauce", "Sriracha", "Celery salt", "Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 9, "dW": 9, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Caipirinha",
"recipe": "Place lime and sugar into old fashioned glass and muddle (mash the two ingredients together using a muddler or a wooden spoon). Fill the glass with crushed ice and add the Cachaça.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/15-09-26-RalfR-WLC-0048.jpg/220px-15-09-26-RalfR-WLC-0048.jpg",
"alcohol": [],
"ingredients": ["2 oz cachaça","Half a lime cut into 4 wedges","2 teaspoons sugar",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Cape Codder",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg/220px-Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg",
"alcohol": ["Vodka",],
"ingredients": ["Vodka","Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Chimayó Cocktail",
"recipe": "Pour the tequila and unfiltered apple cider into glass over ice. Add the lemon juice and creme de cassis and stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg/220px-Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz Tequila","1 oz apple cider","1/4 oz lemon juice","1/4 oz creme de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Clover Club Cocktail",
"recipe": "Dry shake ingredients to emulsify, add ice, shake and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/9/99/Cloverclub.jpg/220px-Cloverclub.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz Gin","½ oz Lemon Juice","½ oz Raspberry Syrup","1 Egg White",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 10},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Colombia",
"recipe": "Shake the vodka and citrus juices in a mixer, then strain into the glass. Slide the grenadine down one side of the glass, where it will sink to the bottom. Slide the curacao down the other side, to lie between the vodka and grenadine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Columbia-cocktail.jpg/220px-Columbia-cocktail.jpg",
"alcohol": ["Vodka","Liqueur","Brandy",],
"ingredients": ["2 parts vodka or brandy","1 part blue Curaçao","1 part grenadine","1 part lemon juice","6 parts orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 7, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 4}
}
},
{"drinkName": "Cosmopolitan",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and double strain into large cocktail glass. Garnish with lime wheel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Cosmopolitan_%285076906532%29.jpg/220px-Cosmopolitan_%285076906532%29.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka Citron","½ oz Cointreau","½ oz Fresh lime juice","1 oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 8, "sWin": 4},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Cuba Libre",
"recipe": "Build all ingredients in a Collins glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/15-09-26-RalfR-WLC-0056.jpg/220px-15-09-26-RalfR-WLC-0056.jpg",
"alcohol": ["Rum",],
"ingredients": ["1¾ oz Cola","2 oz Light rum","½ oz Fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Dark N Stormy",
"recipe": "In a highball glass filled with ice add 2 oz dark rum and top with ginger beer. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Dark_n_Stormy.jpg/220px-Dark_n_Stormy.jpg",
"alcohol": ["Rum",],
"ingredients": ["2 oz dark rum","3½ oz Ginger beer",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "El Presidente",
"recipe": "stir well with ice, then strain into glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/El_Presidente_Cocktail.jpg/220px-El_Presidente_Cocktail.jpg",
"alcohol": ["Rum","Liqueur","Vermouth",],
"ingredients": ["Two parts rum","One part curaçao","One part dry vermouth","Dash grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Espresso Martini",
"recipe": "Pour ingredients into shaker filled with ice, shake vigorously, and strain into chilled martini glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Espresso-martini.jpg/220px-Espresso-martini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz Vodka","½ oz Kahlua","Sugar syrup","1 shot strong Espresso",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 8, "tAft": 7, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Fizzy Apple Cocktail",
"recipe": "Combine all three ingredients into a chilled glass and serve with ice and garnish.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Cup02.jpg/220px-Cup02.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1 shot Apple Vodka","1/2 cup Apple Juice","1/2 cup Lemonade",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Flaming Doctor Pepper",
"recipe": "Layer the two spirits in the shot glass, with the high-proof liquor on top. Light the shot and allow it to burn; then extinguish it by dropping it into the beer glass. Drink immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Flaming_dr_pepper_%28101492893%29.jpg/220px-Flaming_dr_pepper_%28101492893%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 pint (~13 parts) beer","3 parts Amaretto","1 part high-proof liquor",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 1},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 3, "dFS": 7},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Flaming Volcano",
"recipe": "Combine all ingredients with 2 scoops of crushed ice in a blender, blend briefly, then pour into the volcano bowl. Pour some rum into the central crater of the volcano bowl and light it.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flaming_Volcano.jpg/220px-Flaming_Volcano.jpg",
"alcohol": ["Rum","Brandy",],
"ingredients": ["1 oz light rum","1 oz brandy","1 oz overproof rum (e.g. Bacardi 151)","4 oz orange juice","2 oz lemon juice","2 oz almond flavored syrup",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "French 75",
"recipe": "Combine gin, syrup, and lemon juice in a cocktail shaker filled with ice. Shake vigorously and strain into an iced champagne glass. Top up with Champagne. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/French_75.jpg/220px-French_75.jpg",
"alcohol": ["Champagne","Gin",],
"ingredients": ["1 oz gin","2 dashes simple syrup","½ oz lemon juice","2 oz Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Gibson",
"recipe": "*Stir well in a shaker with ice, then strain into a chilled martini glass. Garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Gibson_cocktail.jpg/220px-Gibson_cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz gin","½ oz dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Gimlet",
"recipe": "Mix and serve. Garnish with a slice of lime",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Gimlet_cocktail.jpg/220px-Gimlet_cocktail.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["Five parts gin","One part simple syrup","One part sweetened lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 7, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Gin & Tonic",
"recipe": "In a glass filled with ice cubes, add gin and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Gin_and_Tonic_with_ingredients.jpg/220px-Gin_and_Tonic_with_ingredients.jpg",
"alcohol": ["Gin",],
"ingredients": ["Gin", "Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 6, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 8, "dW": 10, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Godfather",
"recipe": "Pour all ingredients directly into old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Godfather_cocktail.jpg/220px-Godfather_cocktail.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1 oz scotch whisky","1 oz Disaronno",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 4},
"timeValue": {"tMrn": 8, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Golden Dream",
"recipe": "Shake with cracked ice. Strain into glass and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg/220px-Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["¾ oz (2 parts) Galliano","¾ oz (2 parts) Triple Sec","¾ oz (2 parts) Fresh orange juice","½ oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 5, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 9, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Grasshopper",
"recipe": "Pour ingredients into a cocktail shaker with ice. Shake briskly and then strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Grasshopper_cocktail.jpg/220px-Grasshopper_cocktail.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz Crème de menthe (green)","1 oz Crème de cacao (white)","1 oz Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 7, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Greyhound",
"recipe": "Mix gin and juice, pour over ice in Old Fashioned glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Greyhound_Cocktail.jpg/220px-Greyhound_Cocktail.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz (1 parts) Gin","7 oz (4 parts) Grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 8, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 8, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Harvey Wallbanger",
"recipe": "Stir the vodka and orange juice with ice in the glass, then float the Galliano on top. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Harvey_Wallbanger.jpg/220px-Harvey_Wallbanger.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Galliano","3 oz (6 parts) fresh orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 8, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Horses Neck",
"recipe": "Pour brandy and ginger ale directly into highball glass with ice cubes. Stir gently. Garnish with lemon zest. If desired, add dashes of Angostura Bitter.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Horse%27s_Neck_cocktail.jpg/220px-Horse%27s_Neck_cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1½ oz (1 part) Brandy","1¾ oz (3 parts) Ginger ale","Dash of Angostura bitter",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 9, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Huckleberry Hound",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice - garnish with Montana Huckleberries",
"image": "http://www.trbimg.com/img-538660e1/turbine/ctn-liquor-cabinet-maggie-mcflys-20140528-001/1050/1050x591",
"alcohol": ["Vodka",],
"ingredients": ["2 oz. 44 North Huckleberry Vodka", "1 oz. Huckleberry syrup", "Lemonade or Limeade"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 9, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Hurricane",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Hurricane_cocktail.jpg/220px-Hurricane_cocktail.jpg",
"alcohol": ["Rum",],
"ingredients": ["One part dark rum","One part white rum","Half part over proofed rum","Passion fruit syrup","Lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Irish Car Bomb",
"recipe": "The whiskey is floated on top of the Irish cream in a shot glass, and the shot glass is then dropped into the stout",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Irish_Car_Bomb.jpg/220px-Irish_Car_Bomb.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1/2 oz whiskey","1/2 oz Irish cream liqueur","1/2 pint stout",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 4, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Irish Coffee",
"recipe": "Heat the coffee, whiskey and sugar; do not boil. Pour into glass and top with cream; serve hot.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Irish_coffee_glass.jpg/220px-Irish_coffee_glass.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (2 parts) Irish whiskey","3 oz (4 parts) hot coffee","1 oz (1½ parts) fresh cream","1tsp brown sugar",],
"drinkRating": {
"weatherValue": {"wCold": 10, "wMod": 8, "wWarm": 2, "wHot": 1},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 8, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 2, "wSleep": 2}
}
},
{"drinkName": "Jack Rose",
"recipe": "Traditionally shaken into a chilled glass, garnished, and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/15-09-26-RalfR-WLC-0259.jpg/220px-15-09-26-RalfR-WLC-0259.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 parts applejack","1 part lemon or lime juice","1/2 part grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 4, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 6, "dW": 4, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Japanese Slipper",
"recipe": "Shake together in a mixer with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Japanese_slipper.jpg/220px-Japanese_slipper.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz (1 part) Midori","1 oz (1 part) cointreau","1 oz (1 part) lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 3, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 3, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kalimotxo",
"recipe": "Stir together over plenty of ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Porr%C3%B3n_1.jpg/220px-Porr%C3%B3n_1.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part cola",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kamikaze",
"recipe": "Shake all ingredients together with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Kamikaze.jpg/220px-Kamikaze.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1 oz vodka","1 oz triple sec","1 oz lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 6},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 4, "sWin": 6},
"dayValue": {"dMTRS": 0, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Kentucky Corpse Reviver",
"recipe": "Shake ingredients together with ice, and strain into a glass. Garnish with mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Glass02.jpg/50px-Glass02.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1 part Bourbon","1 part Lillet Blanc","1 part Lemon Juice","1 part Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 10, "sSum": 8, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Kir",
"recipe": "Add the crème de cassis to the bottom of the glass, then top up with wine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Kir_cocktail.jpg/220px-Kir_cocktail.jpg",
"alcohol": ["Wine",],
"ingredients": ["3 oz (9 parts) white wine","½ oz (1 part) crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 8, "sSum": 7, "sFal": 4, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 5, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Kir Royal",
"recipe": "*Add the crème de cassis to the bottom of the glass, then top up champagne.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Kir_Royal.jpg/220px-Kir_Royal.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 oz champagne","½ oz crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 6, "wHot": 6},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 7, "tNt": 2, "wSleep": 0}
}
},
{"drinkName": "Long Island Iced Tea",
"recipe": "Add all ingredients into highball glass filled with ice. Stir gently. Garnish with lemon spiral. Serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Long_Island_Iced_Teas.jpg/220px-Long_Island_Iced_Teas.jpg",
"alcohol": ["Gin","Tequila","Vodka","Rum","Liqueur",],
"ingredients": ["½ oz Tequila","½ oz Vodka","½ oz White rum","½ oz Triple sec","½ oz Gin","¾ oz Lemon juice","1 oz Gomme Syrup","1 dash of Cola",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 9, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Lynchburg Lemonade",
"recipe": "Shake first 3 ingredients with ice and strain into ice-filled glass. Top with the lemonade or lemon-lime. Add ice and stir. Garnish with lemon slices and cherries.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg/220px-Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1¼ oz Tennessee whiskey", "¾ oz Triple sec", "2 oz Sour mix", "lemon-lime", "lemon slice", "cherries" ],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 2, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 7},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 1, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Mai Tai",
"recipe": "Shake all ingredients with ice. Strain into glass. Garnish and serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/Mai_Tai.jpg/220px-Mai_Tai.jpg",
"alcohol": ["Rum","Liqueur",],
"ingredients": ["1½ oz white rum","¾ oz dark rum","½ oz orange curaçao","½ oz Orgeat syrup","½ oz fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 10, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Manhattan",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Manhattan_Cocktail2.jpg/220px-Manhattan_Cocktail2.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["2 oz rye","¾ oz Sweet red vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Margarita",
"recipe": "Rub the rim of the glass with the lime slice to make the salt stick. Shake the other ingredients with ice, then carefully pour into the glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/MargaritaReal.jpg/220px-MargaritaReal.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1 oz (7 parts) tequila","¾ oz (4 parts) Cointreau","½ oz (3 parts) lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 10, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Stir well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/15-09-26-RalfR-WLC-0084.jpg/220px-15-09-26-RalfR-WLC-0084.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz (6 parts) gin","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 8, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 8},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 2, "dW": 8, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Mimosa",
"recipe": "Ensure both ingredients are well chilled, then mix into the glass. Serve cold.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Pool-side_Mimosas_at_The_Standard_Hotel.jpg/220px-Pool-side_Mimosas_at_The_Standard_Hotel.jpg",
"alcohol": ["Champagne",],
"ingredients": ["7 oz champagne","2 oz orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 5, "sWin": 4},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 9, "tAft": 4, "tNt": 3, "wSleep": 0}
}
},
{"drinkName": "Mint Julep",
"recipe": "In a highball glass gently muddle the mint, sugar and water. Fill the glass with cracked ice, add Bourbon and stir well until the glass is well frosted. Garnish with a mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Mint_Julep_im_Silberbecher.jpg/220px-Mint_Julep_im_Silberbecher.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["2 oz Bourbon whiskey","4 mint leaves","1 teaspoon powdered sugar","2 teaspoons water", "mint sprig"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 10, "pSome": 2},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 1}
}
},
{"drinkName": "Monkey Gland",
"recipe": "Shake well over ice cubes in a shaker, strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Monkey_Gland_%2811677703163%29.jpg/220px-Monkey_Gland_%2811677703163%29.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz gin","1 oz orange juice","2 drops absinthe","2 drops grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue":{"sSpr": 8, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Moscow Mule",
"recipe": "Combine vodka and ginger beer in a highball glass filled with ice. Add lime juice. Stir gently. Garnish with a lime slice and sprig of mint on the brim of the copper mug.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Moscow_Mule.jpg/220px-Moscow_Mule.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (9 parts) vodka","¼ oz (1 part) lime juice","1¾ oz (24 parts) ginger beer","lime slice", "sprig of mint"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 9, "wSleep": 4}
}
},
{"drinkName": "Negroni",
"recipe": "Stir into glass over ice, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Negroni_served_in_Vancouver_BC.jpg/220px-Negroni_served_in_Vancouver_BC.jpg",
"alcohol": ["Gin","Vermouth","Liqueur",],
"ingredients": ["1 oz gin","1 oz sweet red vermouth","1 oz campari",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Nikolaschka",
"recipe": "Pour cognac into brandy snifter, place lemon disk across the top of the glass and top with sugar and coffee.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Cocktail_-_Nikolaschka.jpg/220px-Cocktail_-_Nikolaschka.jpg",
"alcohol": ["Brandy",],
"ingredients": ["Cognac","Coffee powder","Powdered sugar","Lemon disk, peeled",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 6, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Old Fashioned",
"recipe": "Place sugar cube in old fashioned glass and saturate with bitters, add a dash of plain water. Muddle until dissolved. Fill the glass with ice cubes and add whiskey. Garnish with orange twist, and a cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Whiskey_Old_Fashioned1.jpg/220px-Whiskey_Old_Fashioned1.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz Bourbon or Rye whiskey","2 dashes Angostura bitters","1 sugar cube","Few dashes plain water","orange twist", "cocktail cherry"],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 4},
"precipValue": {"pNone": 4, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 5, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Orgasm",
"recipe": "Build all ingredients over ice in an old fashioned glass or shot glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Orgasm_%28cocktail%29.jpg/220px-Orgasm_%28cocktail%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["3/4 oz. Amaretto","3/4 oz. Kahlúa","3/4 oz. Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Paradise",
"recipe": "Shake together over ice. Strain into cocktail glass and serve chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Paradise_cocktail.jpg/220px-Paradise_cocktail.jpg",
"alcohol": ["Gin","Brandy",],
"ingredients": ["1 oz (7 parts) gin","¾ oz (4 parts) apricot brandy","½ oz (3 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 6, "tAft": 7, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Piña Colada",
"recipe": "Mix with crushed ice in blender until smooth. Pour into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Pi%C3%B1a_Colada.jpg/220px-Pi%C3%B1a_Colada.jpg",
"alcohol": ["Rum",],
"ingredients": ["1 oz (one part) white rum","1 oz (one part) coconut milk","3 oz (3 parts) pineapple juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 8, "sSum": 10, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 8, "tAft": 9, "tNt": 4, "wSleep": 1}
}
},
{"drinkName": "Pink Lady",
"recipe": "Shake ingredients very well with ice and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg/220px-Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg",
"alcohol": ["Gin",],
"ingredients": ["1.5 oz. gin","4 dashes grenadine","1 egg white","cherry"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 8, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue": {"sSpr": 8, "sSum": 7, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Planters Punch",
"recipe": "Pour all ingredients, except the bitters, into shaker filled with ice. Shake well. Pour into large glass, filled with ice. Add Angostura bitters, on top. Garnish with cocktail cherry and pineapple.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Planters_Punch_2.jpg/220px-Planters_Punch_2.jpg",
"alcohol": ["Rum",],
"ingredients": ["1½ oz Dark rum","1 oz Fresh orange juice","1 oz Fresh pineapple juice","¾ oz Fresh lemon juice","½ oz Grenadine syrup","½ oz Sugar syrup","3 or 4 dashes Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 5, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 9, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Porto Flip",
"recipe": "Shake ingredients together in a mixer with ice. Strain into glass, garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Porto_Flip.jpg/220px-Porto_Flip.jpg",
"alcohol": ["Wine","Brandy",],
"ingredients": ["½ oz (3 parts) brandy","1½ oz (8 parts) port","½ oz (2 parts) egg yolk",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 4, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 3, "dW": 9, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Rickey",
"recipe": "Combine spirit, lime and shell in a highball or wine glass. Add ice, stir and then add sparkling mineral water.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Gin_Rickey.jpg/220px-Gin_Rickey.jpg",
"alcohol": ["Gin","Whiskey",],
"ingredients": ["2oz bourbon, rye whiskey, or gin","Half of a lime","Sparkling mineral water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 7, "wWarm": 6, "wHot": 3},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rob Roy",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served straight up, or mixed in rocks glass, filled with ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/15-09-26-RalfR-WLC-0266.jpg/220px-15-09-26-RalfR-WLC-0266.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["1½ oz Scotch whisky","¾ oz Sweet vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 7, "wSleep": 8}
}
},
{"drinkName": "Rose",
"recipe": "Shake together in a cocktail shaker, then strain into chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/Rose_%28cocktail%29.jpg/220px-Rose_%28cocktail%29.jpg",
"alcohol": ["Vermouth","Brandy"],
"ingredients": ["1½ oz (2 parts) dry vermouth","¾ oz (1 parts) Kirsch","3 Dashes Strawberry syrup",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 1, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rusty Nail",
"recipe": "Pour all ingredients directly into old-fashioned glass filled with ice. Stir gently. Garnish with a lemon twist. Serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg/220px-Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["7.2 oz Scotch Whisky","¾ oz Drambuie",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 6, "wWarm": 3, "wHot": 1},
"precipValue": {"pNone": 2, "pSome": 7},
"seasonValue": {"sSpr": 2, "sSum": 1, "sFal": 6, "sWin": 8},
"dayValue": {"dMTRS": 4, "dW": 7, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 8}
}
},
{"drinkName": "Sake Bomb",
"recipe": "The shot of sake is dropped into the beer, causing it to fizz violently. The drink should then be consumed immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/Sake_bomb_-_man_pounds_table_with_fist.jpg/220px-Sake_bomb_-_man_pounds_table_with_fist.jpg",
"alcohol": ["Wine",],
"ingredients": ["1 pint (~16 parts) beer","1 shot (1.5 parts) sake",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Salty Dog",
"recipe": "Shake gin and grapefruit juice in cocktail shaker. Strain into a salt-rimmed highball glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Salty_Dog.jpg/220px-Salty_Dog.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["1½ oz gin or vodka","3½ oz grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue": {"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 4},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Screwdriver",
"recipe": "Mix in a highball glass with ice. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg/220px-Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz (1 part) vodka","3½ oz (2 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 5, "pSome": 4},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 5},
"dayValue": {"dMTRS": 9, "dW": 5, "dFS": 3},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 5}
}
},
{"drinkName": "Sea Breeze",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Cocktail_with_vodka.jpg/220px-Cocktail_with_vodka.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1¾ oz Cranberry juice","1 oz Grapefruit juice","lime wedge"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 3},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Sex on the Beach",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Sex_On_The_Beach.jpg/220px-Sex_On_The_Beach.jpg",
"alcohol": ["Vodka", "Liqueur",],
"ingredients": ["1½ oz Vodka","¾ oz Peach schnapps","1½ oz Orange juice","1½ oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 6, "sSum": 10, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 3, "wSleep": 2}
}
},
{"drinkName": "Sidecar",
"recipe": "Pour all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Sidecar-cocktail.jpg/220px-Sidecar-cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 oz cognac","¾ oz triple sec","¾ oz lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 3, "pSome": 8},
"seasonValue": {"sSpr": 9, "sSum": 6, "sFal": 5, "sWin": 7},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Singapore Sling",
"recipe": "Pour all ingredients into cocktail shaker filled with ice cubes. Shake well. Strain into highball glass. Garnish with pineapple and cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Singapore_Sling.jpg/220px-Singapore_Sling.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1 oz Gin","½ oz Cherry Liqueur","¼ oz Cointreau","¼ oz DOM Bénédictine","½ oz Grenadine","1¾ oz Pineapple juice","½ oz Fresh lime juice","1 dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "Slippery Nipple",
"recipe": "Pour the Baileys into a shot glass, then pour the Sambuca on top so that the two liquids do not mix.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Slippery_Nipple.jpg/220px-Slippery_Nipple.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["(1 part) Sambuca","(1 part) Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 8, "wHot": 4},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 2, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Springbokkie",
"recipe": "The Crème de menthe is poured into the shot glass and the Amarula is carefully layered on top.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Amarula_Springbokkie_shooter.jpg/220px-Amarula_Springbokkie_shooter.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["½ oz (1 part) Amarula","1 oz (3 parts) Crème de menthe",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 7, "tAft": 9, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Tequila & Tonic",
"recipe": "In a glass filled with ice cubes, add tequila and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Tequila_%26_Tonic.jpg/220px-Tequila_%26_Tonic.jpg",
"alcohol": ["Tequila",],
"ingredients": ["Tequila","Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 5, "wSleep": 8}
}
},
{"drinkName": "Tequila Sunrise",
"recipe": "Pour the tequila and orange juice into glass over ice. Add the grenadine, which will sink to the bottom. Do not stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg/220px-Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz (3 parts) Tequila","3 oz (6 parts) Orange juice","½ oz (1 part) Grenadine syrup",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 3, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "The Last Word",
"recipe": "Shake with ice and strain into a cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/The_Last_Word_cocktail_raised.jpg/220px-The_Last_Word_cocktail_raised.jpg",
"alcohol": ["Liqueur","Gin",],
"ingredients": ["One part gin","One part lime juice","One part green Chartreuse","One part maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 6, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 3, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 7, "dW": 4, "dFS": 3},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Tinto de Verano",
"recipe": "Mix and serve well chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Tinto_de_verano.jpg/220px-Tinto_de_verano.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part Sprite and water(or Gaseosa)",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 9, "tNt": 6, "wSleep": 1}
}
},
{"drinkName": "Tom Collins",
"recipe": "Mix the gin, lemon juice and sugar syrup in a tall glass with ice, top up with soda water, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Tom_Collins_in_Copenhagen.jpg/220px-Tom_Collins_in_Copenhagen.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz (3 parts) Old Tom Gin","1 oz (2 parts) lemon juice","½ oz (1 part) sugar syrup","2 oz (4 parts) carbonated water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 9, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Vesper",
"recipe": "Shake over ice until well chilled, then strain into a deep goblet and garnish with a thin slice of lemon peel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Vesper_Martini_%28corrected%29.jpg/220px-Vesper_Martini_%28corrected%29.jpg",
"alcohol": ["Gin","Vodka", "Wine"],
"ingredients": ["2 oz gin","½ oz vodka","¼ oz Lillet Blonde(wine)",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 4, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 9},
"seasonValue": {"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 9},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Vodka Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Shake well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Vermouth","Vodka",],
"ingredients": ["2 oz (6 parts) vodka","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 10, "wWarm": 4, "wHot": 3},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue": {"sSpr": 3, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 10, "wSleep": 9}
}
},
{"drinkName": "Whiskey Sour",
"recipe": "Shake with ice. Strain into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Whiskey_Sour.jpg/220px-Whiskey_Sour.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (3 parts) Bourbon whiskey","1 oz (2 parts) fresh lemon juice","½ oz (1 part) Gomme syrup","dash egg white (optional)",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 6, "wWarm": 6, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "White Russian",
"recipe": "Pour coffee liqueur and vodka into an Old Fashioned glass filled with ice. Float fresh cream on top and stir slowly.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/White-Russian.jpg/220px-White-Russian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur","1 oz (3 parts) fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 7, "sSum": 7, "sFal": 9, "sWin": 3},
"dayValue": {"dMTRS": 7, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Zombie",
"recipe": "Mix ingredients other than the 151 in a shaker with ice. Pour into glass and top with the high-proof rum.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Zombiecocktail.jpg/220px-Zombiecocktail.jpg",
"alcohol": ["Brandy","Rum",],
"ingredients": ["1 part white rum","1 part golden rum","1 part dark rum","1 part apricot brandy","1 part pineapple juice","½ part 151-proof rum","1 part lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 7, "wHot": 10},
"precipValue": {"pNone": 8, "pSome": 1},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 1, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 10, "tNt": 6, "wSleep": 1}
}
}]
module.exports = AllDrinks; | srs1212/drinkSync | AllDrinks.js | JavaScript | mit | 69,466 |
//
// Copyright (c) 2009-2021 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
#define USE_CSHARP_SQLITE
#endif
using System;
using System.Collections;
using System.Diagnostics;
#if !USE_SQLITEPCL_RAW
using System.Runtime.InteropServices;
#endif
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
#if USE_CSHARP_SQLITE
using Sqlite3 = Community.CsharpSqlite.Sqlite3;
using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
#elif USE_WP8_NATIVE_SQLITE
using Sqlite3 = Sqlite.Sqlite3;
using Sqlite3DatabaseHandle = Sqlite.Database;
using Sqlite3Statement = Sqlite.Statement;
#elif USE_SQLITEPCL_RAW
using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
using Sqlite3 = SQLitePCL.raw;
#else
using Sqlite3DatabaseHandle = System.IntPtr;
using Sqlite3BackupHandle = System.IntPtr;
using Sqlite3Statement = System.IntPtr;
#endif
#pragma warning disable 1591 // XML Doc Comments
namespace SQLite
{
public class SQLiteException : Exception
{
public SQLite3.Result Result { get; private set; }
protected SQLiteException (SQLite3.Result r, string message) : base (message)
{
Result = r;
}
public static SQLiteException New (SQLite3.Result r, string message)
{
return new SQLiteException (r, message);
}
}
public class NotNullConstraintViolationException : SQLiteException
{
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
protected NotNullConstraintViolationException (SQLite3.Result r, string message)
: this (r, message, null, null)
{
}
protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
: base (r, message)
{
if (mapping != null && obj != null) {
this.Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue (obj) == null
select c;
}
}
public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
{
return new NotNullConstraintViolationException (r, message);
}
public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (r, message, mapping, obj);
}
public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
}
}
[Flags]
public enum SQLiteOpenFlags
{
ReadOnly = 1, ReadWrite = 2, Create = 4,
NoMutex = 0x8000, FullMutex = 0x10000,
SharedCache = 0x20000, PrivateCache = 0x40000,
ProtectionComplete = 0x00100000,
ProtectionCompleteUnlessOpen = 0x00200000,
ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
ProtectionNone = 0x00400000
}
[Flags]
public enum CreateFlags
{
/// <summary>
/// Use the default creation options
/// </summary>
None = 0x000,
/// <summary>
/// Create a primary key index for a property called 'Id' (case-insensitive).
/// This avoids the need for the [PrimaryKey] attribute.
/// </summary>
ImplicitPK = 0x001,
/// <summary>
/// Create indices for properties ending in 'Id' (case-insensitive).
/// </summary>
ImplicitIndex = 0x002,
/// <summary>
/// Create a primary key for a property called 'Id' and
/// create an indices for properties ending in 'Id' (case-insensitive).
/// </summary>
AllImplicit = 0x003,
/// <summary>
/// Force the primary key property to be auto incrementing.
/// This avoids the need for the [AutoIncrement] attribute.
/// The primary key property on the class should have type int or long.
/// </summary>
AutoIncPK = 0x004,
/// <summary>
/// Create virtual table using FTS3
/// </summary>
FullTextSearch3 = 0x100,
/// <summary>
/// Create virtual table using FTS4
/// </summary>
FullTextSearch4 = 0x200
}
/// <summary>
/// An open connection to a SQLite database.
/// </summary>
[Preserve (AllMembers = true)]
public partial class SQLiteConnection : IDisposable
{
private bool _open;
private TimeSpan _busyTimeout;
readonly static Dictionary<string, TableMapping> _mappings = new Dictionary<string, TableMapping> ();
private System.Diagnostics.Stopwatch _sw;
private long _elapsedMilliseconds = 0;
private int _transactionDepth = 0;
private Random _rand = new Random ();
public Sqlite3DatabaseHandle Handle { get; private set; }
static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
/// <summary>
/// Gets the database path used by this connection.
/// </summary>
public string DatabasePath { get; private set; }
/// <summary>
/// Gets the SQLite library version number. 3007014 would be v3.7.14
/// </summary>
public int LibVersionNumber { get; private set; }
/// <summary>
/// Whether Trace lines should be written that show the execution time of queries.
/// </summary>
public bool TimeExecution { get; set; }
/// <summary>
/// Whether to write queries to <see cref="Tracer"/> during execution.
/// </summary>
public bool Trace { get; set; }
/// <summary>
/// The delegate responsible for writing trace lines.
/// </summary>
/// <value>The tracer.</value>
public Action<string> Tracer { get; set; }
/// <summary>
/// Whether to store DateTime properties as ticks (true) or strings (false).
/// </summary>
public bool StoreDateTimeAsTicks { get; private set; }
/// <summary>
/// Whether to store TimeSpan properties as ticks (true) or strings (false).
/// </summary>
public bool StoreTimeSpanAsTicks { get; private set; }
/// <summary>
/// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
/// </summary>
/// <value>The date time string format.</value>
public string DateTimeStringFormat { get; private set; }
/// <summary>
/// The DateTimeStyles value to use when parsing a DateTime property string.
/// </summary>
/// <value>The date time style.</value>
internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
static SQLiteConnection ()
{
SQLitePCL.Batteries_V2.Init ();
}
#endif
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="connectionString">
/// Details on how to find and open the database.
/// </param>
public SQLiteConnection (SQLiteConnectionString connectionString)
{
if (connectionString == null)
throw new ArgumentNullException (nameof (connectionString));
if (connectionString.DatabasePath == null)
throw new InvalidOperationException ("DatabasePath must be specified");
DatabasePath = connectionString.DatabasePath;
LibVersionNumber = SQLite3.LibVersionNumber ();
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
StoreTimeSpanAsTicks = connectionString.StoreTimeSpanAsTicks;
DateTimeStringFormat = connectionString.DateTimeStringFormat;
DateTimeStyle = connectionString.DateTimeStyle;
BusyTimeout = TimeSpan.FromSeconds (1.0);
Tracer = line => Debug.WriteLine (line);
connectionString.PreKeyAction?.Invoke (this);
if (connectionString.Key is string stringKey) {
SetKey (stringKey);
}
else if (connectionString.Key is byte[] bytesKey) {
SetKey (bytesKey);
}
else if (connectionString.Key != null) {
throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
}
connectionString.PostKeyAction?.Invoke (this);
}
/// <summary>
/// Enables the write ahead logging. WAL is significantly faster in most scenarios
/// by providing better concurrency and better disk IO performance than the normal
/// journal mode. You only need to call this function once in the lifetime of the database.
/// </summary>
public void EnableWriteAheadLogging ()
{
ExecuteScalar<string> ("PRAGMA journal_mode=WAL");
}
/// <summary>
/// Convert an input string to a quoted SQL string that can be safely used in queries.
/// </summary>
/// <returns>The quoted string.</returns>
/// <param name="unsafeString">The unsafe string to quote.</param>
static string Quote (string unsafeString)
{
// TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
if (unsafeString == null)
return "NULL";
var safe = unsafeString.Replace ("'", "''");
return "'" + safe + "'";
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">Ecryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
void SetKey (string key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
var q = Quote (key);
ExecuteScalar<string> ("pragma key = " + q);
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database.
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">256-bit (32 byte) ecryption key data</param>
void SetKey (byte[] key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
if (key.Length != 32 && key.Length != 48)
throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
var s = String.Join ("", key.Select (x => x.ToString ("X2")));
ExecuteScalar<string> ("pragma key = \"x'" + s + "'\"");
}
/// <summary>
/// Enable or disable extension loading.
/// </summary>
public void EnableLoadExtension (bool enabled)
{
SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
#if !USE_SQLITEPCL_RAW
static byte[] GetNullTerminatedUtf8 (string s)
{
var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
var bytes = new byte [utf8Length + 1];
utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
#endif
/// <summary>
/// Sets a busy handler to sleep the specified amount of time when a table is locked.
/// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
/// </summary>
public TimeSpan BusyTimeout {
get { return _busyTimeout; }
set {
_busyTimeout = value;
if (Handle != NullHandle) {
SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
}
}
}
/// <summary>
/// Returns the mappings from types to tables that the connection
/// currently understands.
/// </summary>
public IEnumerable<TableMapping> TableMappings {
get {
lock (_mappings) {
return new List<TableMapping> (_mappings.Values);
}
}
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="type">
/// The type whose mapping to the database is returned.
/// </param>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
TableMapping map;
var key = type.FullName;
lock (_mappings) {
if (_mappings.TryGetValue (key, out map)) {
if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
map = new TableMapping (type, createFlags);
_mappings[key] = map;
}
}
else {
map = new TableMapping (type, createFlags);
_mappings.Add (key, map);
}
}
return map;
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None)
{
return GetMapping (typeof (T), createFlags);
}
private struct IndexedColumn
{
public int Order;
public string ColumnName;
}
private struct IndexInfo
{
public string IndexName;
public string TableName;
public bool Unique;
public List<IndexedColumn> Columns;
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
public int DropTable<T> ()
{
return DropTable (GetMapping (typeof (T)));
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
public int DropTable (TableMapping map)
{
var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
return Execute (query);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None)
{
return CreateTable (typeof (T), createFlags);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <param name="ty">Type to reflect to a database table.</param>
/// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None)
{
var map = GetMapping (ty, createFlags);
// Present a nice error if no columns specified
if (map.Columns.Length == 0) {
throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
}
// Check if the table exists
var result = CreateTableResult.Created;
var existingCols = GetTableInfo (map.TableName);
// Create or migrate it
if (existingCols.Count == 0) {
// Facilitate virtual tables a.k.a. full-text search.
bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
bool fts = fts3 || fts4;
var @virtual = fts ? "virtual " : string.Empty;
var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
// Build query.
var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
var decl = string.Join (",\n", decls.ToArray ());
query += decl;
query += ")";
if (map.WithoutRowId) {
query += " without rowid";
}
Execute (query);
}
else {
result = CreateTableResult.Migrated;
MigrateTable (map, existingCols);
}
var indexes = new Dictionary<string, IndexInfo> ();
foreach (var c in map.Columns) {
foreach (var i in c.Indices) {
var iname = i.Name ?? map.TableName + "_" + c.Name;
IndexInfo iinfo;
if (!indexes.TryGetValue (iname, out iinfo)) {
iinfo = new IndexInfo {
IndexName = iname,
TableName = map.TableName,
Unique = i.Unique,
Columns = new List<IndexedColumn> ()
};
indexes.Add (iname, iinfo);
}
if (i.Unique != iinfo.Unique)
throw new Exception ("All the columns in an index must have the same value for their Unique property");
iinfo.Columns.Add (new IndexedColumn {
Order = i.Order,
ColumnName = c.Name
});
}
}
foreach (var indexName in indexes.Keys) {
var index = indexes[indexName];
var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
CreateIndex (indexName, index.TableName, columns, index.Unique);
}
return result;
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
where T5 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
{
var result = new CreateTablesResult ();
foreach (Type type in types) {
var aResult = CreateTable (type, createFlags);
result.Results[type] = aResult;
}
return result;
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
{
const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
return Execute (sql);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
{
return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string columnName, bool unique = false)
{
return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
{
return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
}
/// <summary>
/// Creates an index for the specified object property.
/// e.g. CreateIndex<Client>(c => c.Name);
/// </summary>
/// <typeparam name="T">Type to reflect to a database table.</typeparam>
/// <param name="property">Property to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false)
{
MemberExpression mx;
if (property.Body.NodeType == ExpressionType.Convert) {
mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
}
else {
mx = (property.Body as MemberExpression);
}
var propertyInfo = mx.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
}
var propName = propertyInfo.Name;
var map = GetMapping<T> ();
var colName = map.FindColumnWithPropertyName (propName).Name;
return CreateIndex (map.TableName, colName, unique);
}
[Preserve (AllMembers = true)]
public class ColumnInfo
{
// public int cid { get; set; }
[Column ("name")]
public string Name { get; set; }
// [Column ("type")]
// public string ColumnType { get; set; }
public int notnull { get; set; }
// public string dflt_value { get; set; }
// public int pk { get; set; }
public override string ToString ()
{
return Name;
}
}
/// <summary>
/// Query the built-in sqlite table_info table for a specific tables columns.
/// </summary>
/// <returns>The columns contains in the table.</returns>
/// <param name="tableName">Table name.</param>
public List<ColumnInfo> GetTableInfo (string tableName)
{
var query = "pragma table_info(\"" + tableName + "\")";
return Query<ColumnInfo> (query);
}
void MigrateTable (TableMapping map, List<ColumnInfo> existingCols)
{
var toBeAdded = new List<TableMapping.Column> ();
foreach (var p in map.Columns) {
var found = false;
foreach (var c in existingCols) {
found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
if (found)
break;
}
if (!found) {
toBeAdded.Add (p);
}
}
foreach (var p in toBeAdded) {
var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
Execute (addCol);
}
}
/// <summary>
/// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
/// </summary>
/// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
protected virtual SQLiteCommand NewCommand ()
{
return new SQLiteCommand (this);
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
/// in the command text for each of the arguments.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="ps">
/// Arguments to substitute for the occurences of '?' in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand"/>
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
var cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var o in ps) {
cmd.Bind (o);
}
return cmd;
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with named arguments. Place a "[@:$]VVV"
/// in the command text for each of the arguments. VVV represents an alphanumeric identifier.
/// For example, @name :name and $name can all be used in the query.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of "[@:$]VVV" in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand" />
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
SQLiteCommand cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var kv in args) {
cmd.Bind (kv.Key, kv.Value);
}
return cmd;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method instead of Query when you don't expect rows back. Such cases include
/// INSERTs, UPDATEs, and DELETEs.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public int Execute (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteNonQuery ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method when return primitive values.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public T ExecuteScalar<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteScalar<T> ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<T> Query<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns the first column of each row of the result.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for the first column of each row returned by the query.
/// </returns>
public List<T> QueryScalars<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQueryScalars<T> ().ToList ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<object> Query (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<object> (map);
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<object> (map);
}
/// <summary>
/// Returns a queryable interface to the table represented by the given type.
/// </summary>
/// <returns>
/// A queryable object that is able to translate Where, OrderBy, and Take
/// queries into native SQL.
/// </returns>
public TableQuery<T> Table<T> () where T : new()
{
return new TableQuery<T> (this);
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public object Get (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public T Find<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public object Find (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T Find<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T FindWithQuery<T> (string query, params object[] args) where T : new()
{
return Query<T> (query, args).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public object FindWithQuery (TableMapping map, string query, params object[] args)
{
return Query (map, query, args).FirstOrDefault ();
}
/// <summary>
/// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
/// </summary>
public bool IsInTransaction {
get { return _transactionDepth > 0; }
}
/// <summary>
/// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
/// </summary>
/// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example>
public void BeginTransaction ()
{
// The BEGIN command only works if the transaction stack is empty,
// or in other words if there are no pending transactions.
// If the transaction stack is not empty when the BEGIN command is invoked,
// then the command fails with an error.
// Rather than crash with an error, we will just ignore calls to BeginTransaction
// that would result in an error.
if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) {
try {
Execute ("begin transaction");
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
// Call decrement and not VolatileWrite in case we've already
// created a transaction point in SaveTransactionPoint since the catch.
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
}
else {
// Calling BeginTransaction on an already open transaction is invalid
throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction.");
}
}
/// <summary>
/// Creates a savepoint in the database at the current point in the transaction timeline.
/// Begins a new transaction if one is not in progress.
///
/// Call <see cref="RollbackTo(string)"/> to undo transactions since the returned savepoint.
/// Call <see cref="Release"/> to commit transactions after the savepoint returned here.
/// Call <see cref="Commit"/> to end the transaction, committing all changes.
/// </summary>
/// <returns>A string naming the savepoint.</returns>
public string SaveTransactionPoint ()
{
int depth = Interlocked.Increment (ref _transactionDepth) - 1;
string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth;
try {
Execute ("savepoint " + retVal);
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
return retVal;
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>.
/// </summary>
public void Rollback ()
{
RollbackTo (null, false);
}
/// <summary>
/// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
public void RollbackTo (string savepoint)
{
RollbackTo (savepoint, false);
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
/// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param>
void RollbackTo (string savepoint, bool noThrow)
{
// Rolling back without a TO clause rolls backs all transactions
// and leaves the transaction stack empty.
try {
if (String.IsNullOrEmpty (savepoint)) {
if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) {
Execute ("rollback");
}
}
else {
DoSavePointExecute (savepoint, "rollback to ");
}
}
catch (SQLiteException) {
if (!noThrow)
throw;
}
// No need to rollback if there are no transactions open.
}
/// <summary>
/// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint
/// makes changes since that savepoint permanent if the savepoint began the transaction,
/// or otherwise the changes are permanent pending a call to <see cref="Commit"/>.
///
/// The RELEASE command is like a COMMIT for a SAVEPOINT.
/// </summary>
/// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param>
public void Release (string savepoint)
{
try {
DoSavePointExecute (savepoint, "release ");
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Busy) {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
// Writes to the database only happen at depth=0, so this failure will only happen then.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
}
throw;
}
}
void DoSavePointExecute (string savepoint, string cmd)
{
// Validate the savepoint
int firstLen = savepoint.IndexOf ('D');
if (firstLen >= 2 && savepoint.Length > firstLen + 1) {
int depth;
if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) {
// TODO: Mild race here, but inescapable without locking almost everywhere.
if (0 <= depth && depth < _transactionDepth) {
#if NETFX_CORE || USE_SQLITEPCL_RAW || NETCORE
Volatile.Write (ref _transactionDepth, depth);
#elif SILVERLIGHT
_transactionDepth = depth;
#else
Thread.VolatileWrite (ref _transactionDepth, depth);
#endif
Execute (cmd + savepoint);
return;
}
}
}
throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint");
}
/// <summary>
/// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
public void Commit ()
{
if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) {
try {
Execute ("commit");
}
catch {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
throw;
}
}
// Do nothing on a commit with no open transaction
}
/// <summary>
/// Executes <paramref name="action"/> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an
/// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception
/// is rethrown.
/// </summary>
/// <param name="action">
/// The <see cref="Action"/> to perform within a transaction. <paramref name="action"/> can contain any number
/// of operations on the connection but should never call <see cref="BeginTransaction"/> or
/// <see cref="Commit"/>.
/// </param>
public void RunInTransaction (Action action)
{
try {
var savePoint = SaveTransactionPoint ();
action ();
Release (savePoint);
}
catch (Exception) {
Rollback ();
throw;
}
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// <param name="runInTransaction"/>
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, string extra, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, extra);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, extra);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, Type objType, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, objType);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, objType);
}
}
return c;
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "OR REPLACE", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, Type objType)
{
return Insert (obj, "", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj, Type objType)
{
return Insert (obj, "OR REPLACE", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra)
{
if (obj == null) {
return 0;
}
return Insert (obj, extra, Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra, Type objType)
{
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
if (map.PK != null && map.PK.IsAutoGuid) {
if (map.PK.GetValue (obj).Equals (Guid.Empty)) {
map.PK.SetValue (obj, Guid.NewGuid ());
}
}
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns;
var vals = new object[cols.Length];
for (var i = 0; i < vals.Length; i++) {
vals[i] = cols[i].GetValue (obj);
}
var insertCmd = GetInsertCommand (map, extra);
int count;
lock (insertCmd) {
// We lock here to protect the prepared statement returned via GetInsertCommand.
// A SQLite prepared statement can be bound for only one operation at a time.
try {
count = insertCmd.ExecuteNonQuery (vals);
}
catch (SQLiteException ex) {
if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj);
}
throw;
}
if (map.HasAutoIncPK) {
var id = SQLite3.LastInsertRowid (Handle);
map.SetAutoIncPK (obj, id);
}
}
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Insert);
return count;
}
readonly Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> _insertCommandMap = new Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> ();
PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra)
{
PreparedSqlLiteInsertCommand prepCmd;
var key = Tuple.Create (map.MappedType.FullName, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out prepCmd)) {
return prepCmd;
}
}
prepCmd = CreateInsertCommand (map, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out var existing)) {
prepCmd.Dispose ();
return existing;
}
_insertCommandMap.Add (key, prepCmd);
}
return prepCmd;
}
PreparedSqlLiteInsertCommand CreateInsertCommand (TableMapping map, string extra)
{
var cols = map.InsertColumns;
string insertSql;
if (cols.Length == 0 && map.Columns.Length == 1 && map.Columns[0].IsAutoInc) {
insertSql = string.Format ("insert {1} into \"{0}\" default values", map.TableName, extra);
}
else {
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
if (replacing) {
cols = map.InsertOrReplaceColumns;
}
insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", map.TableName,
string.Join (",", (from c in cols
select "\"" + c.Name + "\"").ToArray ()),
string.Join (",", (from c in cols
select "?").ToArray ()), extra);
}
var insertCommand = new PreparedSqlLiteInsertCommand (this, insertSql);
return insertCommand;
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj)
{
if (obj == null) {
return 0;
}
return Update (obj, Orm.GetType (obj));
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj, Type objType)
{
int rowsAffected = 0;
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
}
var cols = from p in map.Columns
where p != pk
select p;
var vals = from c in cols
select c.GetValue (obj);
var ps = new List<object> (vals);
if (ps.Count == 0) {
// There is a PK but no accompanying data,
// so reset the PK to make the UPDATE work.
cols = map.Columns;
vals = from c in cols
select c.GetValue (obj);
ps = new List<object> (vals);
}
ps.Add (pk.GetValue (obj));
var q = string.Format ("update \"{0}\" set {1} where \"{2}\" = ? ", map.TableName, string.Join (",", (from c in cols
select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
try {
rowsAffected = Execute (q, ps.ToArray ());
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex, map, obj);
}
throw ex;
}
if (rowsAffected > 0)
OnTableChanged (map, NotifyTableChangedAction.Update);
return rowsAffected;
}
/// <summary>
/// Updates all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int UpdateAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Update (r);
}
});
}
else {
foreach (var r in objects) {
c += Update (r);
}
}
return c;
}
/// <summary>
/// Deletes the given object from the database using its primary key.
/// </summary>
/// <param name="objectToDelete">
/// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows deleted.
/// </returns>
public int Delete (object objectToDelete)
{
var map = GetMapping (Orm.GetType (objectToDelete));
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, pk.GetValue (objectToDelete));
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of object.
/// </typeparam>
public int Delete<T> (object primaryKey)
{
return Delete (primaryKey, GetMapping (typeof (T)));
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int Delete (object primaryKey, TableMapping map)
{
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, primaryKey);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of objects to delete.
/// </typeparam>
public int DeleteAll<T> ()
{
var map = GetMapping (typeof (T));
return DeleteAll (map);
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int DeleteAll (TableMapping map)
{
var query = string.Format ("delete from \"{0}\"", map.TableName);
var count = Execute (query);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Backup the entire database to the specified path.
/// </summary>
/// <param name="destinationDatabasePath">Path to backup file.</param>
/// <param name="databaseName">The name of the database to backup (usually "main").</param>
public void Backup (string destinationDatabasePath, string databaseName = "main")
{
// Open the destination
var r = SQLite3.Open (destinationDatabasePath, out var destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, "Failed to open destination database");
}
// Init the backup
var backup = SQLite3.BackupInit (destHandle, databaseName, Handle, databaseName);
if (backup == NullBackupHandle) {
SQLite3.Close (destHandle);
throw new Exception ("Failed to create backup");
}
// Perform it
SQLite3.BackupStep (backup, -1);
SQLite3.BackupFinish (backup);
// Check for errors
r = SQLite3.GetResult (destHandle);
string msg = "";
if (r != SQLite3.Result.OK) {
msg = SQLite3.GetErrmsg (destHandle);
}
// Close everything and report errors
SQLite3.Close (destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, msg);
}
}
~SQLiteConnection ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public void Close ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
var useClose2 = LibVersionNumber >= 3007014;
if (_open && Handle != NullHandle) {
try {
if (disposing) {
lock (_insertCommandMap) {
foreach (var sqlInsertCommand in _insertCommandMap.Values) {
sqlInsertCommand.Dispose ();
}
_insertCommandMap.Clear ();
}
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
else {
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
}
}
finally {
Handle = NullHandle;
_open = false;
}
}
}
void OnTableChanged (TableMapping table, NotifyTableChangedAction action)
{
var ev = TableChanged;
if (ev != null)
ev (this, new NotifyTableChangedEventArgs (table, action));
}
public event EventHandler<NotifyTableChangedEventArgs> TableChanged;
}
public class NotifyTableChangedEventArgs : EventArgs
{
public TableMapping Table { get; private set; }
public NotifyTableChangedAction Action { get; private set; }
public NotifyTableChangedEventArgs (TableMapping table, NotifyTableChangedAction action)
{
Table = table;
Action = action;
}
}
public enum NotifyTableChangedAction
{
Insert,
Update,
Delete,
}
/// <summary>
/// Represents a parsed connection string.
/// </summary>
public class SQLiteConnectionString
{
const string DateTimeSqliteDefaultFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff";
public string UniqueKey { get; }
public string DatabasePath { get; }
public bool StoreDateTimeAsTicks { get; }
public bool StoreTimeSpanAsTicks { get; }
public string DateTimeStringFormat { get; }
public System.Globalization.DateTimeStyles DateTimeStyle { get; }
public object Key { get; }
public SQLiteOpenFlags OpenFlags { get; }
public Action<SQLiteConnection> PreKeyAction { get; }
public Action<SQLiteConnection> PostKeyAction { get; }
public string VfsName { get; }
#if NETFX_CORE
static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
public static readonly string[] InMemoryDbPaths = new[]
{
":memory:",
"file::memory:"
};
public static bool IsInMemoryPath(string databasePath)
{
return InMemoryDbPaths.Any(i => i.Equals(databasePath, StringComparison.OrdinalIgnoreCase));
}
#endif
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks = true)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks, key, preKeyAction, postKeyAction, vfsName)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
/// <param name="dateTimeStringFormat">
/// Specifies the format to use when storing DateTime properties as strings.
/// </param>
/// <param name="storeTimeSpanAsTicks">
/// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeTimeSpanAsTicks = true.
/// </param>
public SQLiteConnectionString (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true)
{
if (key != null && !((key is byte[]) || (key is string)))
throw new ArgumentException ("Encryption keys must be strings or byte arrays", nameof (key));
UniqueKey = string.Format ("{0}_{1:X8}", databasePath, (uint)openFlags);
StoreDateTimeAsTicks = storeDateTimeAsTicks;
StoreTimeSpanAsTicks = storeTimeSpanAsTicks;
DateTimeStringFormat = dateTimeStringFormat;
DateTimeStyle = "o".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None;
Key = key;
PreKeyAction = preKeyAction;
PostKeyAction = postKeyAction;
OpenFlags = openFlags;
VfsName = vfsName;
#if NETFX_CORE
DatabasePath = IsInMemoryPath(databasePath)
? databasePath
: System.IO.Path.Combine(MetroStyleDataPath, databasePath);
#else
DatabasePath = databasePath;
#endif
}
}
[AttributeUsage (AttributeTargets.Class)]
public class TableAttribute : Attribute
{
public string Name { get; set; }
/// <summary>
/// Flag whether to create the table without rowid (see https://sqlite.org/withoutrowid.html)
///
/// The default is <c>false</c> so that sqlite adds an implicit <c>rowid</c> to every table created.
/// </summary>
public bool WithoutRowId { get; set; }
public TableAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
public ColumnAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class PrimaryKeyAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class AutoIncrementAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class IndexedAttribute : Attribute
{
public string Name { get; set; }
public int Order { get; set; }
public virtual bool Unique { get; set; }
public IndexedAttribute ()
{
}
public IndexedAttribute (string name, int order)
{
Name = name;
Order = order;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class IgnoreAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class UniqueAttribute : IndexedAttribute
{
public override bool Unique {
get { return true; }
set { /* throw? */ }
}
}
[AttributeUsage (AttributeTargets.Property)]
public class MaxLengthAttribute : Attribute
{
public int Value { get; private set; }
public MaxLengthAttribute (int length)
{
Value = length;
}
}
public sealed class PreserveAttribute : System.Attribute
{
public bool AllMembers;
public bool Conditional;
}
/// <summary>
/// Select the collating sequence to use on a column.
/// "BINARY", "NOCASE", and "RTRIM" are supported.
/// "BINARY" is the default.
/// </summary>
[AttributeUsage (AttributeTargets.Property)]
public class CollationAttribute : Attribute
{
public string Value { get; private set; }
public CollationAttribute (string collation)
{
Value = collation;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class NotNullAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Enum)]
public class StoreAsTextAttribute : Attribute
{
}
public class TableMapping
{
public Type MappedType { get; private set; }
public string TableName { get; private set; }
public bool WithoutRowId { get; private set; }
public Column[] Columns { get; private set; }
public Column PK { get; private set; }
public string GetByPrimaryKeySql { get; private set; }
public CreateFlags CreateFlags { get; private set; }
internal MapMethod Method { get; private set; } = MapMethod.ByName;
readonly Column _autoPk;
readonly Column[] _insertColumns;
readonly Column[] _insertOrReplaceColumns;
public TableMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
MappedType = type;
CreateFlags = createFlags;
var typeInfo = type.GetTypeInfo ();
#if ENABLE_IL2CPP
var tableAttr = typeInfo.GetCustomAttribute<TableAttribute> ();
#else
var tableAttr =
typeInfo.CustomAttributes
.Where (x => x.AttributeType == typeof (TableAttribute))
.Select (x => (TableAttribute)Orm.InflateAttribute (x))
.FirstOrDefault ();
#endif
TableName = (tableAttr != null && !string.IsNullOrEmpty (tableAttr.Name)) ? tableAttr.Name : MappedType.Name;
WithoutRowId = tableAttr != null ? tableAttr.WithoutRowId : false;
var members = GetPublicMembers(type);
var cols = new List<Column>(members.Count);
foreach(var m in members)
{
var ignore = m.IsDefined(typeof(IgnoreAttribute), true);
if(!ignore)
cols.Add(new Column(m, createFlags));
}
Columns = cols.ToArray ();
foreach (var c in Columns) {
if (c.IsAutoInc && c.IsPK) {
_autoPk = c;
}
if (c.IsPK) {
PK = c;
}
}
HasAutoIncPK = _autoPk != null;
if (PK != null) {
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
}
else {
// People should not be calling Get/Find without a PK
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName);
}
_insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
_insertOrReplaceColumns = Columns.ToArray ();
}
private IReadOnlyCollection<MemberInfo> GetPublicMembers(Type type)
{
if(type.Name.StartsWith("ValueTuple`"))
return GetFieldsFromValueTuple(type);
var members = new List<MemberInfo>();
var memberNames = new HashSet<string>();
var newMembers = new List<MemberInfo>();
do
{
var ti = type.GetTypeInfo();
newMembers.Clear();
newMembers.AddRange(
from p in ti.DeclaredProperties
where !memberNames.Contains(p.Name) &&
p.CanRead && p.CanWrite &&
p.GetMethod != null && p.SetMethod != null &&
p.GetMethod.IsPublic && p.SetMethod.IsPublic &&
!p.GetMethod.IsStatic && !p.SetMethod.IsStatic
select p);
members.AddRange(newMembers);
foreach(var m in newMembers)
memberNames.Add(m.Name);
type = ti.BaseType;
}
while(type != typeof(object));
return members;
}
private IReadOnlyCollection<MemberInfo> GetFieldsFromValueTuple(Type type)
{
Method = MapMethod.ByPosition;
var fields = type.GetFields();
// https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest
if(fields.Length >= 8)
throw new NotSupportedException("ValueTuple with more than 7 members not supported due to nesting; see https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest");
return fields;
}
public bool HasAutoIncPK { get; private set; }
public void SetAutoIncPK (object obj, long id)
{
if (_autoPk != null) {
_autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null));
}
}
public Column[] InsertColumns {
get {
return _insertColumns;
}
}
public Column[] InsertOrReplaceColumns {
get {
return _insertOrReplaceColumns;
}
}
public Column FindColumnWithPropertyName (string propertyName)
{
var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName);
return exact;
}
public Column FindColumn (string columnName)
{
if(Method != MapMethod.ByName)
throw new InvalidOperationException($"This {nameof(TableMapping)} is not mapped by name, but {Method}.");
var exact = Columns.FirstOrDefault (c => c.Name.ToLower () == columnName.ToLower ());
return exact;
}
public class Column
{
MemberInfo _member;
public string Name { get; private set; }
public PropertyInfo PropertyInfo => _member as PropertyInfo;
public string PropertyName { get { return _member.Name; } }
public Type ColumnType { get; private set; }
public string Collation { get; private set; }
public bool IsAutoInc { get; private set; }
public bool IsAutoGuid { get; private set; }
public bool IsPK { get; private set; }
public IEnumerable<IndexedAttribute> Indices { get; set; }
public bool IsNullable { get; private set; }
public int? MaxStringLength { get; private set; }
public bool StoreAsText { get; private set; }
public Column (MemberInfo member, CreateFlags createFlags = CreateFlags.None)
{
_member = member;
var memberType = GetMemberType(member);
var colAttr = member.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (ColumnAttribute));
#if ENABLE_IL2CPP
var ca = member.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
Name = ca == null ? member.Name : ca.Name;
#else
Name = (colAttr != null && colAttr.ConstructorArguments.Count > 0) ?
colAttr.ConstructorArguments[0].Value?.ToString () :
member.Name;
#endif
//If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
ColumnType = Nullable.GetUnderlyingType (memberType) ?? memberType;
Collation = Orm.Collation (member);
IsPK = Orm.IsPK (member) ||
(((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
string.Compare (member.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);
var isAuto = Orm.IsAutoInc (member) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
IsAutoGuid = isAuto && ColumnType == typeof (Guid);
IsAutoInc = isAuto && !IsAutoGuid;
Indices = Orm.GetIndices (member);
if (!Indices.Any ()
&& !IsPK
&& ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
&& Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
) {
Indices = new IndexedAttribute[] { new IndexedAttribute () };
}
IsNullable = !(IsPK || Orm.IsMarkedNotNull (member));
MaxStringLength = Orm.MaxStringLength (member);
StoreAsText = memberType.GetTypeInfo ().CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
}
public Column (PropertyInfo member, CreateFlags createFlags = CreateFlags.None)
: this((MemberInfo)member, createFlags)
{ }
public void SetValue (object obj, object val)
{
if(_member is PropertyInfo propy)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
propy.SetValue (obj, Enum.ToObject (ColumnType, val));
else
propy.SetValue (obj, val);
}
else if(_member is FieldInfo field)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
field.SetValue (obj, Enum.ToObject (ColumnType, val));
else
field.SetValue (obj, val);
}
else
throw new InvalidProgramException("unreachable condition");
}
public object GetValue (object obj)
{
if(_member is PropertyInfo propy)
return propy.GetValue(obj);
else if(_member is FieldInfo field)
return field.GetValue(obj);
else
throw new InvalidProgramException("unreachable condition");
}
private static Type GetMemberType(MemberInfo m)
{
switch(m.MemberType)
{
case MemberTypes.Property: return ((PropertyInfo)m).PropertyType;
case MemberTypes.Field: return ((FieldInfo)m).FieldType;
default: throw new InvalidProgramException($"{nameof(TableMapping)} supports properties or fields only.");
}
}
}
internal enum MapMethod
{
ByName,
ByPosition
}
}
class EnumCacheInfo
{
public EnumCacheInfo (Type type)
{
var typeInfo = type.GetTypeInfo ();
IsEnum = typeInfo.IsEnum;
if (IsEnum) {
StoreAsText = typeInfo.CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
if (StoreAsText) {
EnumValues = new Dictionary<int, string> ();
foreach (object e in Enum.GetValues (type)) {
EnumValues[Convert.ToInt32 (e)] = e.ToString ();
}
}
}
}
public bool IsEnum { get; private set; }
public bool StoreAsText { get; private set; }
public Dictionary<int, string> EnumValues { get; private set; }
}
static class EnumCache
{
static readonly Dictionary<Type, EnumCacheInfo> Cache = new Dictionary<Type, EnumCacheInfo> ();
public static EnumCacheInfo GetInfo<T> ()
{
return GetInfo (typeof (T));
}
public static EnumCacheInfo GetInfo (Type type)
{
lock (Cache) {
EnumCacheInfo info = null;
if (!Cache.TryGetValue (type, out info)) {
info = new EnumCacheInfo (type);
Cache[type] = info;
}
return info;
}
}
}
public static class Orm
{
public const int DefaultMaxStringLength = 140;
public const string ImplicitPkName = "Id";
public const string ImplicitIndexSuffix = "Id";
public static Type GetType (object obj)
{
if (obj == null)
return typeof (object);
var rt = obj as IReflectableType;
if (rt != null)
return rt.GetTypeInfo ().AsType ();
return obj.GetType ();
}
public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks, storeTimeSpanAsTicks) + " ";
if (p.IsPK) {
decl += "primary key ";
}
if (p.IsAutoInc) {
decl += "autoincrement ";
}
if (!p.IsNullable) {
decl += "not null ";
}
if (!string.IsNullOrEmpty (p.Collation)) {
decl += "collate " + p.Collation + " ";
}
return decl;
}
public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
var clrType = p.ColumnType;
if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32) || clrType == typeof (UInt32) || clrType == typeof (Int64)) {
return "integer";
}
else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) {
return "float";
}
else if (clrType == typeof (String) || clrType == typeof (StringBuilder) || clrType == typeof (Uri) || clrType == typeof (UriBuilder)) {
int? len = p.MaxStringLength;
if (len.HasValue)
return "varchar(" + len.Value + ")";
return "varchar";
}
else if (clrType == typeof (TimeSpan)) {
return storeTimeSpanAsTicks ? "bigint" : "time";
}
else if (clrType == typeof (DateTime)) {
return storeDateTimeAsTicks ? "bigint" : "datetime";
}
else if (clrType == typeof (DateTimeOffset)) {
return "bigint";
}
else if (clrType.GetTypeInfo ().IsEnum) {
if (p.StoreAsText)
return "varchar";
else
return "integer";
}
else if (clrType == typeof (byte[])) {
return "blob";
}
else if (clrType == typeof (Guid)) {
return "varchar(36)";
}
else {
throw new NotSupportedException ("Don't know about " + clrType);
}
}
public static bool IsPK (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
}
public static string Collation (MemberInfo p)
{
#if ENABLE_IL2CPP
return (p.GetCustomAttribute<CollationAttribute> ()?.Value) ?? "";
#else
return
(p.CustomAttributes
.Where (x => typeof (CollationAttribute) == x.AttributeType)
.Select (x => {
var args = x.ConstructorArguments;
return args.Count > 0 ? ((args[0].Value as string) ?? "") : "";
})
.FirstOrDefault ()) ?? "";
#endif
}
public static bool IsAutoInc (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (AutoIncrementAttribute));
}
public static FieldInfo GetField (TypeInfo t, string name)
{
var f = t.GetDeclaredField (name);
if (f != null)
return f;
return GetField (t.BaseType.GetTypeInfo (), name);
}
public static PropertyInfo GetProperty (TypeInfo t, string name)
{
var f = t.GetDeclaredProperty (name);
if (f != null)
return f;
return GetProperty (t.BaseType.GetTypeInfo (), name);
}
public static object InflateAttribute (CustomAttributeData x)
{
var atype = x.AttributeType;
var typeInfo = atype.GetTypeInfo ();
#if ENABLE_IL2CPP
var r = Activator.CreateInstance (x.AttributeType);
#else
var args = x.ConstructorArguments.Select (a => a.Value).ToArray ();
var r = Activator.CreateInstance (x.AttributeType, args);
foreach (var arg in x.NamedArguments) {
if (arg.IsField) {
GetField (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
else {
GetProperty (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
}
#endif
return r;
}
public static IEnumerable<IndexedAttribute> GetIndices (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttributes<IndexedAttribute> ();
#else
var indexedInfo = typeof (IndexedAttribute).GetTypeInfo ();
return
p.CustomAttributes
.Where (x => indexedInfo.IsAssignableFrom (x.AttributeType.GetTypeInfo ()))
.Select (x => (IndexedAttribute)InflateAttribute (x));
#endif
}
public static int? MaxStringLength (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttribute<MaxLengthAttribute> ()?.Value;
#else
var attr = p.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (MaxLengthAttribute));
if (attr != null) {
var attrv = (MaxLengthAttribute)InflateAttribute (attr);
return attrv.Value;
}
return null;
#endif
}
public static int? MaxStringLength (PropertyInfo p) => MaxStringLength((MemberInfo)p);
public static bool IsMarkedNotNull (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (NotNullAttribute));
}
}
public partial class SQLiteCommand
{
SQLiteConnection _conn;
private List<Binding> _bindings;
public string CommandText { get; set; }
public SQLiteCommand (SQLiteConnection conn)
{
_conn = conn;
_bindings = new List<Binding> ();
CommandText = "";
}
public int ExecuteNonQuery ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing: " + this);
}
var r = SQLite3.Result.OK;
var stmt = Prepare ();
r = SQLite3.Step (stmt);
Finalize (stmt);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (_conn.Handle);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (_conn.Handle);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint) {
if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
public IEnumerable<T> ExecuteDeferredQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T)));
}
public List<T> ExecuteQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T))).ToList ();
}
public List<T> ExecuteQuery<T> (TableMapping map)
{
return ExecuteDeferredQuery<T> (map).ToList ();
}
/// <summary>
/// Invoked every time an instance is loaded from the database.
/// </summary>
/// <param name='obj'>
/// The newly created object.
/// </param>
/// <remarks>
/// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/>
/// method to hook into the life-cycle of objects.
/// </remarks>
protected virtual void OnInstanceCreated (object obj)
{
// Can be overridden.
}
public IEnumerable<T> ExecuteDeferredQuery<T> (TableMapping map)
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)];
var fastColumnSetters = new Action<object, Sqlite3Statement, int>[SQLite3.ColumnCount (stmt)];
if (map.Method == TableMapping.MapMethod.ByPosition)
{
Array.Copy(map.Columns, cols, Math.Min(cols.Length, map.Columns.Length));
}
else if (map.Method == TableMapping.MapMethod.ByName) {
MethodInfo getSetter = null;
if (typeof(T) != map.MappedType) {
getSetter = typeof(FastColumnSetter)
.GetMethod (nameof(FastColumnSetter.GetFastSetter),
BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (map.MappedType);
}
for (int i = 0; i < cols.Length; i++) {
var name = SQLite3.ColumnName16 (stmt, i);
cols[i] = map.FindColumn (name);
if (cols[i] != null)
if (getSetter != null) {
fastColumnSetters[i] = (Action<object, Sqlite3Statement, int>)getSetter.Invoke(null, new object[]{ _conn, cols[i]});
}
else {
fastColumnSetters[i] = FastColumnSetter.GetFastSetter<T>(_conn, cols[i]);
}
}
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var obj = Activator.CreateInstance (map.MappedType);
for (int i = 0; i < cols.Length; i++) {
if (cols[i] == null)
continue;
if (fastColumnSetters[i] != null) {
fastColumnSetters[i].Invoke (obj, stmt, i);
}
else {
var colType = SQLite3.ColumnType (stmt, i);
var val = ReadCol (stmt, i, colType, cols[i].ColumnType);
cols[i].SetValue (obj, val);
}
}
OnInstanceCreated (obj);
yield return (T)obj;
}
}
finally {
SQLite3.Finalize (stmt);
}
}
public T ExecuteScalar<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
T val = default (T);
var stmt = Prepare ();
try {
var r = SQLite3.Step (stmt);
if (r == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var colval = ReadCol (stmt, 0, colType, typeof (T));
if (colval != null) {
val = (T)colval;
}
}
else if (r == SQLite3.Result.Done) {
}
else {
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
finally {
Finalize (stmt);
}
return val;
}
public IEnumerable<T> ExecuteQueryScalars<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
if (SQLite3.ColumnCount (stmt) < 1) {
throw new InvalidOperationException ("QueryScalars should return at least one column");
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var val = ReadCol (stmt, 0, colType, typeof (T));
if (val == null) {
yield return default (T);
}
else {
yield return (T)val;
}
}
}
finally {
Finalize (stmt);
}
}
public void Bind (string name, object val)
{
_bindings.Add (new Binding {
Name = name,
Value = val
});
}
public void Bind (object val)
{
Bind (null, val);
}
public override string ToString ()
{
var parts = new string[1 + _bindings.Count];
parts[0] = CommandText;
var i = 1;
foreach (var b in _bindings) {
parts[i] = string.Format (" {0}: {1}", i - 1, b.Value);
i++;
}
return string.Join (Environment.NewLine, parts);
}
Sqlite3Statement Prepare ()
{
var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
BindAll (stmt);
return stmt;
}
void Finalize (Sqlite3Statement stmt)
{
SQLite3.Finalize (stmt);
}
void BindAll (Sqlite3Statement stmt)
{
int nextIdx = 1;
foreach (var b in _bindings) {
if (b.Name != null) {
b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
}
else {
b.Index = nextIdx++;
}
BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.DateTimeStringFormat, _conn.StoreTimeSpanAsTicks);
}
}
static IntPtr NegativePointer = new IntPtr (-1);
internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks, string dateTimeStringFormat, bool storeTimeSpanAsTicks)
{
if (value == null) {
SQLite3.BindNull (stmt, index);
}
else {
if (value is Int32) {
SQLite3.BindInt (stmt, index, (int)value);
}
else if (value is String) {
SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer);
}
else if (value is Byte || value is UInt16 || value is SByte || value is Int16) {
SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
}
else if (value is Boolean) {
SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0);
}
else if (value is UInt32 || value is Int64) {
SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value));
}
else if (value is Single || value is Double || value is Decimal) {
SQLite3.BindDouble (stmt, index, Convert.ToDouble (value));
}
else if (value is TimeSpan) {
if (storeTimeSpanAsTicks) {
SQLite3.BindInt64 (stmt, index, ((TimeSpan)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((TimeSpan)value).ToString (), -1, NegativePointer);
}
}
else if (value is DateTime) {
if (storeDateTimeAsTicks) {
SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((DateTime)value).ToString (dateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture), -1, NegativePointer);
}
}
else if (value is DateTimeOffset) {
SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks);
}
else if (value is byte[]) {
SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer);
}
else if (value is Guid) {
SQLite3.BindText (stmt, index, ((Guid)value).ToString (), 72, NegativePointer);
}
else if (value is Uri) {
SQLite3.BindText (stmt, index, ((Uri)value).ToString (), -1, NegativePointer);
}
else if (value is StringBuilder) {
SQLite3.BindText (stmt, index, ((StringBuilder)value).ToString (), -1, NegativePointer);
}
else if (value is UriBuilder) {
SQLite3.BindText (stmt, index, ((UriBuilder)value).ToString (), -1, NegativePointer);
}
else {
// Now we could possibly get an enum, retrieve cached info
var valueType = value.GetType ();
var enumInfo = EnumCache.GetInfo (valueType);
if (enumInfo.IsEnum) {
var enumIntValue = Convert.ToInt32 (value);
if (enumInfo.StoreAsText)
SQLite3.BindText (stmt, index, enumInfo.EnumValues[enumIntValue], -1, NegativePointer);
else
SQLite3.BindInt (stmt, index, enumIntValue);
}
else {
throw new NotSupportedException ("Cannot store type: " + Orm.GetType (value));
}
}
}
}
class Binding
{
public string Name { get; set; }
public object Value { get; set; }
public int Index { get; set; }
}
object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType)
{
if (type == SQLite3.ColType.Null) {
return null;
}
else {
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
return SQLite3.ColumnString (stmt, index);
}
else if (clrType == typeof (Int32)) {
return (int)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Boolean)) {
return SQLite3.ColumnInt (stmt, index) == 1;
}
else if (clrType == typeof (double)) {
return SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (float)) {
return (float)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (TimeSpan)) {
if (_conn.StoreTimeSpanAsTicks) {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
}
}
else if (clrType == typeof (DateTime)) {
if (_conn.StoreDateTimeAsTicks) {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, _conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, _conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
}
}
else if (clrType == typeof (DateTimeOffset)) {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
}
else if (clrTypeInfo.IsEnum) {
if (type == SQLite3.ColType.Text) {
var value = SQLite3.ColumnString (stmt, index);
return Enum.Parse (clrType, value.ToString (), true);
}
else
return SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int64)) {
return SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (UInt32)) {
return (uint)SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (decimal)) {
return (decimal)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (Byte)) {
return (byte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (UInt16)) {
return (ushort)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int16)) {
return (short)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (sbyte)) {
return (sbyte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (byte[])) {
return SQLite3.ColumnByteArray (stmt, index);
}
else if (clrType == typeof (Guid)) {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
}
else if (clrType == typeof (Uri)) {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
}
else if (clrType == typeof (StringBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
}
else if (clrType == typeof (UriBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
}
else {
throw new NotSupportedException ("Don't know how to read " + clrType);
}
}
}
}
internal class FastColumnSetter
{
/// <summary>
/// Creates a delegate that can be used to quickly set object members from query columns.
///
/// Note that this frontloads the slow reflection-based type checking for columns to only happen once at the beginning of a query,
/// and then afterwards each row of the query can invoke the delegate returned by this function to get much better performance (up to 10x speed boost, depending on query size and platform).
/// </summary>
/// <typeparam name="T">The type of the destination object that the query will read into</typeparam>
/// <param name="conn">The active connection. Note that this is primarily needed in order to read preferences regarding how certain data types (such as TimeSpan / DateTime) should be encoded in the database.</param>
/// <param name="column">The table mapping used to map the statement column to a member of the destination object type</param>
/// <returns>
/// A delegate for fast-setting of object members from statement columns.
///
/// If no fast setter is available for the requested column (enums in particular cause headache), then this function returns null.
/// </returns>
internal static Action<object, Sqlite3Statement, int> GetFastSetter<T> (SQLiteConnection conn, TableMapping.Column column)
{
Action<object, Sqlite3Statement, int> fastSetter = null;
Type clrType = column.PropertyInfo.PropertyType;
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
fastSetter = CreateTypedSetterDelegate<T, string> (column, (stmt, index) => {
return SQLite3.ColumnString (stmt, index);
});
}
else if (clrType == typeof (Int32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, int> (column, (stmt, index)=>{
return SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Boolean)) {
fastSetter = CreateNullableTypedSetterDelegate<T, bool> (column, (stmt, index) => {
return SQLite3.ColumnInt (stmt, index) == 1;
});
}
else if (clrType == typeof (double)) {
fastSetter = CreateNullableTypedSetterDelegate<T, double> (column, (stmt, index) => {
return SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (float)) {
fastSetter = CreateNullableTypedSetterDelegate<T, float> (column, (stmt, index) => {
return (float) SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (TimeSpan)) {
if (conn.StoreTimeSpanAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
});
}
}
else if (clrType == typeof (DateTime)) {
if (conn.StoreDateTimeAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
});
}
}
else if (clrType == typeof (DateTimeOffset)) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTimeOffset> (column, (stmt, index) => {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
});
}
else if (clrTypeInfo.IsEnum) {
// NOTE: Not sure of a good way (if any?) to do a strongly-typed fast setter like this for enumerated types -- for now, return null and column sets will revert back to the safe (but slow) Reflection-based method of column prop.Set()
}
else if (clrType == typeof (Int64)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int64> (column, (stmt, index) => {
return SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (UInt32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt32> (column, (stmt, index) => {
return (uint)SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (decimal)) {
fastSetter = CreateNullableTypedSetterDelegate<T, decimal> (column, (stmt, index) => {
return (decimal)SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (Byte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Byte> (column, (stmt, index) => {
return (byte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (UInt16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt16> (column, (stmt, index) => {
return (ushort)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Int16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int16> (column, (stmt, index) => {
return (short)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (sbyte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, sbyte> (column, (stmt, index) => {
return (sbyte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (byte[])) {
fastSetter = CreateTypedSetterDelegate<T, byte[]> (column, (stmt, index) => {
return SQLite3.ColumnByteArray (stmt, index);
});
}
else if (clrType == typeof (Guid)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Guid> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
});
}
else if (clrType == typeof (Uri)) {
fastSetter = CreateTypedSetterDelegate<T, Uri> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
});
}
else if (clrType == typeof (StringBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, StringBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
});
}
else if (clrType == typeof (UriBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, UriBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
});
}
else {
// NOTE: Will fall back to the slow setter method in the event that we are unable to create a fast setter delegate for a particular column type
}
return fastSetter;
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
///
/// Note that this is identical to CreateTypedSetterDelegate(), but has an extra check to see if it should create a nullable version of the delegate.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateNullableTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue) where ColumnMemberType : struct
{
var clrTypeInfo = column.PropertyInfo.PropertyType.GetTypeInfo();
bool isNullable = false;
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
isNullable = true;
}
if (isNullable) {
var setProperty = (Action<ObjectType, ColumnMemberType?>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType?>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
return CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (column, getColumnValue);
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue)
{
var setProperty = (Action<ObjectType, ColumnMemberType>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
}
/// <summary>
/// Since the insert never changed, we only need to prepare once.
/// </summary>
class PreparedSqlLiteInsertCommand : IDisposable
{
bool Initialized;
SQLiteConnection Connection;
string CommandText;
Sqlite3Statement Statement;
static readonly Sqlite3Statement NullStatement = default (Sqlite3Statement);
public PreparedSqlLiteInsertCommand (SQLiteConnection conn, string commandText)
{
Connection = conn;
CommandText = commandText;
}
public int ExecuteNonQuery (object[] source)
{
if (Initialized && Statement == NullStatement) {
throw new ObjectDisposedException (nameof (PreparedSqlLiteInsertCommand));
}
if (Connection.Trace) {
Connection.Tracer?.Invoke ("Executing: " + CommandText);
}
var r = SQLite3.Result.OK;
if (!Initialized) {
Statement = SQLite3.Prepare2 (Connection.Handle, CommandText);
Initialized = true;
}
//bind the values.
if (source != null) {
for (int i = 0; i < source.Length; i++) {
SQLiteCommand.BindParameter (Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks, Connection.DateTimeStringFormat, Connection.StoreTimeSpanAsTicks);
}
}
r = SQLite3.Step (Statement);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (Connection.Handle);
SQLite3.Reset (Statement);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (Connection.Handle);
SQLite3.Reset (Statement);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
SQLite3.Reset (Statement);
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
else {
SQLite3.Reset (Statement);
throw SQLiteException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
void Dispose (bool disposing)
{
var s = Statement;
Statement = NullStatement;
Connection = null;
if (s != NullStatement) {
SQLite3.Finalize (s);
}
}
~PreparedSqlLiteInsertCommand ()
{
Dispose (false);
}
}
public enum CreateTableResult
{
Created,
Migrated,
}
public class CreateTablesResult
{
public Dictionary<Type, CreateTableResult> Results { get; private set; }
public CreateTablesResult ()
{
Results = new Dictionary<Type, CreateTableResult> ();
}
}
public abstract class BaseTableQuery
{
protected class Ordering
{
public string ColumnName { get; set; }
public bool Ascending { get; set; }
}
}
public class TableQuery<T> : BaseTableQuery, IEnumerable<T>
{
public SQLiteConnection Connection { get; private set; }
public TableMapping Table { get; private set; }
Expression _where;
List<Ordering> _orderBys;
int? _limit;
int? _offset;
BaseTableQuery _joinInner;
Expression _joinInnerKeySelector;
BaseTableQuery _joinOuter;
Expression _joinOuterKeySelector;
Expression _joinSelector;
Expression _selector;
TableQuery (SQLiteConnection conn, TableMapping table)
{
Connection = conn;
Table = table;
}
public TableQuery (SQLiteConnection conn)
{
Connection = conn;
Table = Connection.GetMapping (typeof (T));
}
public TableQuery<U> Clone<U> ()
{
var q = new TableQuery<U> (Connection, Table);
q._where = _where;
q._deferred = _deferred;
if (_orderBys != null) {
q._orderBys = new List<Ordering> (_orderBys);
}
q._limit = _limit;
q._offset = _offset;
q._joinInner = _joinInner;
q._joinInnerKeySelector = _joinInnerKeySelector;
q._joinOuter = _joinOuter;
q._joinOuterKeySelector = _joinOuterKeySelector;
q._joinSelector = _joinSelector;
q._selector = _selector;
return q;
}
/// <summary>
/// Filters the query based on a predicate.
/// </summary>
public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
if (predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
var pred = lambda.Body;
var q = Clone<T> ();
q.AddWhere (pred);
return q;
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
/// <summary>
/// Delete all the rows that match this query.
/// </summary>
public int Delete ()
{
return Delete (null);
}
/// <summary>
/// Delete all the rows that match this query and the given predicate.
/// </summary>
public int Delete (Expression<Func<T, bool>> predExpr)
{
if (_limit.HasValue || _offset.HasValue)
throw new InvalidOperationException ("Cannot delete with limits or offsets");
if (_where == null && predExpr == null)
throw new InvalidOperationException ("No condition specified");
var pred = _where;
if (predExpr != null && predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
pred = pred != null ? Expression.AndAlso (pred, lambda.Body) : lambda.Body;
}
var args = new List<object> ();
var cmdText = "delete from \"" + Table.TableName + "\"";
var w = CompileExpr (pred, args);
cmdText += " where " + w.CommandText;
var command = Connection.CreateCommand (cmdText, args.ToArray ());
int result = command.ExecuteNonQuery ();
return result;
}
/// <summary>
/// Yields a given number of elements from the query and then skips the remainder.
/// </summary>
public TableQuery<T> Take (int n)
{
var q = Clone<T> ();
q._limit = n;
return q;
}
/// <summary>
/// Skips a given number of elements from the query and then yields the remainder.
/// </summary>
public TableQuery<T> Skip (int n)
{
var q = Clone<T> ();
q._offset = n;
return q;
}
/// <summary>
/// Returns the element at a given index
/// </summary>
public T ElementAt (int index)
{
return Skip (index).Take (1).First ();
}
bool _deferred;
public TableQuery<T> Deferred ()
{
var q = Clone<T> ();
q._deferred = true;
return q;
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc)
{
if (orderExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)orderExpr;
MemberExpression mem = null;
var unary = lambda.Body as UnaryExpression;
if (unary != null && unary.NodeType == ExpressionType.Convert) {
mem = unary.Operand as MemberExpression;
}
else {
mem = lambda.Body as MemberExpression;
}
if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) {
var q = Clone<T> ();
if (q._orderBys == null) {
q._orderBys = new List<Ordering> ();
}
q._orderBys.Add (new Ordering {
ColumnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name,
Ascending = asc
});
return q;
}
else {
throw new NotSupportedException ("Order By does not support: " + orderExpr);
}
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
private void AddWhere (Expression pred)
{
if (_where == null) {
_where = pred;
}
else {
_where = Expression.AndAlso (_where, pred);
}
}
///// <summary>
///// Performs an inner join of two queries based on matching keys extracted from the elements.
///// </summary>
//public TableQuery<TResult> Join<TInner, TKey, TResult> (
// TableQuery<TInner> inner,
// Expression<Func<T, TKey>> outerKeySelector,
// Expression<Func<TInner, TKey>> innerKeySelector,
// Expression<Func<T, TInner, TResult>> resultSelector)
//{
// var q = new TableQuery<TResult> (Connection, Connection.GetMapping (typeof (TResult))) {
// _joinOuter = this,
// _joinOuterKeySelector = outerKeySelector,
// _joinInner = inner,
// _joinInnerKeySelector = innerKeySelector,
// _joinSelector = resultSelector,
// };
// return q;
//}
// Not needed until Joins are supported
// Keeping this commented out forces the default Linq to objects processor to run
//public TableQuery<TResult> Select<TResult> (Expression<Func<T, TResult>> selector)
//{
// var q = Clone<TResult> ();
// q._selector = selector;
// return q;
//}
private SQLiteCommand GenerateCommand (string selectionList)
{
if (_joinInner != null && _joinOuter != null) {
throw new NotSupportedException ("Joins are not supported.");
}
else {
var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\"";
var args = new List<object> ();
if (_where != null) {
var w = CompileExpr (_where, args);
cmdText += " where " + w.CommandText;
}
if ((_orderBys != null) && (_orderBys.Count > 0)) {
var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ());
cmdText += " order by " + t;
}
if (_limit.HasValue) {
cmdText += " limit " + _limit.Value;
}
if (_offset.HasValue) {
if (!_limit.HasValue) {
cmdText += " limit -1 ";
}
cmdText += " offset " + _offset.Value;
}
return Connection.CreateCommand (cmdText, args.ToArray ());
}
}
class CompileResult
{
public string CommandText { get; set; }
public object Value { get; set; }
}
private CompileResult CompileExpr (Expression expr, List<object> queryArgs)
{
if (expr == null) {
throw new NotSupportedException ("Expression is NULL");
}
else if (expr is BinaryExpression) {
var bin = (BinaryExpression)expr;
// VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it
// http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx
if (bin.Left.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)bin.Left;
if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators"
&& call.Method.Name == "CompareString")
bin = Expression.MakeBinary (bin.NodeType, call.Arguments[0], call.Arguments[1]);
}
var leftr = CompileExpr (bin.Left, queryArgs);
var rightr = CompileExpr (bin.Right, queryArgs);
//If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
string text;
if (leftr.CommandText == "?" && leftr.Value == null)
text = CompileNullBinaryExpression (bin, rightr);
else if (rightr.CommandText == "?" && rightr.Value == null)
text = CompileNullBinaryExpression (bin, leftr);
else
text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")";
return new CompileResult { CommandText = text };
}
else if (expr.NodeType == ExpressionType.Not) {
var operandExpr = ((UnaryExpression)expr).Operand;
var opr = CompileExpr (operandExpr, queryArgs);
object val = opr.Value;
if (val is bool)
val = !((bool)val);
return new CompileResult {
CommandText = "NOT(" + opr.CommandText + ")",
Value = val
};
}
else if (expr.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)expr;
var args = new CompileResult[call.Arguments.Count];
var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null;
for (var i = 0; i < args.Length; i++) {
args[i] = CompileExpr (call.Arguments[i], queryArgs);
}
var sqlCall = "";
if (call.Method.Name == "Like" && args.Length == 2) {
sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 2) {
sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 1) {
if (call.Object != null && call.Object.Type == typeof (string)) {
sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )";
}
else {
sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
}
}
else if (call.Method.Name == "StartsWith" && args.Length >= 1) {
var startsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
startsWithCmpOp = (StringComparison)args[1].Value;
}
switch (startsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
break;
}
}
else if (call.Method.Name == "EndsWith" && args.Length >= 1) {
var endsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
endsWithCmpOp = (StringComparison)args[1].Value;
}
switch (endsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString ().Length + "+1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
break;
}
}
else if (call.Method.Name == "Equals" && args.Length == 1) {
sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
}
else if (call.Method.Name == "ToLower") {
sqlCall = "(lower(" + obj.CommandText + "))";
}
else if (call.Method.Name == "ToUpper") {
sqlCall = "(upper(" + obj.CommandText + "))";
}
else if (call.Method.Name == "Replace" && args.Length == 2) {
sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))";
}
else if (call.Method.Name == "IsNullOrEmpty" && args.Length == 1) {
sqlCall = "(" + args[0].CommandText + " is null or" + args[0].CommandText + " ='' )";
}
else {
sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")";
}
return new CompileResult { CommandText = sqlCall };
}
else if (expr.NodeType == ExpressionType.Constant) {
var c = (ConstantExpression)expr;
queryArgs.Add (c.Value);
return new CompileResult {
CommandText = "?",
Value = c.Value
};
}
else if (expr.NodeType == ExpressionType.Convert) {
var u = (UnaryExpression)expr;
var ty = u.Type;
var valr = CompileExpr (u.Operand, queryArgs);
return new CompileResult {
CommandText = valr.CommandText,
Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null
};
}
else if (expr.NodeType == ExpressionType.MemberAccess) {
var mem = (MemberExpression)expr;
var paramExpr = mem.Expression as ParameterExpression;
if (paramExpr == null) {
var convert = mem.Expression as UnaryExpression;
if (convert != null && convert.NodeType == ExpressionType.Convert) {
paramExpr = convert.Operand as ParameterExpression;
}
}
if (paramExpr != null) {
//
// This is a column of our table, output just the column name
// Need to translate it if that column name is mapped
//
var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name;
return new CompileResult { CommandText = "\"" + columnName + "\"" };
}
else {
object obj = null;
if (mem.Expression != null) {
var r = CompileExpr (mem.Expression, queryArgs);
if (r.Value == null) {
throw new NotSupportedException ("Member access failed to compile expression");
}
if (r.CommandText == "?") {
queryArgs.RemoveAt (queryArgs.Count - 1);
}
obj = r.Value;
}
//
// Get the member value
//
object val = null;
if (mem.Member is PropertyInfo) {
var m = (PropertyInfo)mem.Member;
val = m.GetValue (obj, null);
}
else if (mem.Member is FieldInfo) {
var m = (FieldInfo)mem.Member;
val = m.GetValue (obj);
}
else {
throw new NotSupportedException ("MemberExpr: " + mem.Member.GetType ());
}
//
// Work special magic for enumerables
//
if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) {
var sb = new System.Text.StringBuilder ();
sb.Append ("(");
var head = "";
foreach (var a in (System.Collections.IEnumerable)val) {
queryArgs.Add (a);
sb.Append (head);
sb.Append ("?");
head = ",";
}
sb.Append (")");
return new CompileResult {
CommandText = sb.ToString (),
Value = val
};
}
else {
queryArgs.Add (val);
return new CompileResult {
CommandText = "?",
Value = val
};
}
}
}
throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ());
}
static object ConvertTo (object obj, Type t)
{
Type nut = Nullable.GetUnderlyingType (t);
if (nut != null) {
if (obj == null)
return null;
return Convert.ChangeType (obj, nut);
}
else {
return Convert.ChangeType (obj, t);
}
}
/// <summary>
/// Compiles a BinaryExpression where one of the parameters is null.
/// </summary>
/// <param name="expression">The expression to compile</param>
/// <param name="parameter">The non-null parameter</param>
private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter)
{
if (expression.NodeType == ExpressionType.Equal)
return "(" + parameter.CommandText + " is ?)";
else if (expression.NodeType == ExpressionType.NotEqual)
return "(" + parameter.CommandText + " is not ?)";
else if (expression.NodeType == ExpressionType.GreaterThan
|| expression.NodeType == ExpressionType.GreaterThanOrEqual
|| expression.NodeType == ExpressionType.LessThan
|| expression.NodeType == ExpressionType.LessThanOrEqual)
return "(" + parameter.CommandText + " < ?)"; // always false
else
throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ());
}
string GetSqlName (Expression expr)
{
var n = expr.NodeType;
if (n == ExpressionType.GreaterThan)
return ">";
else if (n == ExpressionType.GreaterThanOrEqual) {
return ">=";
}
else if (n == ExpressionType.LessThan) {
return "<";
}
else if (n == ExpressionType.LessThanOrEqual) {
return "<=";
}
else if (n == ExpressionType.And) {
return "&";
}
else if (n == ExpressionType.AndAlso) {
return "and";
}
else if (n == ExpressionType.Or) {
return "|";
}
else if (n == ExpressionType.OrElse) {
return "or";
}
else if (n == ExpressionType.Equal) {
return "=";
}
else if (n == ExpressionType.NotEqual) {
return "!=";
}
else {
throw new NotSupportedException ("Cannot get SQL for: " + n);
}
}
/// <summary>
/// Execute SELECT COUNT(*) on the query
/// </summary>
public int Count ()
{
return GenerateCommand ("count(*)").ExecuteScalar<int> ();
}
/// <summary>
/// Execute SELECT COUNT(*) on the query with an additional WHERE clause.
/// </summary>
public int Count (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).Count ();
}
public IEnumerator<T> GetEnumerator ()
{
if (!_deferred)
return GenerateCommand ("*").ExecuteQuery<T> ().GetEnumerator ();
return GenerateCommand ("*").ExecuteDeferredQuery<T> ().GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
/// <summary>
/// Queries the database and returns the results as a List.
/// </summary>
public List<T> ToList ()
{
return GenerateCommand ("*").ExecuteQuery<T> ();
}
/// <summary>
/// Queries the database and returns the results as an array.
/// </summary>
public T[] ToArray ()
{
return GenerateCommand ("*").ExecuteQuery<T> ().ToArray ();
}
/// <summary>
/// Returns the first element of this query.
/// </summary>
public T First ()
{
var query = Take (1);
return query.ToList ().First ();
}
/// <summary>
/// Returns the first element of this query, or null if no element is found.
/// </summary>
public T FirstOrDefault ()
{
var query = Take (1);
return query.ToList ().FirstOrDefault ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate.
/// </summary>
public T First (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).First ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate, or null
/// if no element is found.
/// </summary>
public T FirstOrDefault (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).FirstOrDefault ();
}
}
public static class SQLite3
{
public enum Result : int
{
OK = 0,
Error = 1,
Internal = 2,
Perm = 3,
Abort = 4,
Busy = 5,
Locked = 6,
NoMem = 7,
ReadOnly = 8,
Interrupt = 9,
IOError = 10,
Corrupt = 11,
NotFound = 12,
Full = 13,
CannotOpen = 14,
LockErr = 15,
Empty = 16,
SchemaChngd = 17,
TooBig = 18,
Constraint = 19,
Mismatch = 20,
Misuse = 21,
NotImplementedLFS = 22,
AccessDenied = 23,
Format = 24,
Range = 25,
NonDBFile = 26,
Notice = 27,
Warning = 28,
Row = 100,
Done = 101
}
public enum ExtendedResult : int
{
IOErrorRead = (Result.IOError | (1 << 8)),
IOErrorShortRead = (Result.IOError | (2 << 8)),
IOErrorWrite = (Result.IOError | (3 << 8)),
IOErrorFsync = (Result.IOError | (4 << 8)),
IOErrorDirFSync = (Result.IOError | (5 << 8)),
IOErrorTruncate = (Result.IOError | (6 << 8)),
IOErrorFStat = (Result.IOError | (7 << 8)),
IOErrorUnlock = (Result.IOError | (8 << 8)),
IOErrorRdlock = (Result.IOError | (9 << 8)),
IOErrorDelete = (Result.IOError | (10 << 8)),
IOErrorBlocked = (Result.IOError | (11 << 8)),
IOErrorNoMem = (Result.IOError | (12 << 8)),
IOErrorAccess = (Result.IOError | (13 << 8)),
IOErrorCheckReservedLock = (Result.IOError | (14 << 8)),
IOErrorLock = (Result.IOError | (15 << 8)),
IOErrorClose = (Result.IOError | (16 << 8)),
IOErrorDirClose = (Result.IOError | (17 << 8)),
IOErrorSHMOpen = (Result.IOError | (18 << 8)),
IOErrorSHMSize = (Result.IOError | (19 << 8)),
IOErrorSHMLock = (Result.IOError | (20 << 8)),
IOErrorSHMMap = (Result.IOError | (21 << 8)),
IOErrorSeek = (Result.IOError | (22 << 8)),
IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)),
IOErrorMMap = (Result.IOError | (24 << 8)),
LockedSharedcache = (Result.Locked | (1 << 8)),
BusyRecovery = (Result.Busy | (1 << 8)),
CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)),
CannotOpenIsDir = (Result.CannotOpen | (2 << 8)),
CannotOpenFullPath = (Result.CannotOpen | (3 << 8)),
CorruptVTab = (Result.Corrupt | (1 << 8)),
ReadonlyRecovery = (Result.ReadOnly | (1 << 8)),
ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)),
ReadonlyRollback = (Result.ReadOnly | (3 << 8)),
AbortRollback = (Result.Abort | (2 << 8)),
ConstraintCheck = (Result.Constraint | (1 << 8)),
ConstraintCommitHook = (Result.Constraint | (2 << 8)),
ConstraintForeignKey = (Result.Constraint | (3 << 8)),
ConstraintFunction = (Result.Constraint | (4 << 8)),
ConstraintNotNull = (Result.Constraint | (5 << 8)),
ConstraintPrimaryKey = (Result.Constraint | (6 << 8)),
ConstraintTrigger = (Result.Constraint | (7 << 8)),
ConstraintUnique = (Result.Constraint | (8 << 8)),
ConstraintVTab = (Result.Constraint | (9 << 8)),
NoticeRecoverWAL = (Result.Notice | (1 << 8)),
NoticeRecoverRollback = (Result.Notice | (2 << 8))
}
public enum ConfigOption : int
{
SingleThread = 1,
MultiThread = 2,
Serialized = 3
}
const string LibraryPath = "sqlite3";
#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE && !USE_SQLITEPCL_RAW
[DllImport(LibraryPath, EntryPoint = "sqlite3_threadsafe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Threadsafe ();
[DllImport(LibraryPath, EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open(byte[] filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)]
public static extern Result EnableLoadExtension (IntPtr db, int onoff);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Close (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Close2(IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Initialize();
[DllImport(LibraryPath, EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Shutdown();
[DllImport(LibraryPath, EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Config (ConfigOption option);
[DllImport(LibraryPath, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
public static extern int SetDirectory (uint directoryType, string directoryPath);
[DllImport(LibraryPath, EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)]
public static extern Result BusyTimeout (IntPtr db, int milliseconds);
[DllImport(LibraryPath, EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)]
public static extern int Changes (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail);
#if NETFX_CORE
[DllImport (LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail);
#endif
public static IntPtr Prepare2 (IntPtr db, string query)
{
IntPtr stmt;
#if NETFX_CORE
byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query);
var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero);
#else
var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero);
#endif
if (r != Result.OK) {
throw SQLiteException.New (r, GetErrmsg (db));
}
return stmt;
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Step (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Reset (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Finalize (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)]
public static extern long LastInsertRowid (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr Errmsg (IntPtr db);
public static string GetErrmsg (IntPtr db)
{
return Marshal.PtrToStringUni (Errmsg (db));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindNull (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt (IntPtr stmt, int index, int val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt64 (IntPtr stmt, int index, long val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindDouble (IntPtr stmt, int index, double val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnCount (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnName (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr ColumnName16Internal (IntPtr stmt, int index);
public static string ColumnName16(IntPtr stmt, int index)
{
return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)]
public static extern ColType ColumnType (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnInt (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern long ColumnInt64 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)]
public static extern double ColumnDouble (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText16 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnBlob (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnBytes (IntPtr stmt, int index);
public static string ColumnString (IntPtr stmt, int index)
{
return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index));
}
public static byte[] ColumnByteArray (IntPtr stmt, int index)
{
int length = ColumnBytes (stmt, index);
var result = new byte[length];
if (length > 0)
Marshal.Copy (ColumnBlob (stmt, index), result, 0, length);
return result;
}
[DllImport (LibraryPath, EntryPoint = "sqlite3_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern Result GetResult (Sqlite3DatabaseHandle db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern ExtendedResult ExtendedErrCode (IntPtr db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
public static extern int LibVersionNumber ();
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
public static extern Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, [MarshalAs (UnmanagedType.LPStr)] string destName, Sqlite3DatabaseHandle sourceDb, [MarshalAs (UnmanagedType.LPStr)] string sourceName);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupStep (Sqlite3BackupHandle backup, int numPages);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupFinish (Sqlite3BackupHandle backup);
#else
public static Result Open (string filename, out Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_open (filename, out db);
}
public static Result Open (string filename, out Sqlite3DatabaseHandle db, int flags, string vfsName)
{
#if USE_WP8_NATIVE_SQLITE
return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, vfsName ?? "");
#else
return (Result)Sqlite3.sqlite3_open_v2 (filename, out db, flags, vfsName);
#endif
}
public static Result Close (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close (db);
}
public static Result Close2 (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close_v2 (db);
}
public static Result BusyTimeout (Sqlite3DatabaseHandle db, int milliseconds)
{
return (Result)Sqlite3.sqlite3_busy_timeout (db, milliseconds);
}
public static int Changes (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_changes (db);
}
public static Sqlite3Statement Prepare2 (Sqlite3DatabaseHandle db, string query)
{
Sqlite3Statement stmt = default (Sqlite3Statement);
#if USE_WP8_NATIVE_SQLITE || USE_SQLITEPCL_RAW
var r = Sqlite3.sqlite3_prepare_v2 (db, query, out stmt);
#else
stmt = new Sqlite3Statement();
var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0);
#endif
if (r != 0) {
throw SQLiteException.New ((Result)r, GetErrmsg (db));
}
return stmt;
}
public static Result Step (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_step (stmt);
}
public static Result Reset (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_reset (stmt);
}
public static Result Finalize (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_finalize (stmt);
}
public static long LastInsertRowid (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_last_insert_rowid (db);
}
public static string GetErrmsg (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_errmsg (db).utf8_to_string ();
}
public static int BindParameterIndex (Sqlite3Statement stmt, string name)
{
return Sqlite3.sqlite3_bind_parameter_index (stmt, name);
}
public static int BindNull (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_bind_null (stmt, index);
}
public static int BindInt (Sqlite3Statement stmt, int index, int val)
{
return Sqlite3.sqlite3_bind_int (stmt, index, val);
}
public static int BindInt64 (Sqlite3Statement stmt, int index, long val)
{
return Sqlite3.sqlite3_bind_int64 (stmt, index, val);
}
public static int BindDouble (Sqlite3Statement stmt, int index, double val)
{
return Sqlite3.sqlite3_bind_double (stmt, index, val);
}
public static int BindText (Sqlite3Statement stmt, int index, string val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_text(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_text (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null);
#endif
}
public static int BindBlob (Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_blob (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null);
#endif
}
public static int ColumnCount (Sqlite3Statement stmt)
{
return Sqlite3.sqlite3_column_count (stmt);
}
public static string ColumnName (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static string ColumnName16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static ColType ColumnType (Sqlite3Statement stmt, int index)
{
return (ColType)Sqlite3.sqlite3_column_type (stmt, index);
}
public static int ColumnInt (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int (stmt, index);
}
public static long ColumnInt64 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int64 (stmt, index);
}
public static double ColumnDouble (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_double (stmt, index);
}
public static string ColumnText (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static string ColumnText16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnBlob (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_blob (stmt, index).ToArray ();
}
public static int ColumnBytes (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_bytes (stmt, index);
}
public static string ColumnString (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnByteArray (Sqlite3Statement stmt, int index)
{
int length = ColumnBytes (stmt, index);
if (length > 0) {
return ColumnBlob (stmt, index);
}
return new byte[0];
}
public static Result EnableLoadExtension (Sqlite3DatabaseHandle db, int onoff)
{
return (Result)Sqlite3.sqlite3_enable_load_extension (db, onoff);
}
public static int LibVersionNumber ()
{
return Sqlite3.sqlite3_libversion_number ();
}
public static Result GetResult (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_errcode (db);
}
public static ExtendedResult ExtendedErrCode (Sqlite3DatabaseHandle db)
{
return (ExtendedResult)Sqlite3.sqlite3_extended_errcode (db);
}
public static Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, string destName, Sqlite3DatabaseHandle sourceDb, string sourceName)
{
return Sqlite3.sqlite3_backup_init (destDb, destName, sourceDb, sourceName);
}
public static Result BackupStep (Sqlite3BackupHandle backup, int numPages)
{
return (Result)Sqlite3.sqlite3_backup_step (backup, numPages);
}
public static Result BackupFinish (Sqlite3BackupHandle backup)
{
return (Result)Sqlite3.sqlite3_backup_finish (backup);
}
#endif
public enum ColType : int
{
Integer = 1,
Float = 2,
Text = 3,
Blob = 4,
Null = 5
}
}
}
| praeclarum/sqlite-net | src/SQLite.cs | C# | mit | 158,773 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About IadixCoin</source>
<translation>Over IadixCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>IadixCoin</b> version</source>
<translation><b>IadixCoin</b> versie</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The IadixCoin developers</source>
<translation>Copyright © 2009-2014 De Bitcoin ontwikkelaars
Copyright © 2012-2014 De NovaCoin ontwikkelaars
Copyright © 2014 De IadixCoin ontwikkelaars</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresboek</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dubbelklik om het adres of label te wijzigen</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Maak een nieuw adres aan</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopieer het huidig geselecteerde adres naar het klembord</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Nieuw adres</translation>
</message>
<message>
<location line="-43"/>
<source>These are your IadixCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dit zijn al jou IadixCoin adressen om betalingen mee te ontvangen. Je kunt iedere verzender een apart adres geven zodat je kunt volgen wie jou betaald.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Kopiëer Adres</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Toon &QR Code</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a IadixCoin address</source>
<translation>Teken een bericht om te bewijzen dat je een IadixCoin adres bezit.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Teken &Bericht</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Verwijder het geselecteerde adres van de lijst</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified IadixCoin address</source>
<translation>Verifieer een bericht om zeker te zijn dat deze is ondertekend met een specifiek IadixCoin adres</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifieer Bericht</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Verwijder</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+66"/>
<source>Copy &Label</source>
<translation>Kopiëer &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Bewerk</translation>
</message>
<message>
<location line="+248"/>
<source>Export Address Book Data</source>
<translation>Exporteer Adresboek Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kan niet schrijven naat bestand %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Wachtwoordscherm</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Voer wachtwoord in</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nieuw wachtwoord</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Herhaal wachtwoord</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Bedoeld om het command 'sendmoney' uit te schakelen indien het OS niet meer veilig is. Geeft geen echte beveiliging.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Alleen voor staking</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Versleutel portemonnee</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Open portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Ontsleutel portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Wijzig wachtwoord</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Bevestig versleuteling van de portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Waarschuwing: Als je je portemonnee versleuteld en je verliest je wachtwoord zul je <b>AL JE MUNTEN VERLIEZEN</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Portemonnee versleuteld</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>IadixCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>IadixCoin zal nu sluiten om het versleutel proces te voltooien. Onthou dat het versleutelen van je portemonnee je niet volledig beschermt tegen diefstal van munten door malware op je computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Portemonneeversleuteling mislukt</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>De opgegeven wachtwoorden komen niet overeen</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Portemonnee openen mislukt</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Portemonnee-ontsleuteling mislukt</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Portemonneewachtwoord is met succes gewijzigd.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>&Onderteken bericht...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Toon algemeen overzicht van de portemonnee</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transacties</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Blader door transactieverleden</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adresboek</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Wijzig de lijst met bewaarde adressen en labels</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Toon de lijst aan adressen voor ontvangen betalingen</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Afsluiten</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Programma afsluiten</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about IadixCoin</source>
<translation>Toon informatie over IadixCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Over &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Toon informatie over Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opties...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Versleutel Portemonnee...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>&Backup Portemonnee...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Wijzig Wachtwoord</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Exporteren...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a IadixCoin address</source>
<translation>Verstuur munten naar een IadixCoin adres</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for IadixCoin</source>
<translation>Verander configuratie opties voor IadixCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporteer de data in de huidige tab naar een bestand</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Versleutel of ontsleutel de portemonnee</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Backup portemonnee naar een andere locatie</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Debugscherm</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging en diagnostische console</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifiëer bericht...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>IadixCoin</source>
<translation>IadixCoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+193"/>
<source>&About IadixCoin</source>
<translation>&Over IadixCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Toon / Verberg</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Open portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Sluit portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Sluit portemonnee</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Bestand</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Instellingen</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Tab-werkbalk</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnetwerk]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>IadixCoin client</source>
<translation>IadixCoin client</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to IadixCoin network</source>
<translation><numerusform>%n actieve verbinding naar IadixCoin netwerk</numerusform><numerusform>%n actieve verbindingen naar IadixCoin netwerk</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Staking. <br> Uw gewicht wordt %1 <br> Network gewicht is %2 <br> Verwachte tijd om beloning te verdienen is %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Niet staking omdat portemonnee beveiligd is</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Niet staking omdat portemonnee offline is</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Niet staking omdat portemonnee aan het synchroniseren is.</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Niet staking omdat je geen mature munten hebt</translation>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation>&Ontvangen</translation>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation>&Verzenden</translation>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>Ontgrendel portemonnee...</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Bijgewerkt</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Aan het bijwerken...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bevestig transactie kosten</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Verzonden transactie</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Binnenkomende transactie</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Bedrag: %2
Type: %3
Adres: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI-behandeling</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid IadixCoin address or malformed URI parameters.</source>
<translation>URI kan niet ontleedt worden! Mogelijke oorzaken zijn een ongeldig IadixCoin adres of incorrecte URI parameters.</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>geopend</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>gesloten</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Backup Portemonnee</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Portemonnee bestanden (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup mislukt</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Er was een fout opgetreden bij het opslaan van de wallet data naar de nieuwe locatie.</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n seconden</numerusform><numerusform>%n seconden</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minuut</numerusform><numerusform>%n minuten</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation>Laatst ontvangen block was %1 geleden</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informatie</translation>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Niet aan het staken.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. IadixCoin can no longer continue safely and will quit.</source>
<translation>Een fatale fout . Iadixcoin kan niet langer veilig doorgaan en sluit af.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Netwerkwaarschuwing</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Coin controle opties</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Kwantiteit</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioriteit:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lage uitvoer:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>nee</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Na vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Wijzigen:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(de)selecteer alles</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Boom modus</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Lijst modus</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Bevestigingen</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Bevestigd</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioriteit</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Kopieer adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopieer label</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopieer transactie-ID</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopieer aantal</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopieer vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopieer na vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopieer bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopieer prioriteit</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopieer lage uitvoer</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopieer wijzig</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>hoogste</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>hoog</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>gemiddeld hoog</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>gemiddeld</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>laag gemiddeld</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>laag</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>laagste</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation>STOF</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ja</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Dit label wordt rood, als de transactie grootte groter is dan 10000 bytes.<br>
Dit betekend een fee van minimaal %1 per kb is noodzakelijk.<br>
Kan varieren van +/- 1 Byte per invulling</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Transacties met hogere prioriteit komen sneller in een blok
Dit label wordt rood, als de prioriteit kleiner is dan "normaal".
Dit betekend een fee van minimaal %1 per kb is noodzakelijk.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Dit label wordt rood, als elke ontvanger ontvangt een bedrag dat kleiner is dan 1%.
Dit betekent dat een vergoeding van ten minste 2% is vereist.
Bedragen onder 0.546 keer het minimum vergoeding worden weergegeven als DUST.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Dit label wordt rood, als de verandering kleiner is dan %1.
Dit betekend dat een fee van %2 is vereist.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>wijzig van %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(wijzig)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Bewerk Adres</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Het label geassocieerd met deze notitie in het adresboek</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Het adres geassocieerd met deze notitie in het adresboek. Dit kan enkel aangepast worden bij verzend-adressen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nieuw ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nieuw adres om naar te verzenden</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Bewerk ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Bewerk adres om naar te verzenden</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Het opgegeven adres "%1" bestaat al in uw adresboek.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid IadixCoin address.</source>
<translation>Het ingevoerde adres "%1" is geen geldig Iadixcoin adres.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kon de portemonnee niet openen.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Genereren nieuwe sleutel mislukt.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>IadixCoin-Qt</source>
<translation>IadixCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versie</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Commandoregel-opties</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Gebruikerinterface-opties</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Stel taal in, bijvoorbeeld "de_DE" (standaard: systeeminstellingen)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Geminimaliseerd starten</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opties</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Algemeen</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Optioneel transactiekosten per kB dat helpt ervoor zorgen dat uw transacties worden snel verwerkt. De meeste transacties zijn 1 kB. Fee 0.01 aanbevolen.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betaal &transactiekosten</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Gereserveerde hoeveelheid doet niet mee in staking en is daarom altijd uitgeefbaar.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Gereserveerd</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start IadixCoin after logging in to the system.</source>
<translation>Automatisch starten van Iadixcoin na inloggen van het systeem.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start IadixCoin on system login</source>
<translation>&Start Iadixcoin bij systeem aanmelding</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Netwerk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the IadixCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>De IadixCoin client poort automatisch openen op de router. Dit werkt alleen wanneer uw router UPnP ondersteunt en deze is ingeschakeld.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portmapping via &UPnP</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP Adres van de proxy (bijv. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Poort:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Poort van de proxy (bijv. 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the IadixCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Scherm</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimaliseer naar het systeemvak in plaats van de taakbalk</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Minimaliseer bij sluiten van het &venster</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interface</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Taal &Gebruikersinterface:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting IadixCoin.</source>
<translation>De user interface-taal kan hier ingesteld worden. Deze instelling word toegepast na IadixCoin opnieuw op te starten.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Eenheid om bedrag in te tonen:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Munt controle functies weergeven of niet.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Laat coin & control functies zien (enkel voor gevorderden!)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>Ann&uleren</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Toepassen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>standaard</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting IadixCoin.</source>
<translation>Deze instelling word toegepast na een restart van IadixCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Het opgegeven proxyadres is ongeldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the IadixCoin network after a connection is established, but this process has not completed yet.</source>
<translation>De weergegeven informatie kan verouderd zijn, Je portemonnee synchroniseerd automatisch met het IadixCoin netwerk nadat er verbindig is gemaakt, maar dit proces is nog niet voltooid.</translation>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Onbevestigd:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Uitgeefbaar:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Uw beschikbare saldo</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Immatuur:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Totaal:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Uw totale saldo</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Recente transacties</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totaal van de transacties die nog moeten worden bevestigd, en nog niet mee voor het huidige balans</translation>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Totaal aantal munten dat was staked, en nog niet telt voor huidige balans.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>niet gesynchroniseerd</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start iadixcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Scherm</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Vraag betaling</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Hoeveelheid:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Bericht:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Opslaan als...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fout tijdens encoderen URI in QR-code</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>De ingevoerde hoeveel is ongeldig, controleer aub.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Sla QR Code op.</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Afbeeldingen (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Clientnaam</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>N.v.t.</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Clientversie</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informatie</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Gebruikt OpenSSL versie</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Opstarttijd</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Netwerk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Aantal connecties</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Op testnetwerk</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokketen</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Huidig aantal blokken</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Tijd laatste blok</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Commandoregel-opties</translation>
</message>
<message>
<location line="+7"/>
<source>Show the IadixCoin-Qt help message to get a list with possible IadixCoin command-line options.</source>
<translation>Laat het Iadixcoin-QT help bericht zien om een lijst te krijgen met mogelijke Iadixcoin command-regel opties.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Bouwdatum</translation>
</message>
<message>
<location line="-104"/>
<source>IadixCoin - Debug window</source>
<translation>Iadixcoin - Debugscherm</translation>
</message>
<message>
<location line="+25"/>
<source>IadixCoin Core</source>
<translation>IadixCoin Kern</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Debug-logbestand</translation>
</message>
<message>
<location line="+7"/>
<source>Open the IadixCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open het IadixCoin debug log bestand van de huidige data map. Dit kan een paar seconden duren voor grote log bestanden.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Maak console leeg</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the IadixCoin RPC console.</source>
<translation>Welkom bij de IadixCoin RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en <b>Ctrl-L</b> om het scherm leeg te maken.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Typ <b>help</b> voor een overzicht van de beschikbare commando's.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Verstuur munten</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Coin controle opties</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Invoer...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automatisch geselecteerd</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Onvoldoende fonds!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Kwantiteit</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Prioriteit:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>gemiddeld</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lage uitvoer:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>nee</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Na vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Wijzigen</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>handmatig veranderen adres</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Verstuur aan verschillende ontvangers ineens</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Voeg &Ontvanger Toe</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Bevestig de verstuuractie</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Verstuur</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopieer aantal</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopieer vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopieer na vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopieer bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopieer prioriteit</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopieer lage uitvoer</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopieer wijzig</translation>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b> %1 </b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bevestig versturen munten</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Weet je zeker dat je %1 wilt verzenden?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>en</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Bedrag is hoger dan uw huidige saldo</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fout: De transactie was geweigerd, Dit kan gebeuren als sommige munten in je portemonnee al gebruikt zijn, door het gebruik van een kopie van wallet.dat en de munten in de kopie zijn niet gemarkeerd als gebruikt.</translation>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid IadixCoin address</source>
<translation>WAARSCHUWING: Ongeldig Iadixcoin adres</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>WAARSCHUWING: Onbekend adres</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Bedra&g:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betaal &Aan:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Kies adres uit adresboek</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Plak adres vanuit klembord</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Verwijder deze ontvanger</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>O&nderteken Bericht</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Het adres om het bericht te ondertekenen (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i) </translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Kies een adres uit het adresboek</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Plak adres vanuit klembord</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Typ hier het bericht dat u wilt ondertekenen</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopieer de huidige handtekening naar het systeemklembord</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this IadixCoin address</source>
<translation>Teken een bericht om te bewijzen dat je een IadixCoin adres bezit.</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verifiëer Bericht</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Het adres van het bericht is ondertekend met (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified IadixCoin address</source>
<translation>Verifieer een bericht om zeker te zijn dat deze is ondertekend met een specifiek IadixCoin adres</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klik "Onderteken Bericht" om de handtekening te genereren</translation>
</message>
<message>
<location line="+3"/>
<source>Enter IadixCoin signature</source>
<translation>Voer IadixCoin handtekening in</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Het opgegeven adres is ongeldig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Controleer s.v.p. het adres en probeer het opnieuw.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Het opgegeven adres verwijst niet naar een sleutel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Portemonnee-ontsleuteling is geannuleerd</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ondertekenen van het bericht is mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Bericht ondertekend.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>De handtekening kon niet worden gedecodeerd.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>De handtekening hoort niet bij het bericht.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Berichtverificatie mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Bericht correct geverifiëerd.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Openen totdat %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>conflicted</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/onbevestigd</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bevestigingen</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Bron</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gegenereerd</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Aan</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>eigen adres</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>niet geaccepteerd</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transactiekosten</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Bericht</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Opmerking</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transactie-ID:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Gegenereerd munten moeten 510 blokken maturen voordat ze kunnen worden besteed. Wanneer je een blok genereerd, het naar het netwerk is verzonden en toegevoegd aan de blokketen, zal de status veranderen naar "niet geaccepteerd"and kan het niet uitgegeven worden. Dit kan soms gebeuren als een ander knooppunt genereert een blok binnen een paar seconden na jou.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug-informatie</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transactie</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, is nog niet met succes uitgezonden</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transactiedetails</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Open tot %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bevestigd (%1 bevestigingen)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Offline</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Onbevestigd:</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Bevestigen.. (%1 van de %2 bevestigingen)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Conflicted</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 bevestiging, word beschikbaar na %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gegenereerd maar niet geaccepteerd</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ontvangen van</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling aan uzelf</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nvt)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tijd waarop deze transactie is ontvangen.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Ontvangend adres van transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bedrag verwijderd van of toegevoegd aan saldo</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Vandaag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Deze week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Deze maand</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Vorige maand</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dit jaar</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Bereik...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Aan uzelf</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Anders</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Vul adres of label in om te zoeken</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min. bedrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopieer adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopieer label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopieer transactie-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Bewerk label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Toon transactiedetails</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>Exporteer Transactie Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bevestigd</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kan niet schrijven naar bestand %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Bereik:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>naar</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+212"/>
<source>Sending...</source>
<translation>Versturen...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+171"/>
<source>IadixCoin version</source>
<translation>IadixCoin versie</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or iadixcoind</source>
<translation>Verstuur commando naar -server of iadixcoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lijst van commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Toon hulp voor een commando</translation>
</message>
<message>
<location line="-145"/>
<source>Options:</source>
<translation>Opties:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: iadixcoin.conf)</source>
<translation>Selecteer configuratie bestand (standaard: iadixcoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: iadixcoind.pid)</source>
<translation>Selecteer pid bestand (standaard: iadixcoin.conf)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Specificeer het portemonnee bestand (vanuit de gegevensmap)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Stel datamap in</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=iadixcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "IadixCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Stel database cache grootte in in megabytes (standaard: 100)</translation>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Luister voor verbindingen op <poort> (standaard: 15714 of testnet: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Onderhoud maximaal <n> verbindingen naar peers (standaard: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Specificeer uw eigen publieke adres</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Koppel aan gegeven adres. Gebruik [host]:poort notatie voor IPv6</translation>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation>
</message>
<message>
<location line="-35"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation>
</message>
<message>
<location line="+62"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Wacht op JSON-RPC-connecties op <poort> (standaard: 15715 of testnet: 25715) </translation>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aanvaard commandoregel- en JSON-RPC-commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Draai in de achtergrond als daemon en aanvaard commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Gebruik het testnetwerk</translation>
</message>
<message>
<location line="-23"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar IPv4: %s</translation>
</message>
<message>
<location line="+93"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Stel maximale grootte van high-priority/low-fee transacties in bytes (standaard: 27000)</translation>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong IadixCoin will not work properly.</source>
<translation>Waarschuwing: Controleer of de datum en tijd van de computer juist zijn! Als uw klok verkeerd is IadixCoin zal niet goed werken.</translation>
</message>
<message>
<location line="+130"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma's zouden kunnen ontbreken of fouten bevatten.</translation>
</message>
<message>
<location line="-16"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Blokcreatie-opties:</translation>
</message>
<message>
<location line="-67"/>
<source>Connect only to the specified node(s)</source>
<translation>Verbind alleen naar de gespecificeerde node(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation>
</message>
<message>
<location line="-2"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ongeldig-tor adres: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Ongeldig bedrag voor -reservebalance = <bedrag></translation>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connectie ontvangstbuffer, <n>*1000 bytes (standaard: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connectie zendbuffer, <n>*1000 bytes (standaard: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Verbind alleen naar nodes in netwerk <net> (IPv4, IPv6 of Tor)</translation>
</message>
<message>
<location line="+30"/>
<source>Prepend debug output with timestamp</source>
<translation>Voeg een tijdstempel toe aan debug output</translation>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL-opties: (zie de Bitcoin wiki voor SSL-instructies)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Stel maximale block grootte in bytes in (standaard: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation>
</message>
<message>
<location line="-41"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation>
</message>
<message>
<location line="+28"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Gebruik proxy tor verborgen diensten (standaard: zelfde als -proxy)</translation>
</message>
<message>
<location line="+45"/>
<source>Username for JSON-RPC connections</source>
<translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Database integriteit wordt geverifieërd</translation>
</message>
<message>
<location line="+42"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation>
</message>
<message>
<location line="-52"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, veiligstellen mislukt</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>Wachtwoord voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="-47"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synchroniseer tijd met andere connecties. Uitschakelen als de tijd op uw systeem nauwkeurig is bijv. synchroniseren met NTP (standaard: 1)</translation>
</message>
<message>
<location line="+12"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Bij het maken van transacties, negeer ingangen met waarde minder dan dit (standaard: 0,01)</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Verstuur commando's naar proces dat op <ip> draait (standaard: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Vereist een bevestiging voor verandering (standaard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Voer opdracht uit zodra een relevante waarschuwing wordt ontvangen (%s in cmd wordt vervangen door bericht)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Vernieuw portemonnee naar nieuwste versie</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Stel sleutelpoelgrootte in op <n> (standaard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Hoe grondig het blokverificatie is (0-6, standaard: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importeer blokken van extern blk000?.dat bestand</translation>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> MiB of unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificaat-bestand voor server (standaard: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Geheime sleutel voor server (standaard: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. IadixCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Fout: Portemonnee ontgrendeld voor alleen staking, niet in staat om de transactie te maken.</translation>
</message>
<message>
<location line="+16"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-168"/>
<source>This help message</source>
<translation>Dit helpbericht</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Portemonnee %s bevindt zich buiten de datamap %s.</translation>
</message>
<message>
<location line="+35"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation>
</message>
<message>
<location line="-129"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation>
</message>
<message>
<location line="+125"/>
<source>Loading addresses...</source>
<translation>Adressen aan het laden...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of IadixCoin</source>
<translation>Fout bij laden van wallet.dat: Portemonnee vereist een nieuwere versie van IadixCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart IadixCoin to complete</source>
<translation>Portemonnee moet herschreven worden: herstart IadixCoin om te voltooien</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Fout bij laden wallet.dat</translation>
</message>
<message>
<location line="-15"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ongeldig -proxy adres: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Onbekend netwerk gespecificeerd in -onlynet: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kan -bind adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kan -externlip adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -paytxfee=<bedrag>: '%s'</translation>
</message>
<message>
<location line="+58"/>
<source>Sending...</source>
<translation>Versturen...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ongeldig bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Ontoereikend saldo</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Blokindex aan het laden...</translation>
</message>
<message>
<location line="-109"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation>
</message>
<message>
<location line="+124"/>
<source>Unable to bind to %s on this computer. IadixCoin is probably already running.</source>
<translation>Niet mogelijk om %s op deze computer. IadixCoin is waarschijnlijk al geopened.</translation>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Vergoeding per KB toe te voegen aan de transacties die u verzendt</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -mininput = <bedrag>: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. IadixCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Loading wallet...</source>
<translation>Portemonnee aan het laden...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Kan portemonnee niet downgraden</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Kan standaardadres niet schrijven</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Blokketen aan het doorzoeken...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Klaar met laden</translation>
</message>
<message>
<location line="-159"/>
<source>To use the %s option</source>
<translation>Om de %s optie te gebruiken</translation>
</message>
<message>
<location line="+186"/>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>U dient rpcpassword=<wachtwoord> in te stellen in het configuratiebestand:
%s
Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen permissie.</translation>
</message>
</context>
</TS> | iadix/iadixcoin | src/qt/locale/bitcoin_nl.ts | TypeScript | mit | 126,834 |
package org.mdo.storyline.character.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import org.mdo.storyline.character.web.filter.CachingHttpHeadersFilter;
import org.mdo.storyline.character.web.filter.StaticResourcesProductionFilter;
import org.mdo.storyline.character.web.filter.gzip.GZipServletFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import javax.inject.Inject;
import javax.servlet.*;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
@AutoConfigureAfter(CacheConfiguration.class)
public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
@Inject
private Environment env;
@Inject
private MetricRegistry metricRegistry;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
initMetrics(servletContext, disps);
if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
initCachingHttpHeadersFilter(servletContext, disps);
initStaticResourcesProductionFilter(servletContext, disps);
}
initGzipFilter(servletContext, disps);
log.info("Web application fully configured");
}
/**
* Set up Mime types.
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", "text/html;charset=utf-8");
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", "text/html;charset=utf-8");
container.setMimeMappings(mappings);
}
/**
* Initializes the GZip filter.
*/
private void initGzipFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Registering GZip Filter");
FilterRegistration.Dynamic compressingFilter = servletContext.addFilter("gzipFilter", new GZipServletFilter());
Map<String, String> parameters = new HashMap<>();
compressingFilter.setInitParameters(parameters);
compressingFilter.addMappingForUrlPatterns(disps, true, "*.css");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.json");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.html");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.js");
compressingFilter.addMappingForUrlPatterns(disps, true, "/app/rest/*");
compressingFilter.addMappingForUrlPatterns(disps, true, "/metrics/*");
compressingFilter.setAsyncSupported(true);
}
/**
* Initializes the static resources production Filter.
*/
private void initStaticResourcesProductionFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering static resources production Filter");
FilterRegistration.Dynamic staticResourcesProductionFilter =
servletContext.addFilter("staticResourcesProductionFilter",
new StaticResourcesProductionFilter());
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/images/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/views/*");
staticResourcesProductionFilter.setAsyncSupported(true);
}
/**
* Initializes the cachig HTTP Headers Filter.
*/
private void initCachingHttpHeadersFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
new CachingHttpHeadersFilter());
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/images/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
/**
* Initializes Metrics.
*/
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Initializing Metrics registries");
servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
metricRegistry);
servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
metricRegistry);
log.debug("Registering Metrics Filter");
FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
new InstrumentedFilter());
metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
metricsFilter.setAsyncSupported(true);
log.debug("Registering Metrics Servlet");
ServletRegistration.Dynamic metricsAdminServlet =
servletContext.addServlet("metricsServlet", new MetricsServlet());
metricsAdminServlet.addMapping("/metrics/metrics/*");
metricsAdminServlet.setAsyncSupported(true);
metricsAdminServlet.setLoadOnStartup(2);
}
}
| dohr-michael/storyline-character | src/main/java/org/mdo/storyline/character/config/WebConfigurer.java | Java | mit | 6,892 |
;(function(){
'use strict';
angular.module('TTT')
.config(function($routeProvider){
$routeProvider
.when('/emu',{
templateUrl: 'views/emu.html',
controller: 'emuController',
controllerAs: 'emu'
});
});
})();
| beck410/GJ_Timetravel | app/js/config/emu.config.js | JavaScript | mit | 247 |
/* External utility functions for Modelica packages
Modelica_Utilities.Internal
The functions are mostly non-portable. The following #define's are used
to define the system calls of the operating system
_WIN32 : System calls of Windows'95, Windows'NT
(Note, that these system calls allow both '/' and '\'
as directory separator for input arguments. As return
argument '\' is used).
All system calls are from the library libc.a.
_POSIX_ : System calls of POSIX
_MSC_VER : Microsoft Visual C++
__GNUC__ : GNU C compiler
NO_FILE_SYSTEM: A file system is not present (e.g. on dSpace or xPC).
Release Notes:
Sept. 26, 2004: by Martin Otter, DLR.
Added missing implementations, merged code from previous ModelicaFiles
and clean-up of code.
Sep. 9, 2004: by Dag Bruck, Dynasim AB.
Further implementation and clean-up of code.
Aug. 24, 2004: by Martin Otter, DLR.
Adapted to Dymola 5.3 with minor improvements.
Jan. 7, 2002: by Martin Otter, DLR.
First version implemented.
Only tested for _WIN32, but implemented all
functions also for _POSIX_, with the exception of
ModelicaInternal_getFullPath
Copyright (C) 2002-2006, Modelica Association and DLR.
The content of this file is free software; it can be redistributed
and/or modified under the terms of the Modelica License 2, see the
license conditions and the accompanying disclaimer in file
Modelica/ModelicaLicense2.html or in Modelica.UsersGuide.ModelicaLicense2.
*/
#if defined(linux)
#define _POSIX_ 1
#endif
#include <string.h>
#include "ModelicaUtilities.h"
static void ModelicaNotExistError(const char* name) {
/* Print error message if a function is not implemented */
ModelicaFormatError("C-Function \"%s\" is called\n"
"but is not implemented for the actual environment\n"
"(e.g., because there is no file system available on the machine\n"
"as for dSpace or xPC systems)", name);
}
#if NO_FILE_SYSTEM
static void ModelicaInternal_mkdir(const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_mkdir"); }
static void ModelicaInternal_rmdir(const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_rmdir"); }
static int ModelicaInternal_stat(const char* name) {
ModelicaNotExistError("ModelicaInternal_stat"); return 0; }
static void ModelicaInternal_rename(const char* oldName, const char* newName) {
ModelicaNotExistError("ModelicaInternal_rename"); }
static void ModelicaInternal_removeFile(const char* file) {
ModelicaNotExistError("ModelicaInternal_removeFile"); }
static void ModelicaInternal_copyFile(const char* oldFile, const char* newFile) {
ModelicaNotExistError("ModelicaInternal_copyFile"); }
static void ModelicaInternal_readDirectory(const char* directory, int nFiles, const char* files[]) {
ModelicaNotExistError("ModelicaInternal_readDirectory"); }
static int ModelicaInternal_getNumberOfFiles(const char* directory) {
ModelicaNotExistError("ModelicaInternal_getNumberOfFiles"); return 0; }
static const char* ModelicaInternal_fullPathName(const char* name) {
ModelicaNotExistError("ModelicaInternal_fullPathName"); return 0; }
static const char* ModelicaInternal_temporaryFileName() {
ModelicaNotExistError("ModelicaInternal_temporaryFileName"); return 0; }
static void ModelicaInternal_print(const char* string, const char* fileName) {
ModelicaNotExistError("ModelicaInternal_print"); }
static int ModelicaInternal_countLines(const char* fileName) {
ModelicaNotExistError("ModelicaInternal_countLines"); return 0; }
static void ModelicaInternal_readFile(const char* fileName, const char* string[], size_t nLines) {
ModelicaNotExistError("ModelicaInternal_readFile"); }
static const char* ModelicaInternal_readLine(const char* fileName, int lineNumber, int* endOfFile) {
ModelicaNotExistError("ModelicaInternal_readLine"); return 0; }
static void ModelicaInternal_chdir(const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_chdir"); }
static const char* ModelicaInternal_getcwd(int dummy) {
ModelicaNotExistError("ModelicaInternal_getcwd"); return 0; }
static const char* ModelicaInternal_getenv(const char* name, int convertToSlash, int* exist) {
ModelicaNotExistError("ModelicaInternal_getenv"); return 0; }
static void ModelicaInternal_setenv(const char* name, const char* value, int convertFromSlash) {
ModelicaNotExistError("ModelicaInternal_setenv"); }
#else
# include <stdio.h>
# include <stdlib.h>
# include <errno.h>
# if defined(__WATCOMC__)
# include <direct.h>
# include <sys/types.h>
# include <sys/stat.h>
# elif defined(_WIN32)
# include <direct.h>
# include <sys/types.h>
# include <sys/stat.h>
/* include the opendir/readdir/closedir implementation for _WIN32 */
# include "win32_dirent.c"
# elif defined(_POSIX_)
# include <dirent.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <dirent.h>
# endif
#define BUFFER_LENGTH 1000
static char buffer[BUFFER_LENGTH]; /* Buffer for temporary storage */
typedef enum {
FileType_NoFile = 1,
FileType_RegularFile,
FileType_Directory,
FileType_SpecialFile /* pipe, FIFO, device, etc. */
} ModelicaFileType;
/* Convert to Unix directory separators: */
#if defined(_WIN32)
static void ModelicaConvertToUnixDirectorySeparator(char* string) {
/* convert to Unix directory separators */
char* c = string;
while ( *c ) {
if ( *c == '\\' ) {*c = '/';}
c++;
}
};
static void ModelicaConvertFromUnixDirectorySeparator(char* string) {
/* convert from Unix directory separators */
char* c = string;
while ( *c ) {
if ( *c == '/' ) {*c = '\\';}
c++;
}
};
#else
# define ModelicaConvertToUnixDirectorySeparator(string) ;
# define ModelicaConvertFromUnixDirectorySeparator(string) ;
#endif
/* --------------------- Modelica_Utilities.Internal --------------------------------- */
static void ModelicaInternal_mkdir(const char* directoryName)
{
/* Create directory */
#if defined(_WIN32)
int result = _mkdir(directoryName);
#elif defined(_POSIX_)
int result = mkdir(directoryName, S_IRUSR | S_IWUSR | S_IXUSR);
#else
int result = -1;
ModelicaNotExistError("ModelicaInternal_mkdir");
#endif
if (result != 0) {
ModelicaFormatError("Not possible to create new directory\n"
"\"%s\":\n%s", directoryName, strerror(errno));
}
}
static void ModelicaInternal_rmdir(const char* directoryName)
{
#if defined(__WATCOMC__)
int result = rmdir(directoryName);
#elif defined(_WIN32) && !defined(SimStruct)
int result = _rmdir(directoryName);
#elif defined(_POSIX_)
int result = rmdir(directoryName);
#else
int result = -1;
ModelicaNotExistError("ModelicaInternal_rmdir");
#endif
if (result != 0) {
ModelicaFormatError("Not possible to remove directory\n"
"\"%s\":\n%s", directoryName, strerror(errno));
}
}
static int ModelicaInternal_stat(const char* name)
{
/* Inquire type of file */
ModelicaFileType type = FileType_NoFile;
#if defined(_WIN32) && defined(_MSC_VER)
struct _stat fileInfo;
if ( _stat(name, &fileInfo) != 0 ) {
type = FileType_NoFile;
} else if ( fileInfo.st_mode & S_IFREG ) {
type = FileType_RegularFile;
} else if ( fileInfo.st_mode & S_IFDIR ) {
type = FileType_Directory;
} else {
type = FileType_SpecialFile;
}
#elif defined(_POSIX_) || defined(__GNUC__)
struct stat fileInfo;
if ( stat(name, &fileInfo) != 0 ) {
type = FileType_NoFile;
} else if ( S_ISREG(fileInfo.st_mode) ) {
type = FileType_RegularFile;
} else if ( S_ISDIR(fileInfo.st_mode) ) {
type = FileType_Directory;
} else {
type = FileType_SpecialFile;
}
#else
ModelicaNotExistError("ModelicaInternal_stat");
#endif
return type;
}
static void ModelicaInternal_rename(const char* oldName, const char* newName) {
/* Changes the name of a file or of a directory */
if ( rename(oldName, newName) != 0 ) {
ModelicaFormatError("renaming \"%s\" to \"%s\" failed:\n%s",
oldName, newName, strerror(errno));
}
}
static void ModelicaInternal_removeFile(const char* file) {
/* Remove file. */
if ( remove(file) != 0 ) {
ModelicaFormatError("Not possible to remove file \"%s\":\n%s",
file, strerror(errno));
}
}
static void ModelicaInternal_copyFile(const char* oldFile, const char* newFile) {
/* Copy file */
#ifdef _WIN32
const char* modeOld = "rb";
const char* modeNew = "wb";
#else
const char* modeOld = "r";
const char* modeNew = "w";
#endif
FILE* fpOld;
FILE* fpNew;
ModelicaFileType type;
int c;
/* Check file existence */
type = (ModelicaFileType) ModelicaInternal_stat(oldFile);
if ( type == FileType_NoFile ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause it does not exist", oldFile);
return;
} else if ( type == FileType_Directory ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause it is a directory", oldFile);
return;
} else if ( type == FileType_SpecialFile ) {
ModelicaFormatError("\"%s\" cannot be copied\n"
"because it is not a regular file", oldFile);
return;
}
type = (ModelicaFileType) ModelicaInternal_stat(newFile);
if ( type != FileType_NoFile ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause the target "
"\"%s\" exists", oldFile, newFile);
return;
}
/* Copy file */
fpOld = fopen(oldFile, modeOld);
if ( fpOld == NULL ) {
ModelicaFormatError("\"%s\" cannot be copied:\n%s", oldFile, strerror(errno));
return;
}
fpNew = fopen(newFile, modeNew);
if ( fpNew == NULL ) {
fclose(fpOld);
ModelicaFormatError("\"%s\" cannot be copied to \"%s\":\n%s",
oldFile, newFile, strerror(errno));
return;
}
while ( (c = getc(fpOld)) != EOF ) putc(c, fpNew);
fclose(fpOld);
fclose(fpNew);
}
static void ModelicaInternal_readDirectory(const char* directory, int nFiles,
const char** files) {
/* Get all file and directory names in a directory in any order
(must be very careful, to call closedir if an error occurs)
*/
#if defined(_WIN32) || defined(_POSIX_)
int errnoTemp;
int iFiles = 0;
char *pName;
struct dirent *pinfo;
DIR* pdir;
/* Open directory information inquiry */
pdir = opendir(directory);
if ( pdir == NULL ) {
ModelicaFormatError("1: Not possible to get file names of \"%s\":\n%s",
directory, strerror(errno));
}
/* Read file and directory names and store them in vector "files" */
errno = 0;
while ( (pinfo = readdir(pdir)) != NULL ) {
if ( (strcmp(pinfo->d_name, "." ) != 0) &&
(strcmp(pinfo->d_name, "..") != 0) ) {
/* Check if enough space in "files" vector */
if ( iFiles >= nFiles ) {
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"More files in this directory as reported by nFiles (= %i)",
directory, nFiles);
}
/* Allocate Modelica memory for file/directory name and copy name */
pName = ModelicaAllocateStringWithErrorReturn(strlen(pinfo->d_name));
if ( pName == NULL ) {
errnoTemp = errno;
closedir(pdir);
if ( errnoTemp == 0 ) {
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"Not enough storage", directory);
} else {
ModelicaFormatError("Not possible to get file names of \"%s\":\n%s",
directory, strerror(errnoTemp));
}
}
strcpy(pName, pinfo->d_name);
/* Save pointer to file */
files[iFiles] = pName;
iFiles++;
};
};
if ( errno != 0 ) {
errnoTemp = errno;
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n%s",
directory, strerror(errnoTemp));
}
/* Check, whether the whole "files" vector is filled and close inquiry */
if ( iFiles != nFiles) {
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"Less files (= %d) found as defined by argument nNames (= %d)",
directory, iFiles, nFiles);
}
if ( closedir(pdir) != 0 ) {
ModelicaFormatError("Not possible to get file names of \"%s\":\n",
directory, strerror(errno));
}
#else
ModelicaNotExistError("ModelicaInternal_readDirectory");
#endif
};
static int ModelicaInternal_getNumberOfFiles(const char* directory) {
/* Get number of files and directories in a directory */
#if defined(_WIN32) || defined(_POSIX_)
int nFiles = 0;
int errnoTemp;
struct dirent *pinfo;
DIR* pdir;
pdir = opendir(directory);
if ( pdir == NULL ) goto ERROR;
errno = 0;
while ( (pinfo = readdir(pdir)) != NULL ) {
if ( (strcmp(pinfo->d_name, "." ) != 0) &&
(strcmp(pinfo->d_name, "..") != 0) ) {
nFiles++;
};
};
errnoTemp = errno;
closedir(pdir);
if ( errnoTemp != 0 ) {errno = errnoTemp; goto ERROR;}
return nFiles;
ERROR: ModelicaFormatError("Not possible to get number of files in \"%s\":\n%s",
directory, strerror(errno));
return 0;
#else
ModelicaNotExistError("ModelicaInternal_getNumberOfFiles");
return 0;
#endif
};
/* --------------------- Modelica_Utilities.Files ------------------------------------- */
static const char* ModelicaInternal_fullPathName(const char* name)
{
/* Get full path name of file or directory */
char* fullName;
#if defined(_WIN32)
char* tempName = _fullpath(buffer, name, sizeof(buffer));
if (tempName == NULL) {
ModelicaFormatError("Not possible to construct full path name of \"%s\"\n%s",
name, strerror(errno));
return "";
}
fullName = ModelicaAllocateString(strlen(tempName));
strcpy(fullName, tempName);
ModelicaConvertToUnixDirectorySeparator(fullName);
#else
/* No such system call in _POSIX_ available */
char* cwd = getcwd(buffer, sizeof(buffer));
if (cwd == NULL) {
ModelicaFormatError("Not possible to get current working directory:\n%s",
strerror(errno));
}
fullName = ModelicaAllocateString(strlen(cwd) + strlen(name) + 1);
strcpy(fullName, cwd);
strcat(fullName, "/");
strcat(fullName, name);
#endif
return fullName;
}
static const char* ModelicaInternal_temporaryFileName()
{
/* Get full path name of a temporary */
char* fullName;
char* tempName = tmpnam(NULL);
if (tempName == NULL) {
ModelicaFormatError("Not possible to get temporary filename\n%s", strerror(errno));
return "";
}
fullName = ModelicaAllocateString(strlen(tempName));
strcpy(fullName, tempName);
ModelicaConvertToUnixDirectorySeparator(fullName);
return fullName;
}
/* --------------------- Abstract data type for stream handles --------------------- */
/* Needs to be improved for cashing of the open files */
static FILE* ModelicaStreams_openFileForReading(const char* fileName) {
/* Open text file for reading */
FILE* fp;
/* Open file */
fp = fopen(fileName, "r");
if ( fp == NULL ) {
ModelicaFormatError("Not possible to open file \"%s\" for reading:\n"
"%s\n", fileName, strerror(errno));
}
return fp;
}
static FILE* ModelicaStreams_openFileForWriting(const char* fileName) {
/* Open text file for writing (with append) */
FILE* fp;
/* Check fileName */
if ( strlen(fileName) == 0 ) {
ModelicaError("fileName is an empty string.\n"
"Opening of file is aborted\n");
}
/* Open file */
fp = fopen(fileName, "a");
if ( fp == NULL ) {
ModelicaFormatError("Not possible to open file \"%s\" for writing:\n"
"%s\n", fileName, strerror(errno));
}
return fp;
}
static void ModelicaStreams_closeFile(const char* fileName) {
/* close file */
}
/* --------------------- Modelica_Utilities.Streams ----------------------------------- */
static void ModelicaInternal_print(const char* string, const char* fileName) {
/* Write string to terminal or to file */
if ( fileName[0] == '\0' ) {
/* Write string to terminal */
ModelicaMessage(string);
} else {
/* Write string to file */
FILE* fp = ModelicaStreams_openFileForWriting(fileName);
if ( fputs(string,fp) < 0 ) goto ERROR;
if ( fputs("\n",fp) < 0 ) goto ERROR;
fclose(fp);
return;
ERROR: fclose(fp);
ModelicaFormatError("Error when writing string to file \"%s\":\n"
"%s\n", fileName, strerror(errno));
}
}
static int ModelicaInternal_countLines(const char* fileName)
/* Get number of lines of a file */
{
int c;
int nLines = 0;
int start_of_line = 1;
/* If true, next character starts a new line. */
FILE* fp = ModelicaStreams_openFileForReading(fileName);
/* Count number of lines */
while ((c = fgetc(fp)) != EOF) {
if (start_of_line) {
nLines++;
start_of_line = 0;
}
if (c == '\n') start_of_line = 1;
}
fclose(fp);
return nLines;
}
static void ModelicaInternal_readFile(const char* fileName, const char* string[], size_t nLines) {
/* Read file into string vector string[nLines] */
FILE* fp = ModelicaStreams_openFileForReading(fileName);
char* line;
int c;
size_t lineLen;
size_t iLines;
long offset;
size_t nc;
/* Read data from file */
iLines = 1;
while ( iLines <= nLines ) {
/* Determine length of next line */
offset = ftell(fp);
lineLen = 0;
c = fgetc(fp);
while ( c != '\n' && c != EOF ) {
lineLen++;
c = fgetc(fp);
}
/* Allocate storage for next line */
line = ModelicaAllocateStringWithErrorReturn(lineLen);
if ( line == NULL ) {
fclose(fp);
ModelicaFormatError("Not enough memory to allocate string for reading line %i from file\n"
"\"%s\".\n"
"(this file contains %i lines)\n", iLines, fileName, nLines);
}
/* Read next line */
if ( fseek(fp, offset, SEEK_SET != 0) ) {
fclose(fp);
ModelicaFormatError("Error when reading line %i from file\n\"%s\":\n"
"%s\n", iLines, fileName, strerror(errno));
};
nc = ( iLines < nLines ? lineLen+1 : lineLen);
if ( fread(line, sizeof(char), nc, fp) != nc ) {
fclose(fp);
ModelicaFormatError("Error when reading line %i from file\n\"%s\"\n",
iLines, fileName);
};
line[lineLen] = '\0';
string[iLines-1] = line;
iLines++;
}
fclose(fp);
}
static const char* ModelicaInternal_readLine(const char* fileName, int lineNumber, int* endOfFile) {
/* Read line lineNumber from file fileName */
FILE* fp = ModelicaStreams_openFileForReading(fileName);
char* line;
int c;
size_t lineLen;
size_t iLines;
long offset;
/* Read upto line lineNumber-1 */
iLines = 0;
c = 1;
while ( iLines != (size_t) lineNumber-1 && c != EOF ) {
c = fgetc(fp);
while ( c != '\n' && c != EOF ) {
c = fgetc(fp);
}
iLines++;
}
if ( iLines != (size_t) lineNumber-1 ) goto END_OF_FILE;
/* Determine length of line lineNumber */
offset = ftell(fp);
lineLen = 0;
c = fgetc(fp);
while ( c != '\n' && c != EOF ) {
lineLen++;
c = fgetc(fp);
}
if ( lineLen == 0 && c == EOF ) goto END_OF_FILE;
/* Read line lineNumber */
line = ModelicaAllocateStringWithErrorReturn(lineLen);
if ( line == NULL ) goto ERROR;
if ( fseek(fp, offset, SEEK_SET != 0) ) goto ERROR;
if ( fread(line, sizeof(char), lineLen, fp) != lineLen ) goto ERROR;
fclose(fp);
line[lineLen] = '\0';
*endOfFile = 0;
return line;
/* End-of-File or error */
END_OF_FILE: fclose(fp);
*endOfFile = 1;
line = ModelicaAllocateString(0);
return line;
ERROR : fclose(fp);
ModelicaFormatError("Error when reading line %i from file\n\"%s\":\n%s",
lineNumber, fileName, strerror(errno));
return "";
}
/* --------------------- Modelica_Utilities.System ------------------------------------ */
static void ModelicaInternal_chdir(const char* directoryName)
{
/* Change current working directory. */
#if defined(__WATCOMC__)
int result = chdir(directoryName);
#elif defined(_WIN32) && !defined(SimStruct)
int result = _chdir(directoryName);
#elif defined(_POSIX_)
int result = chdir(directoryName);
#else
int result = -1;
ModelicaNotExistError("ModelicaInternal_chdir");
#endif
if (result != 0) {
ModelicaFormatError("Not possible to change current working directory to\n"
"\"%s\":\n%s", directoryName, strerror(errno));
}
}
static const char* ModelicaInternal_getcwd(int dummy)
{
const char* cwd;
char* directory;
#if defined(_WIN32)
cwd = _getcwd(buffer, sizeof(buffer));
#elif defined(_POSIX_)
cwd = getcwd(buffer, sizeof(buffer));
#else
ModelicaNotExistError("ModelicaInternal_getcwd");
cwd = "";
#endif
if (cwd == NULL) {
ModelicaFormatError("Not possible to get current working directory:\n%s",
strerror(errno));
cwd = "";
}
directory = ModelicaAllocateString(strlen(cwd));
strcpy(directory, cwd);
ModelicaConvertToUnixDirectorySeparator(directory);
return directory;
}
static const char* ModelicaInternal_getenv(const char* name, int convertToSlash, int* exist)
{
/* Get content of environment variable */
char* value = getenv(name);
char* result;
if (value == NULL) {
result = ModelicaAllocateString(0);
result[0] = '\0';
*exist = 0;
} else {
result = ModelicaAllocateString(strlen(value));
strcpy(result, value);
if ( convertToSlash == 1 ) ModelicaConvertToUnixDirectorySeparator(result);
*exist = 1;
}
return result;
}
static void ModelicaInternal_setenv(const char* name, const char* value, int convertFromSlash)
{
#if defined(_WIN32) || defined(_POSIX_)
int valueStart;
if (strlen(name) + strlen(value) + 1 > sizeof(buffer)) {
ModelicaFormatError("Environment variable\n"
"\"%s\"=\"%s\"\n"
"cannot be set, because the internal buffer\n"
"in file \"ModelicaInternal.c\" is too small (= %d)",
name, value, sizeof(buffer));
}
strcpy(buffer,name);
strcat(buffer, "=");
valueStart = strlen(buffer);
strcat(buffer, value);
if ( convertFromSlash == 1 ) ModelicaConvertFromUnixDirectorySeparator(&buffer[valueStart]);
#endif
/* Set environment variable */
#if defined(_WIN32)
if (_putenv(buffer) != 0) {
ModelicaFormatError("Environment variable\n"
"\"%s\"=\"%s\"\n"
"cannot be set: %s", name, value, strerror(errno));
}
#elif defined(_POSIX_)
if (putenv(buffer) != 0) {
ModelicaFormatError("Environment variable\n"
"\"%s\"=\"%s\"\n"
"cannot be set: %s", name, value, strerror(errno));
}
#else
ModelicaNotExistError("ModelicaInternal_setenv");
#endif
}
#endif
| pombredanne/metamorphosys-desktop | metamorphosys/META/analysis_tools/FAME/MSL/3.2/Modelica/Resources/C-Sources/ModelicaInternal.c | C | mit | 25,865 |
/*
Created on : 3 Sep, 2015, 6:57:21 AM
Author : Design_mylife
Template : Assan - Multipurpose template
Version : v1.9
*/
/**google fonts **/
@import url(https://fonts.googleapis.com/css?family=Montserrat:400,700);
@import url(https://fonts.googleapis.com/css?family=Josefin+Sans:400,700);
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600);
/**variables for one page template**/
/***Base*****/
html, body {
height: 100%;
}
body {
font-family: "Roboto", sans-serif;
line-height: 26px;
color: #4D4D4D;
font-weight: 400;
font-size: 13px;
-webkit-font-smoothing: antialiased;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
/* overflow-x: hidden;*/
}
h1, h2, h3, h4, h5, h6 {
margin-top: 0px;
font-family: "Montserrat", sans-serif;
}
a {
text-decoration: none;
-moz-transition: 0.3s;
-o-transition: 0.3s;
-webkit-transition: 0.3s;
transition: 0.3s;
color: #32c5d2;
}
a:hover, a:focus, button:focus, .btn, button {
border: 0px;
outline: 0 !important;
text-decoration: none;
color: #aeaeae;
}
.margin-b-10 {
margin-bottom: 10px;
}
.margin-b-20 {
margin-bottom: 20px;
}
.margin-b-30 {
margin-bottom: 20px;
}
.space-20 {
height: 20px;
width: 100%;
}
.space-30 {
height: 30px;
width: 100%;
}
.space-40 {
height: 40px;
width: 100%;
}
.space-50 {
height: 50px;
width: 100%;
}
.colored-text {
color: #32c5d2;
}
/***
buttons
***/
.btn {
font-family: "Montserrat", sans-serif;
text-transform: uppercase;
font-weight: 400;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
border-radius: 0px;
font-size: 13px;
-moz-transition: all 0.4s;
-o-transition: all 0.4s;
-webkit-transition: all 0.4s;
transition: all 0.4s;
}
.btn i {
margin-left: 6px;
}
.btn-lg {
font-size: 14px;
padding: 12px 25px;
}
.btn-radius {
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
border-radius: 30px;
}
.btn-primary {
background-color: #32c5d2;
color: #fff;
}
.btn-primary:hover, .btn-primary:focus {
background-color: #333;
color: #fff;
}
.btn-white-border {
background-color: transparent;
border: 2px solid #fff;
color: #fff;
}
.btn-white-border:hover, .btn-white-border:focus {
color: #333;
background-color: #fff;
border: 2px solid #fff;
}
.btn-default {
border: 1px solid #eee;
color: #777;
}
.btn-default:hover, .btn-default:focus {
background-color: #333;
color: #fff;
border: 1px solid #333;
}
/**center title**/
.center-title {
padding-bottom: 40px;
text-align: center;
}
.center-title h3 {
text-transform: uppercase;
font-weight: 700;
color: #000;
font-size: 36px;
line-height: 40px;
letter-spacing: -1px;
}
.center-title p {
font-family: "Josefin Sans", sans-serif;
font-weight: 700;
text-transform: uppercase;
margin-bottom: 0px;
}
.center-title .center-line {
width: 40px;
height: 3px;
display: block;
background-color: #32c5d2;
margin: 0 auto;
margin-bottom: 5px;
}
/****progress bars****/
/*progress bar*/
h3.heading-progress {
font-size: 12px;
font-weight: 400;
margin-bottom: 6px;
margin-top: 10px;
text-transform: uppercase;
color: #777;
}
.progress {
height: 5px;
line-height: 5px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
box-shadow: none;
background: #E9E9E9;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-ms-border-radius: 0;
border-radius: 0;
}
.progress-bar {
line-height: 5px;
background: #32c5d2;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
box-shadow: none;
}
/*******************
Navigation main
********************/
.navbar-default {
background-color: #fff;
border: 0px;
border-bottom: 2px solid #f5f5f5;
padding: 10px 0;
z-index: 9999 !important;
margin-bottom: 0px;
width: 100%;
-moz-transition: all 0.4s;
-o-transition: all 0.4s;
-webkit-transition: all 0.4s;
transition: all 0.4s;
}
.navbar-default .navbar-nav > li > a {
color: #333;
font-family: "Montserrat", sans-serif;
text-transform: uppercase;
font-weight: 600;
font-size: 13px;
}
.navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:focus, .navbar-default .navbar-nav > .open > a:hover {
color: #32c5d2;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:focus, .navbar-default .navbar-nav > .active > a:hover {
color: #32c5d2;
background-color: transparent;
}
/***dropdown***/
.nav > li > span {
position: relative;
display: block;
padding: 10px 15px;
cursor: pointer;
color: #333;
font-family: "Montserrat", sans-serif;
text-transform: uppercase;
font-weight: 600;
margin-top: -3px;
font-size: 13px;
}
.nav > li > span:hover {
color: #32c5d2;
}
@media (min-width: 768px) {
.navbar-nav > li > span {
padding-top: 15px;
padding-bottom: 15px;
}
.nav > li > a, .nav > li > span {
padding-left: 10px;
padding-right: 10px;
}
}
.navbar-right {
margin-right: 40px;
}
/*********
Off canvas menu
*******************/
.side-panel.navbar-toggle {
display: block;
color: #333;
border: 0px;
padding: 0px;
position: relative;
margin-top: -40px;
}
.side-panel.navbar-toggle:hover {
background-color: transparent;
}
.side-panel-inner {
padding: 20px 25px;
}
@media (max-width: 767px) {
.side-panel.navbar-toggle {
right: 40px;
position: absolute;
top: 63px;
font-size: 20px;
}
.navbar-default .navbar-toggle {
border: 0px;
}
}
.navbar-default .side-panel.navbar-toggle:focus, .navbar-default .navbar-toggle:hover {
background-color: transparent;
}
.navmenu-default, .navbar-default .navbar-offcanvas {
background-color: #f5f5f5;
border: 0px;
}
/*****home section****/
.fullwidthbanner .title {
color: #fff;
font-size: 70px;
font-family: "Montserrat", sans-serif;
font-weight: 700;
text-transform: uppercase;
}
.fullwidthbanner .subtitle {
color: #fff;
}
.fullwidthbanner .btn-white-border {
color: #fff;
font-size: 14px;
padding: 12px 30px;
}
.fullwidthbanner .btn-white-border:hover {
color: #333;
border: 2px solid #fff;
}
/**************************
about Section
**************************/
#about {
padding-top: 100px;
padding-bottom: 50px;
background-color: #ffff;
}
.about-quote p {
margin: 0px;
}
.about-quote em {
display: block;
margin: 20px 0;
margin-top: 10px;
color: #32c5d2;
}
.person-col {
overflow: hidden;
position: relative;
}
.person-col img {
width: 100%;
}
.person-col .person-overlay {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 100%;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
padding: 30px;
-moz-transition: all 0.4s;
-o-transition: all 0.4s;
-webkit-transition: all 0.4s;
transition: all 0.4s;
}
.person-col .person-overlay h3 {
color: #fff;
margin-bottom: 5px;
text-transform: capitalize;
}
.person-col .person-overlay p {
color: #fff;
}
.person-col:hover .person-overlay {
top: 0;
}
/****
NUMBERS
******/
.numbers {
background: url(../img/showcase-5.jpg) no-repeat;
background-attachment: fixed;
background-size: cover;
padding-top: 100px;
padding-bottom: 70px;
position: relative;
overflow: hidden;
width: 100%;
background-position: 0 50%;
}
.numbers h1 {
color: #fff;
margin: 15px 0;
}
.numbers i {
color: #fff;
font-size: 20px;
}
.numbers p {
color: #fff;
margin: 0px;
font-family: "Josefin Sans", sans-serif;
text-transform: uppercase;
font-weight: 400;
}
/**************************
Services Section
**************************/
#services {
padding-top: 100px;
padding-bottom: 50px;
background-color: #f5f5f5;
}
.special-feature .section-title hr {
border-color: #333;
}
.special-feature i {
font-size: 65px;
line-height: 75px;
color: #32c5d2;
}
.special-feature h4 {
font-size: 16px;
margin-top: 25px;
position: relative;
text-transform: uppercase;
font-weight: 700;
color: #777;
}
.special-feature .mask-top {
width: 100%;
background-color: #fff;
padding: 55px 0;
position: absolute;
top: 0px;
-moz-transition: all 0.3s ease-out 0s;
-o-transition: all 0.3s ease-out 0s;
-webkit-transition: all 0.3s ease-out 0s;
transition: all 0.3s ease-out 0s;
}
.special-feature .mask-top h4:before {
top: -18px;
content: "";
display: block;
height: 2px;
left: 0;
right: 0;
margin: -2px auto;
position: absolute;
width: 40px;
}
.special-feature .s-feature-box:hover .mask-top {
top: -200px;
-moz-transition: all 0.3s ease-out 0s;
-o-transition: all 0.3s ease-out 0s;
-webkit-transition: all 0.3s ease-out 0s;
transition: all 0.3s ease-out 0s;
}
.special-feature .s-feature-box {
overflow: hidden;
position: relative;
height: 280px;
background-color: #fff;
margin-bottom: 20px;
cursor: pointer;
}
.special-feature .mask-bottom {
color: #333333;
padding: 20px 15px 20px 15px;
background-color: #fff;
width: 100%;
position: absolute;
bottom: -300px;
height: 100%;
-moz-transition: all 0.3s ease-out 0s;
-o-transition: all 0.3s ease-out 0s;
-webkit-transition: all 0.3s ease-out 0s;
transition: all 0.3s ease-out 0s;
}
.special-feature .mask-bottom p {
padding: 0px 5px;
font-size: 13px;
}
.special-feature .mask-bottom h4 {
margin: 15px 0px 17px;
}
.special-feature .s-feature-box:hover .mask-bottom {
bottom: 0;
-moz-transition: all 0.3s ease-out 0s;
-o-transition: all 0.3s ease-out 0s;
-webkit-transition: all 0.3s ease-out 0s;
transition: all 0.3s ease-out 0s;
}
.special-feature .mask-bottom i {
font-size: 38px;
line-height: 50px;
}
/****************
SOCIAL BUTTONS
**********************/
/**social icons default size**/
.social-icon {
margin: 0 5px 5px 0;
width: 40px;
height: 40px;
font-size: 20px;
line-height: 40px !important;
color: #555;
text-shadow: none;
border-radius: 3px;
overflow: hidden;
display: inline-block;
text-align: center;
border: 1px solid #AAA;
}
.social-icon:hover {
border-color: transparent;
}
.social-icon i {
display: block;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
line-height: 40px;
position: relative;
}
.social-icon i:last-child {
color: #FFF !important;
}
.social-icon:hover i:first-child {
margin-top: -40px;
}
/***social icons lg (big)***/
.social-icon-lg {
margin: 0 5px 5px 0;
width: 60px;
height: 60px;
font-size: 30px;
line-height: 60px !important;
color: #555;
text-shadow: none;
border-radius: 3px;
overflow: hidden;
display: inline-block;
text-align: center;
border: 1px solid #AAA;
}
.social-icon-lg:hover {
border-color: transparent;
}
.social-icon-lg i {
display: block;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
line-height: 60px;
position: relative;
}
.social-icon-lg i:last-child {
color: #FFF !important;
}
.social-icon-lg:hover i:first-child {
margin-top: -60px;
}
/***social icons small***/
.social-icon-sm {
margin: 0 5px 5px 0;
width: 30px;
height: 30px;
font-size: 18px;
line-height: 30px !important;
color: #555;
text-shadow: none;
border-radius: 3px;
overflow: hidden;
display: inline-block;
text-align: center;
border: 1px solid #AAA;
}
.social-icon-sm:hover {
border-color: transparent;
}
.social-icon-sm i {
display: block;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
line-height: 30px;
position: relative;
}
.social-icon-sm i:last-child {
color: #FFF !important;
}
.social-icon-sm:hover i:first-child {
margin-top: -30px;
}
si-border {
border: 1px solid #AAA !important;
}
.si-border-round {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
}
.si-dark-round {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
}
.si-gray-round {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
}
.si-gray {
background: #f3f3f3;
border: 0px;
}
.si-dark {
background-color: #333;
border: 0px !important;
color: #fff !important;
}
/**icons hover colored**/
.si-colored-facebook, .si-facebook:hover {
background-color: #3B5998 !important;
}
.si-colored-twitter, .si-twitter:hover {
background-color: #00ACEE !important;
}
.si-colored-google-plus, .si-g-plus:hover {
background-color: #DD4B39 !important;
}
.si-colored-skype, .si-skype:hover {
background-color: #00AFF0 !important;
}
.si-linkedin:hover, .si-colored-linkedin {
background-color: #0E76A8 !important;
}
.si-pin:hover, .si-colored-pinterest {
background-color: #C8232C !important;
}
.si-rss:hover, .si-colored-rss {
background-color: #EE802F !important;
}
.si-pinterest:hover, .si-colored-pinterest {
background-color: #C8232C !important;
}
.si-tumblr:hover, .si-colored-tumblr {
background-color: #34526F !important;
}
.si-vimeo:hover, .si-colored-vimeo {
background-color: #86C9EF !important;
}
.si-digg:hover, .si-colored-digg {
background-color: #191919 !important;
}
.si-instagram:hover, .si-colored-instagram {
background-color: #3F729B !important;
}
.si-flickr:hover, .si-colored-flickr {
background-color: #FF0084 !important;
}
.si-paypal:hover, .si-colored-paypal {
background-color: #00588B !important;
}
.si-yahoo:hover, .si-colored-yahoo {
background-color: #720E9E !important;
}
.si-android:hover, .si-colored-andriod {
background-color: #A4C639 !important;
}
.si-appstore:hover, .si-colored-apple {
background-color: #000 !important;
}
.si-dropbox:hover {
background-color: #3D9AE8 !important;
}
.si-dribbble:hover, .si-colored-dribbble {
background-color: #EA4C89 !important;
}
.si-soundcloud:hover, .si-colored-soundcoloud {
background-color: #F70 !important;
}
.si-xing:hover, .si-colored-xing {
background-color: #126567 !important;
}
.si-phone:hover, .si-colored-phone {
background-color: #444 !important;
}
.si-behance:hover, .si-colored-behance {
background-color: #053eff !important;
}
.si-github:hover, .si-colored-github {
background-color: #171515 !important;
}
.si-stumbleupon:hover, .si-colored-stumbleupon {
background-color: #F74425 !important;
}
.si-email:hover, .si-colored-email {
background-color: #6567A5 !important;
}
.si-wordpress:hover, .si-colored-wordpress {
background-color: #1E8CBE !important;
}
/******
Portfolio
*******/
#work {
padding-top: 100px;
padding-bottom: 70px;
}
.cbp-popup-wrap {
z-index: 9999;
}
.cbp-l-grid-projects-title {
font-family: "Montserrat", sans-serif;
text-transform: uppercase;
}
.cbp-l-grid-projects-desc {
font-family: "Roboto", sans-serif;
}
.cbp-l-caption-buttonLeft, .cbp-l-caption-buttonRight {
font-family: "Montserrat", sans-serif;
text-transform: uppercase;
background-color: #32c5d2;
font-weight: 400;
-moz-transition: all 0.3s;
-o-transition: all 0.3s;
-webkit-transition: all 0.3s;
transition: all 0.3s;
}
.cbp-l-caption-buttonLeft:hover, .cbp-l-caption-buttonRight:hover {
background-color: #333;
}
.cbp-popup-singlePage .cbp-popup-navigation-wrap {
background-color: #333;
}
.cbp-l-project-details-visit {
background-color: #32c5d2;
text-transform: uppercase;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
border-radius: 4px;
font-family: "Montserrat", sans-serif;
}
.cbp-l-project-desc-title span, .cbp-l-project-details-title span {
font-family: "Montserrat", sans-serif;
}
.cbp-l-project-details-list > li, .cbp-l-project-details-list > div {
font-family: "Roboto", sans-serif;
}
.cbp-l-project-desc-text {
font-family: "Roboto", sans-serif;
}
.cbp-l-filters-button .cbp-filter-item {
font-family: "Roboto", sans-serif;
}
.cbp-l-project-title {
font-family: "Montserrat", sans-serif;
}
.cbp-l-project-subtitle {
font-family: "Roboto", sans-serif;
}
/***
Contact section
**/
#contact {
padding-top: 100px;
padding-bottom: 70px;
}
#contact h3 {
margin-bottom: 25px;
}
.contact-form label {
font-family: "Josefin Sans", sans-serif;
color: #666;
text-transform: uppercase;
}
.contact-form .form-control {
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
border-radius: 0px;
min-height: 45px;
border: 2px solid #f4f4f4;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
box-shadow: none;
font-weight: 400;
font-size: 13px;
}
.contact-form .help-block {
margin: 0px;
}
.contact-form .help-block ul {
list-style: none;
margin: 0px;
padding: 0px;
}
.contact-form .help-block ul li {
display: block;
margin-top: 10px;
padding: 2px 10px;
font-size: 12px;
font-weight: 400;
border-left: 1px solid red;
color: red;
line-height: 10px;
}
.contact-info .media {
margin-bottom: 30px;
}
.contact-info .media-heading {
text-transform: uppercase;
font-size: 13px;
font-weight: 400;
}
.contact-info i {
width: 50px;
height: 50px;
line-height: 50px;
display: block;
text-align: center;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
background-color: #32c5d2;
font-size: 20px;
color: #fff;
margin-right: 15px;
}
/******Footer******/
.footer {
padding: 40px 0;
padding-bottom: 20px;
background-color: #eee;
border-top: 5px solid #f5f5f5;
}
.footer h3 {
text-transform: uppercase;
font-weight: 700;
font-size: 16px;
color: #333;
margin-bottom: 25px;
}
.footer .latest-f-news li a {
color: #777;
}
.footer .latest-f-news li a:hover {
color: #32c5d2;
}
.footer .footer-btm {
color: #777;
padding-top: 20px;
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-top: 40px;
}
.assan-newsletter input[type="text"] {
height: 40px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
box-shadow: none;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
border-radius: 0px;
font-size: 12px;
font-weight: 400;
}
.assan-newsletter input[type="submit"] {
float: right;
margin-top: 8px;
}
/***testimonials**/
.testimonials {
padding: 80px 0;
background-color: #eee;
overflow: hidden;
}
.testimonials .testi-slide img {
margin-bottom: 20px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
}
.testimonials .testi-slide h4 {
font-family: "Roboto", sans-serif;
font-size: 15px;
color: #32c5d2;
}
.testimonials .testi-slide .flex-control-paging li a {
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
border-radius: 0px;
}
.testimonials .testi-slide .flex-control-paging li a.flex-active {
background: #32c5d2;
}
/******************pricing tables***********************/
.pricing-tables {
padding: 70px 0;
padding-bottom: 40px;
}
/**pricing simple **/
.pricing-simple {
border: 1px solid #D0D6DF;
margin-bottom: 30px;
}
.pricing-simple h4 {
border-bottom: 1px solid #D0D6DF;
margin: 0px;
color: #666;
padding: 20px;
font-size: 20px;
text-align: center;
font-weight: 600;
text-transform: capitalize;
}
.pricing-simple h3 {
margin: 0px;
padding: 30px 20px;
border-bottom: 1px solid #D0D6DF;
font-size: 50px;
font-weight: 300;
text-align: center;
background-color: #f4f4f4;
}
.pricing-simple h3 sup, .pricing-simple h3 sub {
font-size: 13px;
color: #D0D6DF;
font-weight: 400;
}
.pricing-simple h3 sup {
vertical-align: top;
left: 10px;
}
.pricing-simple h3 sub {
vertical-align: bottom;
}
.pricing-simple ul {
padding-top: 30px;
}
.pricing-simple ul li {
padding: 6px 20px;
border-bottom: 1px solid #f5f5f5;
color: #aeaeae;
}
.pricing-simple ul li:last-child {
border-bottom: 0px;
}
.pricing-simple ul li i {
color: #32c5d2;
margin-right: 10px;
}
.pricing-simple .bottom {
padding: 20px 10px;
text-align: center;
}
.pricing-simple p {
color: #aeaeae;
padding: 15px 20px;
text-align: center;
padding-bottom: 0px;
}
.pricing-simple .circle {
width: 150px;
height: 150px;
padding: 0px 0 0;
margin: 30px auto;
margin-bottom: 0px;
display: table;
-webkit-box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.5);
-ms-box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.5);
border: 5px solid #fff;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
background-color: #f4f4f4;
}
.pricing-simple .circle .price {
text-align: center;
font-size: 30px;
display: table-cell;
vertical-align: middle;
}
.pricing-simple .circle .price sub, .pricing-simple .circle .price sup {
font-size: 13px;
color: #777;
}
.pricing-simple .circle .price sup {
vertical-align: top;
}
.pricing-simple .circle .price sub {
vertical-align: bottom;
}
.popular {
position: relative;
overflow: hidden;
}
.popular .ribbon {
position: absolute;
left: -55px;
bottom: 5px;
font-size: 11px;
text-align: center;
width: 150px;
color: #fff;
text-transform: capitalize;
padding: 1px 12px;
display: block;
-webkit-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.2);
-ms-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.2);
box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.2);
background-color: #32c5d2;
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
.no-space-pricing {
margin: 0px;
}
/**dark pricing tables**/
.pricing-simple.dark-pricing {
border: 1px solid rgba(0, 0, 0, 0.1);
background-color: #333;
}
.pricing-simple.dark-pricing h4 {
border-color: rgba(255, 255, 255, 0.1);
color: #fff;
}
.pricing-simple.dark-pricing .circle {
background-color: #444;
border-color: #333;
}
.pricing-simple.dark-pricing .circle .price {
color: #fff;
}
.pricing-simple.dark-pricing ul li {
border-bottom-color: rgba(255, 255, 255, 0.1);
}
/****blog section****/
.blog {
padding-top: 100px;
padding-bottom: 70px;
background-color: #f4f4f4;
}
.blog .item {
background-color: #fff;
padding: 15px;
margin: 0px 15px;
text-align: center;
}
.news-col img {
width: 100%;
margin-bottom: 15px;
}
.news-col h3 {
font-size: 15px;
font-weight: 400;
}
.news-col h3 a {
color: #000;
text-transform: uppercase;
}
.news-col h3 a:hover {
color: #32c5d2;
}
.news-col ul li {
font-size: 12px;
}
.news-col ul li i {
margin-right: 5px;
}
.news-col p {
margin-bottom: 20px;
}
.owl-theme .owl-controls .owl-buttons div {
padding: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
border-radius: 0px;
background-color: transparent;
font-size: 30px;
color: #32c5d2;
}
/**back to top**/
#back-to-top a {
display: block;
z-index: 500;
width: 40px;
height: 40px;
text-align: center;
font-size: 22px;
position: fixed;
bottom: -40px;
right: 20px;
color: #fff;
line-height: 35px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
background-color: #32c5d2;
}
#back-to-top.show a {
bottom: 20px;
}
/**process***/
.process {
background: url(../img/showcase-4.jpg) no-repeat;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
padding-top: 150px;
padding-bottom: 120px;
}
.process .process-col {
margin-bottom: 30px;
text-align: center;
}
.process .center-title p, .process .center-title h3 {
color: #fff;
}
.process .center-line {
background-color: #fff;
}
.process i {
display: block;
margin: 0 auto;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-size: 50px;
color: #fff;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
border-radius: 50%;
border: 1px dashed #fff;
}
.process h4 {
font-weight: 400;
color: #fff;
text-transform: uppercase;
margin-bottom: 0px;
margin-top: 15px;
}
/**cta**/
.call-to-action {
background: url(../img/showcase-4.jpg) no-repeat;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
padding-top: 150px;
padding-bottom: 150px;
}
.call-to-action h1 {
color: #fff;
text-transform: uppercase;
}
.call-to-action .subtitle {
color: #fff;
font-size: 18px;
margin-bottom: 20px;
font-family: "Josefin Sans", sans-serif;
}
/***self hosted video css***/
/**video css new**/
.video-section {
width: 100%;
height: 100%;
position: relative;
display: table;
overflow: hidden;
}
.video-section .overlay {
background-color: rgba(0, 0, 0, 0.6);
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
}
.video-section .fs-background-container {
left: 0;
}
.video-section .video-overlay {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
z-index: 2;
}
.video-section .video-overlay h1 {
font-weight: 700;
color: #fff;
font-size: 70px;
line-height: 70px;
margin-bottom: 0px;
text-transform: capitalize;
}
.video-section .video-overlay p {
color: #fff;
margin-bottom: 25px;
margin-top: 20px;
}
@media (max-width: 767px) {
.process, .numbers, .call-to-action {
background-attachment: scroll !important;
background-size: cover !important;
background-position: center center !important;
}
}
| pangru/church-omania | templates/assan-v2.6/one-page/css/one-page.css | CSS | mit | 25,862 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.1.4: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.1.4
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_string.html">String</a></li><li class="navelem"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">ExternalAsciiStringResource</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::String::ExternalAsciiStringResource Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html#adeb99e8c8c630e2dac5ad76476249d2f">data</a>() const =0</td><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ExternalAsciiStringResource</b>() (defined in <a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a>)</td><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html#aeecccc52434c2057d3dc5c9732458a8e">length</a>() const =0</td><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html#acd8790ae14be1b90794b363d24a147d0">~ExternalAsciiStringResource</a>()</td><td class="entry"><a class="el" href="classv8_1_1_string_1_1_external_ascii_string_resource.html">v8::String::ExternalAsciiStringResource</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:44:35 for V8 API Reference Guide for node.js v0.1.4 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| v8-dox/v8-dox.github.io | 9dc621f/html/classv8_1_1_string_1_1_external_ascii_string_resource-members.html | HTML | mit | 6,327 |
//
// LeftTableViewController.h
// WangYiNEWS
//
// Created by lanou3g on 15/11/22.
// Copyright © 2015年 lanou3g. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface LeftTableViewController : UITableViewController
@end
| gavinqqq/WANGYiNEWS | WangYiNEWS/Classes/General/ViewControllers/LeftTableViewController.h | C | mit | 236 |
<?php
namespace EloquentJs\ScriptGenerator\Model;
class Metadata
{
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $endpoint;
/**
* @var array
*/
public $dates;
/**
* @var array
*/
public $scopes;
/**
* @var array
*/
public $relations;
/**
* @param string $name
* @param string $endpoint
* @param array $dates
* @param array $scopes
*/
public function __construct($name, $endpoint, array $dates = [], array $scopes = [], array $relations = [])
{
$this->name = $name;
$this->endpoint = $endpoint;
$this->dates = $dates;
$this->scopes = $scopes;
$this->relations = $relations;
}
}
| parsnick/eloquentjs | src/ScriptGenerator/Model/Metadata.php | PHP | mit | 772 |
/*------------------------------------------------------------------
Bootstrap Admin Template by EGrappler.com
------------------------------------------------------------------*/
/*------------------------------------------------------------------
[1. Global]
*/
body {
background: #f9f6f1;
font: 13px/1.7em 'Open Sans';
}
p {
font: 13px/1.7em 'Open Sans';
}
input,
button,
select,
textarea {
font-family: 'Open Sans';
}
h5 {
padding-left:10px;
padding-top:10px;
}
.dropdown .dropdown-menu {
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
.btn-icon-only {
padding-right: 3px;
padding-left: 3px;
}
.table td {
vertical-align: middle;
}
.table-bordered th {
background: #E9E9E9;
background:-moz-linear-gradient(top, #FAFAFA 0%, #E9E9E9 100%); /* FF3.6+ */
background:-webkit-gradient(linear, left top, left bottom, color-stop(0%,#FAFAFA), color-stop(100%,#E9E9E9)); /* Chrome,Safari4+ */
background:-webkit-linear-gradient(top, #FAFAFA 0%,#E9E9E9 100%); /* Chrome10+,Safari5.1+ */
background:-o-linear-gradient(top, #FAFAFA 0%,#E9E9E9 100%); /* Opera11.10+ */
background:-ms-linear-gradient(top, #FAFAFA 0%,#E9E9E9 100%); /* IE10+ */
background:linear-gradient(top, #FAFAFA 0%,#E9E9E9 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FAFAFA', endColorstr='#E9E9E9');
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#FAFAFA', endColorstr='#E9E9E9')";
font-size: 10px;
color: #444;
text-transform: uppercase;
}
/*------------------------------------------------------------------
[2. Navbar / .navbar]
*/
.navbar .container {
position: relative;
border:none;
}
.navbar-inner {
padding: 7px 0;
margin-bottom:15px;
background: transparent !important;
border:none;
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
}
.navbar-fixed-top {
position: static;
border:none;
}
.nav-collapse {
margin-top:7px;
}
.navbar .nav a {
font-size: 11px;
}
.navbar .nav>li>a { color:#444 !important;font-size:14px;}
.navbar .brand {
font-weight: 900;
position: relative;
color:#444;
font-size:24px;
font: 27px 'Open Sans';
}
.navbar .search-query {
background-color: #444;
width: 150px;
font-size: 11px;
font-weight: bold;
}
.navbar .search-query::-webkit-input-placeholder {
color: #666;
}
.navbar .search-query:-moz-placeholder {
color: #666;
}
.navbar-search .search-query { background:#008866; border:0; color:#fff; line-height:normal;}
/*------------------------------------------------------------------
[3. Subnavbar / .subnavbar]
*/
.subnavbar {
margin-bottom: 2.5em;
}
.subnavbar-inner {
height: 60px;
background: #fff;
}
.subnavbar .container > ul {
display: inline-block;
height: 80px;
padding: 0;
margin: 0;
}
.subnavbar .container > ul > li {
float: left;
min-width: 90px;
height: 60px;
padding: 0;
margin: 0;
text-align: center;
list-style: none;
border-left: 1px solid #d9d9d9;
}
.subnavbar .container > ul > li > a {
display: block;
height: 100%;
padding: 0 15px;
font-size: 12px;
font-weight: bold;
color: #b2afaa;
}
.subnavbar .container > ul > li > a:hover {
color: #888;
text-decoration: none;
}
.subnavbar .container > ul > li > a > i {
display: inline-block;
width: 24px;
height: 24px;
margin-top: 11px;
margin-bottom: -3px;
font-size: 20px;
}
.subnavbar .container > ul > li > a > span {
display: block;
}
.subnavbar .container > ul > li.active > a {
color: #383838;
}
.subnavbar .dropdown .dropdown-menu a {
font-size: 12px;
}
.subnavbar .dropdown .dropdown-menu {
text-align: left;
-webkit-border-top-left-radius: 0;
-webkit-border-top-right-radius: 0;
-moz-border-radius-topleft: 0;
-moz-border-radius-topright: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.subnavbar .dropdown-menu::before {
content: '';
display: inline-block;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid #CCC;
border-bottom-color: rgba(0, 0, 0, 0.2);
position: absolute;
top: -7px;
left: 9px;
}
.subnavbar .dropdown-menu::after {
content: '';
display: inline-block;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid white;
position: absolute;
top: -6px;
left: 10px;
}
.subnavbar .caret {
margin-top: 4px;
border-top-color: white;
border-bottom-color: white;
}
.subnavbar .dropdown.open .caret {
display: none;
}
/*------------------------------------------------------------------
[4. Main / .main]
*/
.main {
padding-bottom: 2em;
}
/*------------------------------------------------------------------
[5. Extra / .extra]
*/
.extra {
border-top: 1px solid #585858;
border-bottom: 1px solid #000;
}
.extra-inner {
padding: 20px 0;
font-size: 11px;
color: #BBB;
background: #1A1A1A;
}
.extra a {
color: #666;
}
.extra h4 {
margin-bottom: 1em;
font-weight: 400;
}
.extra ul {
padding: 0;
margin: 0;
}
.extra li {
margin-bottom: .6em;
list-style: none;
}
/*------------------------------------------------------------------
[6. Footer/ .footer]
*/
.footer {
margin-top: 0;
}
.footer-inner {
padding: 5px 0;
float:left;
font-size: 14px;
background: #111;
color: #999;
}
.footer a {
color: #AAA;
}
.footer a:hover {
color: #777;
text-decoration: none;
}
/*------------------------------------------------------------------
[6. Widget / .widget]
*/
.widget {
position: relative;
clear: both;
width: auto;
margin-bottom: 2em;
overflow: hidden;
}
.widget-header {
position: relative;
height: 40px;
line-height: 40px;
background: #24E072;
border: 1px solid #d6d6d6;
-webkit-background-clip: padding-box;
}
.widget-header h3 {
position: relative;
top: 2px;
left: 10px;
display: inline-block;
margin-right: 3em;
font-size: 16px;
font-weight: 800;
color: #FFF;
line-height: 18px;
}
.widget-header [class^="icon-"], .widget-header [class*=" icon-"] {
display: inline-block;
margin-left: 13px;
margin-right: -2px;
font-size: 18px;
color: #FFF;
vertical-align: middle;
}
.widget-content {
padding: 20px 15px 15px;
background: #FFF;
}
.widget-header+.widget-content {
border-top: none;
-webkit-border-top-left-radius: 0;
-webkit-border-top-right-radius: 0;
-moz-border-radius-topleft: 0;
-moz-border-radius-topright: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.widget-nopad .widget-content {
padding: 0;
}
/* Widget Content Clearfix */
.widget-content:before,
.widget-content:after {
content:"";
display:table;
}
.widget-content:after {
clear:both;
}
/* For IE 6/7 (trigger hasLayout) */
.widget-content {
zoom:1;
}
/* Widget Table */
.widget-table .widget-content {
padding: 0;
}
.widget-table .table {
margin-bottom: 0;
border: none;
}
.widget-table .table tr td:first-child {
border-left: none;
}
.widget-table .table tr th:first-child {
border-left: none;
}
/* Widget Plain */
.widget-plain {
background: transparent;
border: none;
}
.widget-plain .widget-content {
padding: 0;
background: transparent;
border: none;
}
/* Widget Box */
.widget-box {
}
.widget-box .widget-content {
background: #E3E3E3;
background: #FFF;
}
/*------------------------------------------------------------------
[7. Error / .error-container]
*/
.error-container {
margin-top: 4em;
margin-bottom: 4em;
text-align: center;
}
.error-container h1 {
margin-bottom: .5em;
font-size: 120px;
line-height: 1em;
}
.error-container h2 {
margin-bottom: .75em;
font-size: 28px;
}
.error-container .error-details {
margin-bottom: 1.5em;
font-size: 16px;
}
.error-container .error-actions a {
margin: 0 .5em;
}
/* Message layout */
ul.messages_layout {
position: relative;
margin: 0;
padding: 0
}
ul.messages_layout li {
float: left;
list-style: none;
position: relative
}
ul.messages_layout li.left {
padding-left: 75px
}
ul.messages_layout li.right {
padding-right: 75px
}
ul.messages_layout li.right .avatar {
right: 0;
left: auto
}
ul.messages_layout li.right .message_wrap .arrow {
right: -12px;
left: auto;
background-position: 0 -213px;
height: 15px;
width: 12px
}
ul.messages_layout li.by_myself .message_wrap {
border: 1px solid #b3cdf8
}
ul.messages_layout li.by_myself .message_wrap .info a.name {
color: #4a8cf7
}
ul.messages_layout li a.avatar {
position: absolute;
left: 0;
top: 0
}
ul.messages_layout li a.avatar img {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px
}
ul.messages_layout li .message_wrap {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
position: relative;
border: 1px solid #e9e9e9;
padding: 10px;
border: 1px solid #cbcbcb;
margin-bottom: 20px;
float: left;
background: #fefefe;
-webkit-box-shadow: rgba(0,0,0,0.1) 0 1px 0px;
-moz-box-shadow: rgba(0,0,0,0.1) 0 1px 0px;
box-shadow: rgba(0,0,0,0.1) 0 1px 0px
}
ul.messages_layout li .message_wrap .arrow {
background-position: 0 -228px;
height: 15px;
width: 12px;
height: 15px;
width: 12px;
position: absolute;
left: -12px;
top: 13px
}
ul.messages_layout li .message_wrap .info {
float: left;
width: 100%;
border-bottom: 1px solid #fff;
line-height: 23px
}
ul.messages_layout li .message_wrap .info .name {
float: left;
font-weight: bold;
color: #483734
}
ul.messages_layout li .message_wrap .info .time {
float: left;
font-size: 11px;
margin-left: 6px
}
ul.messages_layout li .message_wrap .text {
float: left;
width: 100%;
border-top: 1px solid #cfcfcf;
padding-top: 5px
}
ul.messages_layout .dropdown-menu li{ width:100%; font-size:11px;}
/* Full Calendar */
.fc {
direction: ltr;
text-align: left;
position: relative
}
.fc table {
border-collapse: collapse;
border-spacing: 0
}
html .fc, .fc table {
font-size: 1em
}
.fc td, .fc th {
padding: 0;
vertical-align: top
}
.fc-header td {
white-space: nowrap;
background: none
}
.fc-header-left {
width: 100%;
text-align: left;
position: absolute;
left: 0;
top: 6px
}
.fc-header-left .fc-button {
margin: 0;
position: relative
}
.fc-header-left .fc-button-prev, .fc-header-left .fc-button-next {
float: left;
border: none;
padding: 14px 10px;
opacity: 0.5
}
.fc-header-left .fc-button-prev .fc-button-inner, .fc-header-left .fc-button-next .fc-button-inner {
border: none
}
.fc-header-left .fc-button-prev .fc-button-inner .fc-button-content, .fc-header-left .fc-button-next .fc-button-inner .fc-button-content {
display: none
}
.fc-header-left .fc-button-prev.fc-state-hover, .fc-header-left .fc-button-next.fc-state-hover {
opacity: 1
}
.fc-header-left .fc-button-prev.fc-state-down, .fc-header-left .fc-button-next.fc-state-down {
background: none !important;
margin-top: -1px
}
.fc-header-left .fc-button-prev .fc-button-inner {
background-position: 0 -351px;
height: 16px;
width: 11px
}
.fc-header-left .fc-button-next {
float: right
}
.fc-header-left .fc-button-next .fc-button-inner {
background-position: 0 -367px;
height: 16px;
width: 11px
}
.fc-header-center {
text-align: center
}
.fc-header-right {
text-align: right;
position: absolute;
top: -34px;
right: 10px
}
.fc-header-title {
display: inline-block;
vertical-align: top
}
.fc-header-title h2 {
margin-top: 0;
white-space: nowrap;
font-size: 1.1rem;
color: #6C737F;
line-height: 55px;
}
.fc .fc-header-space {
padding-left: 10px
}
.fc-header .fc-button {
margin-bottom: 1em;
vertical-align: top
}
.fc-header .fc-button {
margin-right: -1px
}
.fc-header .fc-corner-right {
margin-right: 1px
}
.fc-header .ui-corner-right {
margin-right: 0
}
.fc-header .fc-state-hover, .fc-header .ui-state-hover {
z-index: 2
}
.fc-header .fc-state-down {
z-index: 3
}
.fc-header .fc-state-active, .fc-header .ui-state-active {
z-index: 4
}
.fc-content {
clear: both;
background: #f9f9f9
}
.fc-view {
width: 100%;
overflow: hidden
}
.fc-view thead {
background:#e9ecf1;
line-height: 35px
}
.fc-widget-header, .fc-widget-content {
border: 1px solid #ccc
}
.fc-state-highlight {
background: #F4F3E6
}
.fc-cell-overlay {
background: #9cf;
opacity: .2;
filter: alpha(opacity=20)
}
.fc-button {
position: relative;
display: inline-block;
cursor: pointer
}
.fc-button-today{margin-top: 8px !important;}
.fc-state-default {
border-style: solid;
border-width: 1px 0
}
.fc-button-inner {
position: relative;
float: left;
overflow: hidden
}
.fc-state-default .fc-button-inner {
border-style: solid;
border-width: 0 1px
}
.fc-button-content {
position: relative;
float: left;
height: 1.9em;
line-height: 1.9em;
padding: 0 .6em;
white-space: nowrap
}
.fc-button-content .fc-icon-wrap {
position: relative;
float: left;
top: 50%
}
.fc-button-content .ui-icon {
position: relative;
float: left;
margin-top: -50%;
*margin-top:0;
*top:-50%
}
.fc-state-default .fc-button-effect {
position: absolute;
top: 50%;
left: 0
}
.fc-state-default .fc-button-effect span {
position: absolute;
top: -100px;
left: 0;
width: 500px;
height: 100px;
border-width: 100px 0 0 1px;
border-style: solid;
border-color: #fff;
background: #444;
opacity: .09;
filter: alpha(opacity=9)
}
.fc-state-default, .fc-state-default .fc-button-inner {
border-style: solid;
border-color: #ccc #bbb #aaa;
color: #000
}
.fc-state-hover, .fc-state-hover .fc-button-inner {
border-color: #999
}
.fc-state-down {
border-color: #555;
background: #777
}
.fc-state-active, .fc-state-active .fc-button-inner {
border-color: #555;
background: #777;
color: #fff
}
.fc-state-disabled, .fc-state-disabled .fc-button-inner {
color: #999;
border-color: #ddd
}
.fc-state-disabled {
cursor: default
}
.fc-state-disabled .fc-button-effect {
display: none
}
.fc-event {
border-style: solid;
border-width: 0;
font-size: .85em;
cursor: default
}
a.fc-event, .fc-event-draggable {
cursor: pointer
}
a.fc-event {
text-decoration: none
}
.fc-rtl .fc-event {
text-align: right
}
.fc-event-skin {
border-color: #3f85f5;
background-color: #5e96ea;
color: #fff
}
.fc-event-inner {
position: relative;
width: 100%;
height: 100%;
border-style: solid;
border-width: 0;
overflow: hidden
}
.fc-event-time, .fc-event-title {
padding: 0 1px
}
.fc .ui-resizable-handle {
display: block;
position: absolute;
z-index: 99999;
overflow: hidden;
font-size: 300%;
line-height: 50%
}
.fc-event-hori {
border-width: 1px 0;
margin-bottom: 1px
}
.fc-event-hori .ui-resizable-e {
top: 0 !important;
right: -3px !important;
width: 7px !important;
height: 100% !important;
cursor: e-resize
}
.fc-event-hori .ui-resizable-w {
top: 0 !important;
left: -3px !important;
width: 7px !important;
height: 100% !important;
cursor: w-resize
}
.fc-event-hori .ui-resizable-handle {
_padding-bottom: 14px
}
.fc-corner-left {
margin-left: 1px
}
.fc-corner-left .fc-button-inner, .fc-corner-left .fc-event-inner {
margin-left: -1px
}
.fc-corner-right {
margin-right: 1px
}
.fc-corner-right .fc-button-inner, .fc-corner-right .fc-event-inner {
margin-right: -1px
}
.fc-corner-top {
margin-top: 1px
}
.fc-corner-top .fc-event-inner {
margin-top: -1px
}
.fc-corner-bottom {
margin-bottom: 1px
}
.fc-corner-bottom .fc-event-inner {
margin-bottom: -1px
}
.fc-corner-left .fc-event-inner {
border-left-width: 1px
}
.fc-corner-right .fc-event-inner {
border-right-width: 1px
}
.fc-corner-top .fc-event-inner {
border-top-width: 1px
}
.fc-corner-bottom .fc-event-inner {
border-bottom-width: 1px
}
table.fc-border-separate {
border-collapse: separate
}
.fc-border-separate th, .fc-border-separate td {
border-width: 1px 0 0 1px
}
.fc-border-separate th.fc-last, .fc-border-separate td.fc-last {
border-right-width: 1px
}
.fc-border-separate tr.fc-last th, .fc-border-separate tr.fc-last td {
border-bottom-width: 0px
}
.fc-first {
border-left-width: 0 !important
}
.fc-last {
border-right-width: 0 !important
}
.fc-grid th {
text-align: center
}
.fc-grid .fc-day-number {
float: right;
padding: 0 2px
}
.fc-grid .fc-other-month .fc-day-number {
opacity: 0.3;
filter: alpha(opacity=30)
}
.fc-grid .fc-day-content {
clear: both;
padding: 2px 2px 1px
}
.fc-grid .fc-event-time {
font-weight: bold
}
.fc-rtl .fc-grid .fc-day-number {
float: left
}
.fc-rtl .fc-grid .fc-event-time {
float: right
}
.fc-agenda table {
border-collapse: separate
}
.fc-agenda-days th {
text-align: center
}
.fc-agenda .fc-agenda-axis {
width: 60px !important;
padding: 0 4px;
vertical-align: middle;
text-align: right;
white-space: nowrap;
font-weight: normal
}
.fc-agenda .fc-day-content {
padding: 2px 2px 1px
}
.fc-agenda-days .fc-agenda-axis {
border-right-width: 1px
}
.fc-agenda-days .fc-col0 {
border-left-width: 0
}
.fc-agenda-allday th {
border-width: 0 1px
}
.fc-agenda-allday .fc-day-content {
min-height: 34px;
_height: 34px
}
.fc-agenda-divider-inner {
height: 2px;
overflow: hidden
}
.fc-widget-header .fc-agenda-divider-inner {
background: #eee
}
.fc-agenda-slots th {
border-width: 1px 1px 0
}
.fc-agenda-slots td {
border-width: 1px 0 0;
background: none
}
.fc-agenda-slots td div {
height: 20px
}
.fc-agenda-slots tr.fc-slot0 th, .fc-agenda-slots tr.fc-slot0 td {
border-top-width: 0
}
.fc-agenda-slots tr.fc-minor th, .fc-agenda-slots tr.fc-minor td {
border-top-style: dotted
}
.fc-agenda-slots tr.fc-minor th.ui-widget-header {
*border-top-style:solid
}
.fc-event-vert {
border-width: 0 1px
}
.fc-event-vert .fc-event-head, .fc-event-vert .fc-event-content {
position: relative;
z-index: 2;
width: 100%;
overflow: hidden
}
.fc-event-vert .fc-event-time {
white-space: nowrap;
font-size: 10px
}
.fc-event-vert .fc-event-bg {
position: absolute;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
opacity: .3;
filter: alpha(opacity=30)
}
.fc .ui-draggable-dragging .fc-event-bg, .fc-select-helper .fc-event-bg {
display: none\9
}
.fc-event-vert .ui-resizable-s {
bottom: 0 !important;
width: 100% !important;
height: 8px !important;
overflow: hidden !important;
line-height: 8px !important;
font-size: 11px !important;
font-family: monospace;
text-align: center;
cursor: s-resize
}
.fc-agenda .ui-resizable-resizing {
_overflow: hidden
}
.fc-header-left .fc-button-prev .fc-button-inner {background: url('../img/icons-sa7c41345d9.png') no-repeat; background-position: 0 -351px;
height: 16px;
width: 11px;}
.fc-header-left .fc-button-next .fc-button-inner {background: url('../img/icons-sa7c41345d9.png') no-repeat; background-position: 0 -367px;
height: 16px;
width: 11px;}
/*------------------------------------------------------------------
[8. Miscellaneous]
*/
.chart-holder {
width: 100%;
height: 250px;
}
.dropdown-menu li>a:hover, .dropdown-menu .active>a, .dropdown-menu .active>a:hover { background:#00ba8b;}
.accordion-heading { background:#e5e5e5; }
.accordion-heading a { color:#545454; text-decoration:none; font-weight:bold; }
.btn-facebook-alt i {
color: #23386a;
}
.btn-twitter-alt i {
color: #0098d0;
}
.btn-google-alt i {
color: #b6362d;
}
.btn-linkedin-alt i {
color: #0073b2;
}
.btn-pinterest-alt i {
color: #ab171e;
}
.btn-github-alt i {
color: #333;
}
.all-icons li { list-style:none;}
.ML0 { margin-left:0}
.MR0 { margin-right:0;}
/*------------------------------------------------------------------
[1. Max Width: 480px]
*/
@media (max-width: 480px) {
.error-container h1 {
font-size: 72px;
}
}
/*------------------------------------------------------------------
[1. Max Width: 767px]
*/
@media (max-width: 767px) {
#main {
padding: 0 10px;
margin-right: -20px;
margin-left: -20px;
}
.subnavbar {
margin-left: -20px;
margin-right: -20px;
}
.subnavbar-inner {
height: auto;
}
.subnavbar .container > ul {
width: 100%;
height: auto;
border: none;
}
.subnavbar .container > ul > li {
width: 33%;
height: 70px;
margin-bottom: 0;
border: none;
}
.subnavbar .container > ul > li.active > a {
font-size: 11px;
background: transparent;
}
.subnavbar .container > ul > li > a > i {
display: inline-block;
margin-bottom: 0;
font-size: 20px;
}
.subnavbar-open-right .dropdown-menu {
left: auto;
right: 0;
}
.subnavbar-open-right .dropdown-menu:before {
left: auto;
right: 12px;
}
.subnavbar-open-right .dropdown-menu:after {
left: auto;
right: 13px;
}
.extra {
margin-right: -20px;
margin-left: -20px;
}
.extra .container {
padding: 0 20px;
}
.footer {
margin-right: -20px;
margin-left: -20px;
height:auto;
}
.footer .container {
padding: 0 20px;
}
.footer .footer-terms {
text-align: left;
}
.footer .footer-terms a {
margin-left: 0;
margin-right: 1em;
}
}
/*------------------------------------------------------------------
[3. Max Width: 979px]
*/
@media (max-width: 979px) {
.navbar-fixed-top {
position: static;
margin-bottom: 0;
}
.subnavbar {
}
.subnavbar .container {
width: auto;
}
}
/*------------------------------------------------------------------
[2. Max Width: 1200px]
*/
@media (min-width: 1200px) {
.navbar .search-query {
width: 200px;
}
}
| kozmonaut/pingu-track | css/style.css | CSS | mit | 21,348 |
---
title: "Line-Following Robot"
---
Here's goes my first "projects" post. Last semester I took a class called "Intro To Electromechanical Systems" (shout out to my professor Greg Lewin), a fun class about combining software and hardware to make some cool things. As you've probably guessed, one of the projects we had was to create a line following robot. But what I didn't mention in the title was that this robot didn't only follow lines, but also delivered packages! The robot can be seen below:
<img src="/assets/linefollowing1.JPG" width="70%" />
### Basically an Amazon delivery drone
The general idea was for this robot to get an order from a website we created, go and retrieve the package from our "warehouse", deliver it to the "customers home", and finally update the SQL database with help from some PHP scripts and a little bit of magic. We created the map that the robot following with electrical tape as the lines, and set specific points on the map to be warehouse A, B, or C and other points to be customer's addresses 1, 2, 3, and 4. The robot's "brain" (AI/singularity rant incoming...) was made using the arduino UNO, as well as the arduino wireless and motor shields. This allowed the robot to take the order wirelessly without needing to keep it connected to the computer that was putting the order in through the website.
To make sure that the robot was able to properly follow the lines, light sensors and encoders on the motors were used to keep track of distance and whether the robot was actually on the line or not. Some psuedo code can be seen below:
If (not on line) {
Get back on the line
}
In all seriousness, the robot had two light sensors, and whenever one was giving out a high output (meaning it is seeing black), we adjusted its direction back towards the line.
Everything was wired together using a small breadboard to keep it neat. The body was designed in AutoCAD and laser cut before we put anything else together. Overall, it was pretty satisfying to have the system work in unison (after a ton of tests...I mean seriously a ton...). You can see the side and a closer view of the front of the robot below:
<img src="/assets/linefollowing2.JPG" width="70%" />
<img src="/assets/linefollowing3.JPG" width="70%" />
--- Jamel Charouel
Monday, August 3rd, 2015 | jamelcharouel/jamelcharouel.github.io | _posts/2015-08-03-line-following-robot.markdown | Markdown | mit | 2,318 |
#ifndef HKBGETWORLDFROMMODELMODIFIER_H
#define HKBGETWORLDFROMMODELMODIFIER_H
#include "hkbmodifier.h"
class hkbGetWorldFromModelModifier final: public hkbModifier
{
friend class GetWorldFromModelModifierUI;
public:
hkbGetWorldFromModelModifier(HkxFile *parent, long ref = 0);
hkbGetWorldFromModelModifier& operator=(const hkbGetWorldFromModelModifier&) = delete;
hkbGetWorldFromModelModifier(const hkbGetWorldFromModelModifier &) = delete;
~hkbGetWorldFromModelModifier();
public:
QString getName() const;
static const QString getClassname();
private:
void setName(const QString &newname);
bool getEnable() const;
void setEnable(bool value);
hkQuadVariable getTranslationOut() const;
void setTranslationOut(const hkQuadVariable &value);
hkQuadVariable getRotationOut() const;
void setRotationOut(const hkQuadVariable &value);
bool readData(const HkxXmlReader & reader, long & index);
bool link();
void unlink();
QString evaluateDataValidity();
bool write(HkxXMLWriter *writer);
private:
static uint refCount;
static const QString classname;
long userData;
QString name;
bool enable;
hkQuadVariable translationOut;
hkQuadVariable rotationOut;
mutable std::mutex mutex;
};
#endif // HKBGETWORLDFROMMODELMODIFIER_H
| Zartar/Skyrim-Behavior-Editor- | src/hkxclasses/behavior/modifiers/hkbgetworldfrommodelmodifier.h | C | mit | 1,324 |
@extends('admin.layout')
@section('title')
Payment
@endsection
@section('content')
<a href="/admin/ff/payment/create/{{$pledge->id}}" class="ui teal button right floated">New Payment</a>
<h1 class="ui header">Payments</h1>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Summary </div>
<table class="ui unstackable table">
<thead>
<tr>
<th class="center aligned"> {{trans('futurefund.total_pledge')}} </th>
<th class="center aligned"> {{trans('futurefund.collected')}} </th>
<th class="center aligned"> {{trans('futurefund.balance')}} </th>
</tr>
</thead>
<tr>
<td class="center aligned">RM {{number_format($pledge->amount, 2)}}</td>
<td class="center aligned">RM {{number_format($pledge_collected, 2)}}</td>
<td class="center aligned">RM {{number_format(($pledge->amount - $pledge_collected), 2)}}</td>
</tr>
</table>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Payments </div>
<div class="ui segment">
{!! Form::select('is_cleared', ['0' => 'Not cleared', '1' => 'Cleared', 'all' => 'All'], $filter['is_cleared'], ['class' => 'ui dropdown']) !!}
{!! Form::select('is_cancelled', ['0' => 'Not cancelled', '1' => 'Cancelled', 'all' => 'All'], $filter['is_cancelled'], ['class' => 'ui dropdown']) !!}
<div class="clearfix field">
<a href="{{ url()->current() }}" class="ui basic right floated right labeled icon tiny button">
Reset <i class="undo icon"></i>
</a>
<button class="ui teal right floated right labeled icon tiny button">
Filter <i class="filter icon"></i>
</button>
</div>
<div class="ui hidden divider"></div>
{!! Form::close() !!}
</div>
<table class="ui very compact unstackable table">
<thead>
<tr>
<th >{!! sort_by('id', 'ID' ) !!}</th>
<th class="three wide">Amount</th>
<th >Status</th>
<th >Created at</th>
<th >Actions</th>
</tr>
</thead>
<tbody>
@forelse ($payments as $payment)
<tr>
<td>
<h5 class="ui header">
{{ prefix()->wrap($payment) }}
</h5>
</td>
<td>
<h5 class="ui header">
RM {{ $payment->amount }}
@if ($payment->remarks)
<div class="sub uppercased header">{{ $payment->remarks }}</div>
@endif
</h5>
</td>
<td>
<div>
@if ($payment->is_cancelled)
<div class="ui grey label">cancelled</div>
@else
@if ($payment->is_cleared)
<div class="ui green label">cleared</div>
@else
<div class="ui orange label">pending</div>
@endif
@endif
</div>
</td>
<td>
{{ $payment->created_at->format('Y-m-d') }}
<div>{{ $payment->created_at->format('h:i a') }}</div>
</td>
<td>
<div class="ui small icon buttons">
<a href="/admin/ff/payment/update/{{$payment->id}}" class="ui button">
<i class="pencil icon"></i>
</a>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="5"> No payment record yet, change filter or come back later </td>
</tr>
@endforelse
</tbody>
</table>
@endsection
| yilliot/souls | resources/views/admin/ff/payment_index.blade.php | PHP | mit | 3,322 |
(function (window) {
'use strict';
var applicationModuleName = 'mean';
var service = {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'angularFileUpload', 'ngMaterial'],
registerModule: registerModule
};
window.ApplicationConfiguration = service;
// Add a new vertical module
function registerModule(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
}
}(window));
| tennosys/autoworks | modules/core/client/app/config.js | JavaScript | mit | 674 |
struct stat;
struct rtcdate;
// system calls
int fork(void);
int exit(void) __attribute__((noreturn));
int wait(void);
int pipe(int*);
int write(int, void*, int);
int read(int, void*, int);
int close(int);
int kill(int);
int exec(char*, char**);
int open(char*, int);
int mknod(char*, short, short);
int unlink(char*);
int fstat(int fd, struct stat*);
int link(char*, char*);
int mkdir(char*);
int chdir(char*);
int dup(int);
int getpid(void);
char* sbrk(int);
int sleep(int);
int uptime(void);
// Priority increment syscall
int nice(int);
// ulib.c
int stat(char*, struct stat*);
char* strcpy(char*, char*);
void *memmove(void*, void*, int);
char* strchr(const char*, char c);
int strcmp(const char*, const char*);
void printf(int, char*, ...);
char* gets(char*, int max);
uint strlen(char*);
void* memset(void*, int, uint);
void* malloc(uint);
void free(void*);
int atoi(const char*);
| dswann5/os_assignment_3 | user.h | C | mit | 889 |
/*
* 5-high FONT FOR RENDERING TO THE LED SCREEN.
* Includes kerning support
* Gaurav Manek, 2011
*/
#ifndef __FONT5X4_H
#define __FONT5X4_H
#include <avr/pgmspace.h>
#define FONT_5X4_HEIGHT 5
#define FONT_5X4_STEP_GLYPH 10
// Number of bytes per glyph
const char FONT_5X4 [] PROGMEM = {
0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // SPACE
0b0111, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // !
0b0011, 0b0000, 0b0000, 0b0000, 0b0011, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // "
0b1010, 0b0000, 0b1111, 0b0001, 0b1010, 0b0000, 0b1111, 0b0001, 0b1010, 0b0000, // #
0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // $
0b0011, 0b0001, 0b1011, 0b0000, 0b0100, 0b0000, 0b1010, 0b0001, 0b1001, 0b0001, // %
0b1010, 0b0000, 0b0101, 0b0001, 0b1001, 0b0001, 0b1010, 0b0001, 0b0000, 0b0000, // &
0b0011, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // '
0b1110, 0b0000, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // (
0b0001, 0b0001, 0b1110, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // )
0b0101, 0b0000, 0b0010, 0b0000, 0b0101, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // *
0b0100, 0b0000, 0b0100, 0b0000, 0b1111, 0b0001, 0b0100, 0b0000, 0b0100, 0b0000, // +
0b0000, 0b0001, 0b1000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // ,
0b0100, 0b0000, 0b0100, 0b0000, 0b0100, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // -
0b0000, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // .
0b0000, 0b0001, 0b1100, 0b0000, 0b0110, 0b0000, 0b0001, 0b0000, 0b0000, 0b0000, // /
0b1110, 0b0000, 0b0001, 0b0001, 0b1110, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // 0
0b0010, 0b0001, 0b1111, 0b0001, 0b0000, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // 1
0b0010, 0b0001, 0b1001, 0b0001, 0b0101, 0b0001, 0b0010, 0b0001, 0b0000, 0b0000, // 2
0b0101, 0b0001, 0b0101, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // 3
0b1100, 0b0000, 0b1010, 0b0000, 0b1111, 0b0001, 0b1000, 0b0000, 0b0000, 0b0000, // 4
0b0111, 0b0001, 0b0101, 0b0001, 0b1101, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // 5
0b1110, 0b0000, 0b0101, 0b0001, 0b0101, 0b0001, 0b1000, 0b0000, 0b0000, 0b0000, // 6
0b0001, 0b0000, 0b1101, 0b0001, 0b0101, 0b0000, 0b0011, 0b0000, 0b0000, 0b0000, // 7
0b1010, 0b0000, 0b0101, 0b0001, 0b0101, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, // 8
0b0010, 0b0000, 0b0101, 0b0000, 0b0101, 0b0001, 0b1110, 0b0000, 0b0000, 0b0000, // 9
0b1010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // :
0b0000, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // ;
0b0100, 0b0000, 0b1010, 0b0000, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // <
0b1010, 0b0000, 0b1010, 0b0000, 0b1010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // =
0b0001, 0b0001, 0b1010, 0b0000, 0b0100, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // >
0b0010, 0b0000, 0b0001, 0b0000, 0b1001, 0b0001, 0b0110, 0b0000, 0b0000, 0b0000, // ?
0b1110, 0b0000, 0b0001, 0b0000, 0b1101, 0b0000, 0b0101, 0b0001, 0b1111, 0b0000, // @
0b1110, 0b0001, 0b0101, 0b0000, 0b0101, 0b0000, 0b1110, 0b0001, 0b0000, 0b0000, // A
0b1111, 0b0001, 0b0101, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // B
0b1110, 0b0000, 0b0001, 0b0001, 0b0001, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, // C
0b1111, 0b0001, 0b0001, 0b0001, 0b1110, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // D
0b1111, 0b0001, 0b0101, 0b0001, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // E
0b1111, 0b0001, 0b0101, 0b0000, 0b0101, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // F
0b1110, 0b0000, 0b0001, 0b0001, 0b1001, 0b0001, 0b1010, 0b0000, 0b0000, 0b0000, // G
0b1111, 0b0001, 0b0100, 0b0000, 0b0100, 0b0000, 0b1111, 0b0001, 0b0000, 0b0000, // H
0b0001, 0b0001, 0b1111, 0b0001, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // I
0b1001, 0b0000, 0b0001, 0b0001, 0b1111, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // J
0b1111, 0b0001, 0b0100, 0b0000, 0b1010, 0b0000, 0b0001, 0b0001, 0b0000, 0b0000, // K
0b1111, 0b0001, 0b0000, 0b0001, 0b0000, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // L
0b1111, 0b0001, 0b0010, 0b0000, 0b0100, 0b0000, 0b0010, 0b0000, 0b1111, 0b0001, // M
0b1111, 0b0001, 0b0010, 0b0000, 0b0100, 0b0000, 0b1000, 0b0000, 0b1111, 0b0001, // N
0b1110, 0b0000, 0b0001, 0b0001, 0b0001, 0b0001, 0b1110, 0b0000, 0b0000, 0b0000, // O
0b1111, 0b0001, 0b0101, 0b0000, 0b0010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // P
0b1110, 0b0000, 0b0001, 0b0001, 0b0001, 0b0001, 0b1001, 0b0000, 0b0110, 0b0001, // Q
0b1111, 0b0001, 0b0101, 0b0000, 0b1010, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // R
0b0010, 0b0001, 0b0101, 0b0001, 0b0101, 0b0001, 0b1001, 0b0000, 0b0000, 0b0000, // S
0b0001, 0b0000, 0b1111, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // T
0b1111, 0b0000, 0b0000, 0b0001, 0b0000, 0b0001, 0b1111, 0b0000, 0b0000, 0b0000, // U
0b0011, 0b0000, 0b1100, 0b0000, 0b0000, 0b0001, 0b1100, 0b0000, 0b0011, 0b0000, // V
0b1111, 0b0000, 0b0000, 0b0001, 0b1100, 0b0000, 0b0000, 0b0001, 0b1111, 0b0000, // W
0b1011, 0b0001, 0b0100, 0b0000, 0b1011, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, // X
0b0011, 0b0000, 0b1100, 0b0001, 0b0011, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // Y
0b1001, 0b0001, 0b0101, 0b0001, 0b0101, 0b0001, 0b0011, 0b0001, 0b0000, 0b0000, // Z
0b1111, 0b0001, 0b0001, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // [
0b0001, 0b0000, 0b0110, 0b0000, 0b1100, 0b0000, 0b0000, 0b0001, 0b0000, 0b0000, // backslash
0b0001, 0b0001, 0b1111, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // ]
0b0010, 0b0000, 0b0001, 0b0000, 0b0010, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, // ^
0b0000, 0b0001, 0b0000, 0b0001, 0b0000, 0b0001, 0b0000, 0b0000, 0b0000, 0b0000 // _
};
const char FONT_5X4_WIDTH [] = {
1, 1, 3, 5, 4, 5, 4, 1,
2, 2, 3, 5, 2, 3, 1, 4,
3, 3, 4, 3, 4, 3, 4, 4,
4, 4, 1, 2, 3, 3, 3, 4,
5, 4, 3, 4, 3, 3, 3, 4,
4, 3, 3, 4, 3, 5, 5, 4,
3, 5, 3, 4, 3, 4, 5, 5,
3, 3, 4, 2, 4, 2, 3, 3
};
#endif // __FONT5X4_H
| flavio-fernandes/HT1632-for-Arduino | Arduino/HT1632/font_5x4.h | C | mit | 6,202 |
---
layout: default
---
<section id="content-region-3" class="padding-40 page-tree-bg">
<div class="container">
<h3 class="page-tree-text">
Becoming a Sponsor
</h3>
</div>
</section>
<div class="space-70"></div>
<div class="container">
<div class="row">
<div class="col-md-12">
</div>
</div>
<div class="row">
<div class="col-md-4 margin-btm-20">
<div class="pricing-wrapper">
<div class="pricing-head">
<h3>Terawatt</h3>
</div>
<div class="pricing-rate">
<h1>$6,000 and above</h1>
</div>
<div class="pricing-desc">
<ul class="list-unstyled">
<li><i class="ion-checkmark-round"></i> Invitation to Sponsor Day</li>
<li><i class="ion-checkmark-round"></i> Feature in our newsletter</li>
<li><i class="ion-checkmark-round"></i> Company logo on team website</li>
<li><i class="ion-checkmark-round"></i> Social media shout outs</li>
<li><i class="ion-checkmark-round"></i> Company logo on team banner </li>
<li><i class="ion-checkmark-round"></i> Large Company logo on REV 2</li>
<li><i class="ion-checkmark-round"></i> Access to our team resume book and EVT room tour</li>
<li><i class="ion-checkmark-round"></i> Large Company logo on team T-shirts</li>
</ul>
</div>
</div><!--pricing wrapper-->
</div><!--pricing col end-->
<div class="col-md-4 margin-btm-20">
<div class="pricing-wrapper">
<div class="pricing-head">
<h3>Gigawatt</h3>
</div>
<div class="pricing-rate">
<h1>$3,500 - $5,999</h1>
</div>
<div class="pricing-desc">
<ul class="list-unstyled">
<li><i class="ion-checkmark-round"></i> Invitation to Sponsor Day</li>
<li><i class="ion-checkmark-round"></i> Feature in our newsletter</li>
<li><i class="ion-checkmark-round"></i> Company logo on team website</li>
<li><i class="ion-checkmark-round"></i> Social media shout outs</li>
<li><i class="ion-checkmark-round"></i> Company logo on team banner </li>
<li><i class="ion-checkmark-round"></i> Medium Company logo on REV 2</li>
<li><i class="ion-checkmark-round"></i> Access to our team resume book and EVT room tour</li>
<li><i class="ion-checkmark-round"></i> Medium Company logo on team T-shirts</li>
</ul>
</div>
</div><!--pricing wrapper-->
</div><!--pricing col end-->
<div class="col-md-4 margin-btm-20">
<div class="pricing-wrapper">
<div class="pricing-head">
<h3>Megawatt</h3>
</div>
<div class="pricing-rate">
<h1>$1000 - $3,499</h1>
</div>
<div class="pricing-desc">
<ul class="list-unstyled">
<li><i class="ion-checkmark-round"></i> Invitation to Sponsor Day</li>
<li><i class="ion-checkmark-round"></i> Feature in our newsletter</li>
<li><i class="ion-checkmark-round"></i> Company logo on team website</li>
<li><i class="ion-checkmark-round"></i> Social media shout outs</li>
<li><i class="ion-checkmark-round"></i> Company logo on team banner </li>
<li><i class="ion-checkmark-round"></i> Small Company logo on REV 2</li>
<li><i class="ion-checkmark-round"></i> Access to our team resume book and EVT room tour</li>
<li><i class="ion-checkmark-round"></i> Small Company logo on team T-shirts</li>
</ul>
</div>
</div><!--pricing wrapper-->
</div><!--pricing col end-->
<div class="col-md-4 margin-btm-20">
<div class="pricing-wrapper">
<div class="pricing-head">
<h3>Kilowatt</h3>
</div>
<div class="pricing-rate">
<h1>$500-$999</h1>
</div>
<div class="pricing-desc">
<ul class="list-unstyled">
<li><i class="ion-checkmark-round"></i> Invitation to Sponsor Day</li>
<li><i class="ion-checkmark-round"></i> Feature in our newsletter</li>
<li><i class="ion-checkmark-round"></i> Company logo on team website</li>
<li><i class="ion-checkmark-round"></i> Social media shout outs</li>
<!--<li><i class="ion-close-round"></i> Company logo on team banner </li>-->
<!--<li><i class="ion-close-round"></i> Company logo on REV 1</li>-->
<!--<li><i class="ion-close-round"></i> Private tour of team room and projects</li>-->
</ul>
</div>
</div><!--pricing wrapper-->
</div><!--pricing col end-->
<div class="col-md-4 margin-btm-20">
<div class="pricing-wrapper">
<div class="pricing-head">
<h3>Watt</h3>
</div>
<div class="pricing-rate">
<h1>$1-$499</h1>
</div>
<div class="pricing-desc">
<ul class="list-unstyled">
<li><i class="ion-checkmark-round"></i> Invitation to Sponsor Day</li>
<li><i class="ion-checkmark-round"></i> Feature in our newsletter</li>
<!--<li><i class="ion-close-round"></i> Social media shout outs</li> -->
<!--<li><i class="ion-close-round"></i> Company logo on team banner </li>-->
<!--<li><i class="ion-close-round"></i> Company logo on REV 1</li>-->
<!--<li><i class="ion-close-round"></i> Private tour of team room and projects</li>-->
</ul>
</div>
</div><!--pricing wrapper-->
</div><!--pricing col end-->
</div><!--pricing 3 col row end-->
<div class="col-md-6 text-center">
<h1><a href="../../assets/documents/2018.19_EVT_SponsorshipPacketWeb.pdf" target="_blank" class="text-center btn theme-btn-evt btn-lg btn-radius btn-block">View the official 2018-19 Sponsorship Packet</a></h1>
</div>
<div class="col-md-6 text-center">
<h1><a href="https://securelb.imodules.com/s/1624/index-giving.aspx?sid=1624&gid=1&pgid=705&cid=1466&fid=1466&gfid=800&bledit=1&dids=354"
target="_blank" class="text-center btn theme-btn-evt btn-lg btn-radius btn-block">Make a donation to the RIT Electric Vehicle Team</a></h1>
</div>
<div class="space-40"></div>
<!--<div class="col-md-12">-->
<!--<h1 class="heading-mini">How to Donate</h1>-->
<!--</div>-->
<!--<div class="col-md-8">-->
<!--<div>-->
<!--<img src="/assets/img/gift_to_evt_1.png" class="img-responsive" alt="Responsive Image">-->
<!--</div>-->
<!--</div>-->
<!--<div class="col-md-12">-->
<!--<div class="price-faq-box">-->
<!--<div class="space-20"></div>-->
<!--<h3>Safe, Fast, Offical</h3>-->
<!--<p>-->
<!--Donating only takes 5 steps. On the first page,-->
<!--be sure to select "Other" and fill in-->
<!--"<strong>Electric Vehicle Team</strong>".-->
<!--</p>-->
<!--<a href="https://www.rit.edu/giving/makeagift/" target="_blank"><img src="/assets/img/make_a_gift_button.png"></a>-->
<!--</div>-->
<!--</div>-->
</div>
</div>
<div class="space-20"></div> | RIT-EVT/RIT-EVT.github.io | sponsors/info/index.html | HTML | mit | 8,389 |
---
title: MySQL -- 短连接 + 慢查询
date: 2019-02-20 16:11:17
categories:
- Storage
- MySQL
tags:
- Storage
- MySQL
---
## 短连接
1. 短连接模式:连接到数据库后,执行**很少的SQL**后就断开,下次需要的时候再重连
2. 在**业务高峰**期,会出现连接数突然暴涨的情况
- MySQL建立连接的**成本非常昂贵**
- 成本:TCP/IP三次握手 + 登录权限判断 + 获取连接的数据读写权限
<!-- more -->
### max_connections
1. `max_connections`:MySQL实例同时存在的连接数上限
2. 当连接数超过`max_connections`,系统会**拒绝**接下来的连接请求,返回:`Too many connections`
- 当连接被拒绝,从业务角度来看是**数据库不可用**
3. 如果机器**负载较高**,处理现有请求的时间会变长,每个连接**保持的时间**也会变长
- 如果再有新建连接的话,很容易触发`max_connections`的限制
4. `max_connections`的目的是**保护MySQL**的
- 如果把`max_connections`设置得过大,更多的连接就会进来,导致系统负载会进一步加大
- 大量的资源会耗费在**权限验证**等逻辑上,而已经**拿到连接的线程**会抢不到CPU资源去执行业务SQL
```sql
mysql> SHOW VARIABLES LIKE '%max_connections%';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 2000 |
+-----------------+-------+
```
### 清理Sleep状态的连接
`KILL CONNECTION`:主动踢除**不需要保持**的连接(与`wait_timeout`的效果一样)
| 时刻 | sission A | session B | session C |
| ---- | ---- | ---- | ---- |
| T | BEGIN;<br/>INSERT INTO t VALUES (1,1); | SELECT * FROM t WHERE id=1; | |
| T+30s | | | SHOW PROCESSLIST;<br/>KILL CONNECTION |
1. 踢除`Sleep`状态的连接是**有损**的
2. 如果断开sission A的连接,会**回滚事务**
3. 如果断开sission B的连接,没有任何影响
- 优先断开**事务外空闲**的连接
- 再考虑断开**事务内空闲**的连接
#### 事务外空闲
<img src="https://mysql-1253868755.cos.ap-guangzhou.myqcloud.com/mysql-short-conn-trx-idle-1.png" width=500/>
`trx_mysql_thread_id`:`id=4`的线程还处在事务中
<img src="https://mysql-1253868755.cos.ap-guangzhou.myqcloud.com/mysql-short-conn-trx-idle-2.png" width=500/>
#### KILL CONNECTION
1. 服务端执行`KILL CONNECTION id`,如果连接在此前处于`Sleep`状态,客户端是**不会立马知道**
2. 客户端如果发起**下一个请求**,报错`ERROR 2006 (HY000): MySQL server has gone away`
- 因此,客户端(应用层)需要有**重连机制**
### 减少连接过程的消耗
1. 数据库**跳过权限验证阶段** -- _**风险极高**_
- 重启数据库,启动参数`--skip-grant-tables`
- 跳过**所有**的权限验证阶段(**连接过程**+**语句执行过程**)
2. 从MySQL 8.0开始,启用`--skip-grant-tables`参数,默认会启用`--skip-networking`(**本地客户端**)
## 慢查询
### 索引没有设计好
#### 古老方案
1. `Online DDL` -- `ALTER TABLE`
2. 主库A,备库B
3. 在备库B上执行`SET sql_log_bin=OFF`(**不写binlog**),`ALTER TABLE`加上索引
4. 执行**主备切换**,变成主库B,备库A
5. 在备库A上执行`SET sql_log_bin=OFF`(**不写binlog**),`ALTER TABLE`加上索引
#### 工具
gh-ost
### 语句没写好
```sql
-- Since MySQL 5.7
INSERT INTO query_rewrite.rewrite_rules (pattern, replacement, pattern_database)
VALUES ("SELECT * FROM t WHERE id + 1 = ?", "SELECT * FROM t WHERE id = ? - 1", "test");
CALL query_rewrite.flush_rewrite_rules();
```
### MySQL选错索引
1. `FORCE INDEX`
2. `query_rewrite` + `FORCE INDEX`
### 预先发现问题
1. 测试环境配置:`slow_query_log=ON`+`long_query_time=0`
2. SQL Review,留意`Rows_examined`是否与预期的一致
3. 工具:`pt-query-digest`
## 参考资料
《MySQL实战45讲》
<!-- indicate-the-source -->
| zhongmingmao/zhongmingmao.github.io | source/_posts/mysql-short-conn-slow-query.md | Markdown | mit | 4,013 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Command\CachePoolListCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @group functional
*/
class CachePoolListCommandTest extends AbstractWebTestCase
{
protected function setUp()
{
static::bootKernel(['test_case' => 'CachePools', 'root_config' => 'config.yml']);
}
public function testListPools()
{
$tester = $this->createCommandTester(['cache.app', 'cache.system']);
$tester->execute([]);
$this->assertSame(0, $tester->getStatusCode(), 'cache:pool:list exits with 0 in case of success');
$this->assertContains('cache.app', $tester->getDisplay());
$this->assertContains('cache.system', $tester->getDisplay());
}
public function testEmptyList()
{
$tester = $this->createCommandTester([]);
$tester->execute([]);
$this->assertSame(0, $tester->getStatusCode(), 'cache:pool:list exits with 0 in case of success');
}
private function createCommandTester(array $poolNames)
{
$application = new Application(static::$kernel);
$application->add(new CachePoolListCommand($poolNames));
return new CommandTester($application->find('cache:pool:list'));
}
}
| arjenm/symfony | src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolListCommandTest.php | PHP | mit | 1,603 |
module ActiveSurvey
class Visitor
def visit_items(items)
res = items.map { |item| item.accept(self) }
after_visit_items(items, res)
end
def after_visit_items(items, result)
result
end
def visit_question(item)
end
def visit_section(item)
self.visit_items item.items
end
def visit_text_item(item)
end
end
end | bcardiff/active_survey | lib/active_survey/visitor.rb | Ruby | mit | 378 |
(function (require) {
var test = require('test'),
asyncTest = require('asyncTest'),
start = require('start'),
module = require('module'),
ok = require('ok'),
expect = require('expect'),
$ = require('$'),
document = require('document'),
raises = require('raises'),
rnd = '?' + Math.random(),
ENV_NAME = require('worker_some_global_var') ? 'Worker' : require('node_some_global_var') ? 'Node' : 'DOM';
function getComputedStyle(element, rule) {
if(document.defaultView && document.defaultView.getComputedStyle){
return document.defaultView.getComputedStyle(element, "").getPropertyValue(rule);
}
rule = rule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
return element.currentStyle[rule];
}
module('LMD loader @ ' + ENV_NAME);
asyncTest("require.js()", function () {
expect(6);
require.js('./modules/loader/non_lmd_module.js' + rnd, function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('some_function')() === true, "we can grab content of the loaded script");
ok(require('./modules/loader/non_lmd_module.js' + rnd) === script_tag, "should cache script tag on success");
// some external
require.js('http://yandex.ru/jquery.js' + rnd, function (script_tag) {
ok(typeof script_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('http://yandex.ru/jquery.js' + rnd) === "undefined", "should not cache errorous modules");
require.js('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.js() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.js() JSON callback and chain calls", function () {
expect(2);
var id = require('setTimeout')(function () {
ok(false, 'JSONP call fails');
start();
}, 3000);
require('window').someJsonHandler = function (result) {
ok(result.ok, 'JSON called');
require('window').someJsonHandler = null;
require('clearTimeout')(id);
start();
};
var requireReturned = require.js('./modules/loader/non_lmd_module.jsonp.js' + rnd);
ok(typeof requireReturned === "function", "require.js() must return require");
});
asyncTest("require.js() race calls", function () {
expect(1);
var result;
var check_result = function (scriptTag) {
if (typeof result === "undefined") {
result = scriptTag;
} else {
ok(result === scriptTag, "Must perform one call. Results must be the same");
start();
}
};
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
});
asyncTest("require.js() shortcut", function () {
expect(5);
require.js('sk_js_js', function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('sk_js_js') === script_tag, "require should return the same result");
require.js('sk_js_js', function (script_tag2) {
ok(script_tag2 === script_tag, 'should load once');
ok(require('sk_js_js') === require('/modules/shortcuts/js.js'), "should be defined using path-to-module");
ok(typeof require('shortcuts_js') === "function", 'Should create a global function shortcuts_js as in module function');
start();
})
});
});
// -- CSS
asyncTest("require.css()", function () {
expect(4);
require.css('./modules/loader/some_css.css' + rnd, function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.getElementById('qunit-fixture'), 'visibility') === "hidden", "css should be applied");
ok(require('./modules/loader/some_css.css' + rnd) === link_tag, "should cache link tag on success");
require.css('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.css() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
asyncTest("require.css() CSS loader without callback", function () {
expect(1);
var requireReturned = require
.css('./modules/loader/some_css_callbackless.css' + rnd)
.css('./modules/loader/some_css_callbackless.css' + rnd + 1);
ok(typeof requireReturned === "function", "require.css() must return require");
start();
});
asyncTest("require.css() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
});
asyncTest("require.css() shortcut", function () {
expect(4);
require.css('sk_css_css', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(require('sk_css_css') === link_tag, "require should return the same result");
require.css('sk_css_css', function (link_tag2) {
ok(link_tag2 === link_tag, 'should load once');
ok(require('sk_css_css') === require('/modules/shortcuts/css.css'), "should be defined using path-to-module");
start();
})
});
});
asyncTest("require.css() cross origin", function () {
expect(2);
require.css('sk_css_xdomain', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.body, 'min-width') === "960px", "css should be applied");
start();
});
});
// -- image
asyncTest("require.image()", function () {
expect(5);
require.image('./modules/loader/image.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('./modules/loader/image.gif' + rnd) === img_tag, "should cache img tag on success");
require.image('./modules/loader/image_404.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('./modules/loader/image_404.gif' + rnd) === "undefined", "should not cache errorous modules");
require.image('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.image() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.image() image loader without callback", function () {
expect(1);
var requireReturned = require
.image('./modules/loader/image_callbackless.gif' + rnd)
.image('./modules/loader/image_callbackless.gif' + rnd + 1);
ok(typeof requireReturned === "function", "require.image() must return require");
start();
});
asyncTest("require.image() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.image('./modules/loader_race/image.gif' + rnd, check_result);
require.image('./modules/loader_race/image.gif' + rnd, check_result);
});
asyncTest("require.image() shortcut", function () {
expect(4);
require.image('sk_image_image', function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('sk_image_image') === img_tag, "require should return the same result");
require.image('sk_image_image', function (img_tag2) {
ok(img_tag2 === img_tag, 'should load once');
ok(require('sk_image_image') === require('/modules/shortcuts/image.gif'), "should be defined using path-to-module");
start();
})
});
});
}) | pierrec/js-xxhash | node_modules/lmd/test/qunit/modules/test_case/testcase_lmd_loader/testcase_lmd_loader.js | JavaScript | mit | 10,330 |
/*
The main entry point for the client side of the app
*/
// Create the main app object
this.App = {};
// Create the needed collections on the client side
this.Surprises = new Meteor.Collection("surprises");
// Subscribe to the publishes in server/collections
Meteor.subscribe('surprises');
// Start the app
Meteor.startup(function() {
$(function() {
App.routes = new Routes();
});
});
| angelwong/giftedfromus | client/js/main.js | JavaScript | mit | 405 |
// -*- coding: utf-8 -*-
// Copyright (C) 2016 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <cassert>
#include <ctime>
#include <vector>
#include <spot/twaalgos/dualize.hh>
#include <spot/twaalgos/hoa.hh>
#include <spot/twaalgos/iscolored.hh>
#include <spot/twaalgos/parity.hh>
#include <spot/twaalgos/product.hh>
#include <spot/twaalgos/randomgraph.hh>
#include <spot/misc/random.hh>
#include <spot/twaalgos/complete.hh>
#include <spot/twa/twagraph.hh>
#include <spot/twa/fwd.hh>
#include <spot/twa/acc.hh>
#include <spot/misc/trival.hh>
#include <utility>
#include <string>
#include <iostream>
#define LAST_AUT result.back().first
#define LAST_NUM_SETS result.back().second
#define NEW_AUT() do { \
result.emplace_back(spot::random_graph(6, 0.5, &apf, \
current_bdd, 0, 0, 0.5, true), 0); \
LAST_NUM_SETS = 0; \
/* print_hoa need this */ \
LAST_AUT->prop_state_acc(spot::trival::maybe()); \
} while (false)
#define SET_TR(t, value) do { \
unsigned value_tmp = value; \
if (value_tmp + 1 > LAST_NUM_SETS) \
LAST_NUM_SETS = value_tmp + 1; \
t.acc.set(value_tmp); \
} while (false)
static std::vector<std::pair<spot::twa_graph_ptr, unsigned>>
generate_aut(const spot::bdd_dict_ptr& current_bdd)
{
spot::atomic_prop_set apf = spot::create_atomic_prop_set(3);
std::vector<std::pair<spot::twa_graph_ptr, unsigned>> result;
// No accset on any transition
NEW_AUT();
// The same accset on every transitions
NEW_AUT();
for (auto& t: LAST_AUT->edges())
SET_TR(t, 0);
// All used / First unused / Last unused / First and last unused
for (auto incr_ext: { 0, 1 })
for (auto used: { 1, 2 })
for (auto modulo: { 4, 5, 6 })
if (incr_ext + modulo <= 6)
{
NEW_AUT();
unsigned count = 0;
for (auto& t: LAST_AUT->edges())
if (std::rand() % used == 0)
{
auto value = ++count % modulo + incr_ext;
SET_TR(t, value);
}
}
// One-Three in middle not used
for (auto i: { 0, 1 })
for (auto start: { 1, 2 })
for (auto unused: { 1, 2, 3 })
{
NEW_AUT();
auto count = 0;
for (auto& t: LAST_AUT->edges())
{
int val = 0;
if (count % (3 + i) < start)
val = count % (3 + i);
else
val = count % (3 + i) + unused;
SET_TR(t, val);
}
}
// All accset on all transitions
for (auto i: { 0, 1 })
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
for (auto acc = 0; acc < 5 + i; ++acc)
SET_TR(t, acc);
}
// Some random automata
std::vector<std::vector<int>> cont_sets;
for (auto i = 0; i <= 6; ++i)
{
std::vector<int> cont_set;
for (auto j = 0; j < i; ++j)
cont_set.push_back(j);
cont_sets.push_back(cont_set);
}
for (auto min: { 0, 1 })
{
for (auto num_sets: { 1, 2, 5, 6 })
for (auto i = 0; i < 10; ++i)
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
{
auto nb_acc = std::rand() % (num_sets - min + 1) + min;
std::random_shuffle(cont_sets[num_sets].begin(),
cont_sets[num_sets].end());
for (auto j = 0; j < nb_acc; ++j)
SET_TR(t, cont_sets[num_sets][j]);
}
}
for (auto num_sets: {2, 3})
for (auto even: {0, 1})
if ((num_sets - 1) * 2 + even < 6)
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
{
auto nb_acc = std::rand() % (num_sets - min + 1) + min;
std::random_shuffle(cont_sets[num_sets].begin(),
cont_sets[num_sets].end());
for (auto j = 0; j < nb_acc; ++j)
{
auto value = cont_sets[num_sets][j] * 2 + even;
SET_TR(t, value);
}
}
}
}
return result;
}
static std::vector<std::tuple<spot::acc_cond::acc_code, bool, bool, unsigned>>
generate_acc()
{
std::vector<std::tuple<spot::acc_cond::acc_code, bool, bool, unsigned>>
result;
for (auto max: { true, false })
for (auto odd: { true, false })
for (auto num_sets: { 0, 1, 2, 5, 6 })
result.emplace_back(spot::acc_cond::acc_code::parity(max, odd,
num_sets), max, odd, num_sets);
return result;
}
static bool is_included(spot::const_twa_graph_ptr left,
spot::const_twa_graph_ptr right, bool first_left)
{
auto tmp = spot::dualize(right);
auto product = spot::product(left, tmp);
if (!product->is_empty())
{
std::cerr << "======Not included======" << std::endl;
if (first_left)
std::cerr << "======First automaton======" << std::endl;
else
std::cerr << "======Second automaton======" << std::endl;
spot::print_hoa(std::cerr, left);
std::cerr << std::endl;
if (first_left)
std::cerr << "======Second automaton======" << std::endl;
else
std::cerr << "======First automaton======" << std::endl;
spot::print_hoa(std::cerr, right);
std::cerr << std::endl;
if (first_left)
std::cerr << "======!Second automaton======" << std::endl;
else
std::cerr << "======!First automaton======" << std::endl;
spot::print_hoa(std::cerr, tmp);
std::cerr << std::endl;
if (first_left)
std::cerr << "======First X !Second======" <<std::endl;
else
std::cerr << "======Second X !First======" <<std::endl;
spot::print_hoa(std::cerr, product);
std::cerr << std::endl;
return false;
}
return true;
}
static bool are_equiv(spot::const_twa_graph_ptr left,
spot::const_twa_graph_ptr right)
{
return is_included(left, right, true) && is_included(right, left, false);
}
static bool is_right_parity(spot::const_twa_graph_ptr aut,
spot::parity_kind target_kind,
spot::parity_style target_style,
bool origin_max, bool origin_odd, unsigned num_sets)
{
bool is_max;
bool is_odd;
if (!aut->acc().is_parity(is_max, is_odd))
return false;
bool target_max;
bool target_odd;
if (aut->num_sets() <= 1 || num_sets <= 1
|| target_kind == spot::parity_kind_any)
target_max = is_max;
else if (target_kind == spot::parity_kind_max)
target_max = true;
else if (target_kind == spot::parity_kind_min)
target_max = false;
else
target_max = origin_max;
if (aut->num_sets() == 0 || num_sets == 0
|| target_style == spot::parity_style_any)
target_odd = is_odd;
else if (target_style == spot::parity_style_odd)
target_odd = true;
else if (target_style == spot::parity_style_even)
target_odd = false;
else
target_odd = origin_odd;
if (!(is_max == target_max && is_odd == target_odd))
{
std::cerr << "======Wrong accceptance======" << std::endl;
std::string kind[] = { "max", "min", "same", "any" };
std::string style[] = { "odd", "even", "same", "any" };
std::cerr << "target: " << kind[target_kind] << ' '
<< style[target_style] << std::endl;
std::cerr << "origin: " << kind[origin_max ? 0 : 1] << ' '
<< style[origin_odd ? 0 : 1] << ' '
<< num_sets << std::endl;
std::cerr << "actually: " << kind[is_max ? 0 : 1] << ' '
<< style[is_odd ? 0 : 1] << ' '
<< aut->num_sets() << std::endl;
std::cerr << std::endl;
return false;
}
return true;
}
static bool is_almost_colored(spot::const_twa_graph_ptr aut)
{
for (auto t: aut->edges())
if (t.acc.count() > 1)
{
std::cerr << "======Not colored======" << std::endl;
spot::print_hoa(std::cerr, aut);
std::cerr << std::endl;
return false;
}
return true;
}
static bool is_colored_printerr(spot::const_twa_graph_ptr aut)
{
bool result = is_colored(aut);
if (!result)
{
std::cerr << "======Not colored======" << std::endl;
spot::print_hoa(std::cerr, aut);
std::cerr << std::endl;
}
return result;
}
static spot::parity_kind to_parity_kind(bool is_max)
{
if (is_max)
return spot::parity_kind_max;
return spot::parity_kind_min;
}
static spot::parity_style to_parity_style(bool is_odd)
{
if (is_odd)
return spot::parity_style_odd;
return spot::parity_style_even;
}
int main()
{
auto current_bdd = spot::make_bdd_dict();
spot::srand(0);
auto parity_kinds =
{
spot::parity_kind_max,
spot::parity_kind_min,
spot::parity_kind_same,
spot::parity_kind_any,
};
auto parity_styles =
{
spot::parity_style_odd,
spot::parity_style_even,
spot::parity_style_same,
spot::parity_style_any,
};
auto acceptance_sets = generate_acc();
auto automata_tuples = generate_aut(current_bdd);
unsigned num_automata = automata_tuples.size();
unsigned num_acceptance = acceptance_sets.size();
std::cerr << "num of automata: " << num_automata << '\n';
std::cerr << "num of acceptance expression: " << num_acceptance << '\n';
for (auto acc_tuple: acceptance_sets)
for (auto& aut_tuple: automata_tuples)
{
auto& aut = aut_tuple.first;
auto aut_num_sets = aut_tuple.second;
auto acc = std::get<0>(acc_tuple);
auto is_max = std::get<1>(acc_tuple);
auto is_odd = std::get<2>(acc_tuple);
auto acc_num_sets = std::get<3>(acc_tuple);
if (aut_num_sets <= acc_num_sets)
{
aut->set_acceptance(acc_num_sets, acc);
// Check change_parity
for (auto kind: parity_kinds)
for (auto style: parity_styles)
{
auto output = spot::change_parity(aut, kind, style);
assert(is_right_parity(output, kind, style,
is_max, is_odd, acc_num_sets)
&& "change_parity: wrong acceptance.");
assert(are_equiv(aut, output)
&& "change_parity: not equivalent.");
assert(is_almost_colored(output)
&& "change_parity: too many acc on a transition");
}
// Check colorize_parity
for (auto keep_style: { true, false })
{
auto output = spot::colorize_parity(aut, keep_style);
assert(is_colored_printerr(output)
&& "colorize_parity: not colored.");
assert(are_equiv(aut, output)
&& "colorize_parity: not equivalent.");
auto target_kind = to_parity_kind(is_max);
auto target_style = keep_style ? to_parity_style(is_odd)
: spot::parity_style_any;
assert(is_right_parity(output, target_kind, target_style,
is_max, is_odd, acc_num_sets)
&& "change_parity: wrong acceptance.");
}
// Check cleanup_parity
for (auto keep_style: { true, false })
{
auto output = spot::cleanup_parity(aut, keep_style);
assert(is_almost_colored(output)
&& "cleanup_parity: too many acc on a transition.");
assert(are_equiv(aut, output)
&& "cleanup_parity: not equivalent.");
auto target_kind = to_parity_kind(is_max);
auto target_style = keep_style ? to_parity_style(is_odd)
: spot::parity_style_any;
assert(is_right_parity(output, target_kind, target_style,
is_max, is_odd, acc_num_sets)
&& "cleanup_parity: wrong acceptance.");
}
}
}
std::random_shuffle(automata_tuples.begin(), automata_tuples.end());
unsigned num_left = 15;
unsigned num_right = 15;
unsigned acc_index = 0;
unsigned nb = 0;
// Parity product and sum
for (unsigned left_index = 0; left_index < num_left; ++left_index)
{
auto& aut_tuple_first = automata_tuples[left_index % num_automata];
auto& left = aut_tuple_first.first;
auto aut_num_sets_first = aut_tuple_first.second;
while (std::get<3>(acceptance_sets[acc_index]) < aut_num_sets_first)
acc_index = (acc_index + 1) % num_acceptance;
auto acc_tuple_first = acceptance_sets[acc_index];
acc_index = (acc_index + 1) % num_acceptance;
auto acc_first = std::get<0>(acc_tuple_first);
auto acc_num_sets_first = std::get<3>(acc_tuple_first);
left->set_acceptance(acc_num_sets_first, acc_first);
for (unsigned right_index = 0; right_index < num_right; ++right_index)
{
auto& aut_tuple_second =
automata_tuples[(num_left + right_index) % num_automata];
auto& right = aut_tuple_second.first;
auto aut_num_sets_second = aut_tuple_second.second;
while (std::get<3>(acceptance_sets[acc_index]) < aut_num_sets_second)
acc_index = (acc_index + 1) % num_acceptance;
auto acc_tuple_second = acceptance_sets[acc_index];
acc_index = (acc_index + 1) % num_acceptance;
auto acc_second = std::get<0>(acc_tuple_second);
auto acc_num_sets_second = std::get<3>(acc_tuple_second);
right->set_acceptance(acc_num_sets_second, acc_second);
auto result_prod = spot::parity_product(left, right);
auto ref_prod = spot::product(left, right);
if (!are_equiv(result_prod, ref_prod))
{
std::cerr << nb << ": parity_product: Not equivalent.\n"
<< "=====First Automaton=====\n";
spot::print_hoa(std::cerr, left);
std::cerr << "=====Second Automaton=====\n";
spot::print_hoa(std::cerr, right);
assert(false && "parity_product: Not equivalent.\n");
}
assert(is_colored_printerr(result_prod)
&& "parity_product: not colored.");
assert(is_right_parity(result_prod, spot::parity_kind_any,
spot::parity_style_any,
true, true, 2)
&& "parity_product: not a parity acceptance condition");
auto result_sum = spot::parity_product_or(left, right);
auto ref_sum = spot::product_or(left, right);
if (!are_equiv(result_sum, ref_sum))
{
std::cerr << nb << ": parity_product_or: Not equivalent.\n"
<< "=====First Automaton=====\n";
spot::print_hoa(std::cerr, left);
std::cerr << "=====Second Automaton=====\n";
spot::print_hoa(std::cerr, right);
assert(false && "parity_product_or: Not equivalent.\n");
}
assert(is_colored_printerr(result_sum)
&& "parity_product_or: not colored.");
assert(is_right_parity(result_sum, spot::parity_kind_any,
spot::parity_style_any,
true, true, 2)
&& "parity_product_or: not a parity acceptance condition");
++nb;
}
}
return 0;
}
| mcc-petrinets/formulas | spot/tests/core/parity.cc | C++ | mit | 16,809 |
namespace Meeko
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Meeko";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
| henrikac/Me-e-ko | Meeko/Meeko/Form1.Designer.cs | C# | mit | 1,734 |
title: Hey Boss, Event Sourcing Can Fix That!
author:
name: Emily Stamey
twitter: elstamey
url: http://elstamey.com
theme: elstamey/reveal-cleaver-theme
style: basic-style.css
output: hey_boss.html
controls: true
--
# Event Sourcing Can Fix That!
--

--

--
# Basics of Event Sourcing
- pull from library 11-45 with thinning
--
# Scholarships
- replaced in pieces
- added DDD & ES & CQRS beside complex framework spaghetti
- separation of concerns
- cleaner history and reports of what had been done
--

--

--






--

--

--

--

--

--
## Dependency Injection
- add slide from bootstrapping through controllers and rearrange
--
## Legacy
- this was an example of replacing the code in pieces
- could have replaced only one part or a few
- really powerful to see which parts of your application could benefit from event sourcing
- and finding the simplest way to implement
--
# Student Enrollment Process
- rewrote
- ES to follow the process
- status drop-down versus events
--

--
# Diagram

--
# Session Threats Report
- multiple daemons running parts of code and the UI consumes the results of the analysis
- complex DB queries
- reports are slow to generate on-demand
--
## Event: SessionDiscovered
- after validation to determine whether we have a valid session, we log a new event
--
### new SessionDiscovered( attributes we need to know )
--
## Event: SessionDiscovered
- session id
- start time
- protocol
- source ip
- destination ip
- source port
- destination port
--
## Event: SessionScored
- session id
- threat contributor
- score
--
## Event: FileScored
- after validation that a file has matched a signature, we log a new event
### new FileScored( attributes we need to know )
--
## Event: FileScored
- file id
- session id
- integration
- score
- signature that found it
--
## Event: FileRescored
- after validation that a file has matched a signature and that it has been scored before\n- we log a new event
### new FileRescored( attributes we need to know )
--
## Event: FileRescored
- file id
- session id
- integration
- new score
- signature that found it
--
## Projection: Session
- listens for SessionDiscovered events
- creates a new row in a table with the session details and a null score
- listens for SessionScored events
- finds the session in the table and updates the score and score contributor
--
## Projection: Report for Top Threats by Hash
- listens for FileScored and FileRescored Events
- looks up details of file by the file id
- adds a row to table with
- file id
- file md5 hash
- the filename
- file type
- the score
- signature that scored it
- source ip
- destination ip
- protocol
--
## Read Model: Top Threats
methods:
- top 10 threats by the file hash
- this excludes hits I'm not allowed to see by the signature that did the scoring
- gets a current hit count of only the records I can see
- top threats by file type
- top threats by source/destination ip pairs
- top threats by protocol
--
## Good Stuff!
- works well in our environment where we have multiple applications doing different things
- full audit log of what has happened in our environment
- the results of those events can be optimized for read to shorten the time to retrieve data
- separate the logic of what an event means based on context and purpose
- only display results that a user is allowed to see
- flexible to change, our interpretation of events can change, and we can rebuild projections without losing the full history
--
## Signatures
- history of changes
- past scores/score history
--
## Rescans and history from rescans
- what can we see?
--
## Efficiency
- With events written, can process them for multiple contexts
- Speed up scans by delaying the writes to the report
- Speed up reports by building from events/optimized for read
--
# Thank you
 | elstamey/elstamey.github.io | hey_boss.md | Markdown | mit | 4,831 |
// Copyright (c) 2016, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Address Template', {
refresh: function(frm) {
if(frm.is_new() && !frm.doc.template) {
// set default template via js so that it is translated
frappe.call({
method: 'frappe.geo.doctype.address_template.address_template.get_default_address_template',
callback: function(r) {
frm.set_value('template', r.message);
}
});
}
}
});
| rohitwaghchaure/frappe | frappe/geo/doctype/address_template/address_template.js | JavaScript | mit | 488 |
---
title: "Packages for Better React Experience"
categories:
- Web
tags:
- React
---
Here are some components and utils that will make your React developement even more enjoyable.
# React Components
## [React Date Picker](https://github.com/Hacker0x01/react-datepicker)
Feature rich, configurable date picker for react. Worked everytime without any issue.
## [React DnD](https://github.com/gaearon/react-dnd)
Drag and drop is not so easy to handle. React Dnd makes it easy with React.
## [React Ace](https://github.com/securingsincity/react-ace)
When you want a code editor in your react app, React Ace is the package you want. React ace is a wrapper
for [Ace editor](https://ace.c9.io/).
## [React Modal](https://github.com/reactjs/react-modal)
Modal dialog in react.
## [React Skylight](https://github.com/marcio/react-skylight)
Skylight makes modal dialogs easy, which is something I discovered recently.
## [React Dazzle](https://github.com/Raathigesh/Dazzle)
Ok, I snuck one of mine in! Dazzle makes building dashboards easier.
# Util Libraries
## [Classnames](https://github.com/JedWatson/classnames)
Working with CSS classes could be tricky when you want to append and remove based on conditions. If you have a requiment to work with classes,
this package is a must.
## [Axios](https://github.com/mzabriskie/axios)
Axios is a promise based HTTP client. Very nice API and I really enjoyed working with this library. You might
also want to check [axios mock adapter](https://github.com/ctimmerm/axios-mock-adapter) which makes testing easier.
## [Enzyme](https://github.com/airbnb/enzyme)
If you are writting tests for your react components, which you should, do your self a favour and use Enzyme.
# Others
## [Semantic UI](https://github.com/Semantic-Org/Semantic-UI)
As a developer, working with CSS to get things to look the way I wanted was always challenging. Things changed
when I discovered Semantic UI. An awesome set of UI elements to pick from and they compose extremly well. Semantic UI
is also getting its official React components [here](https://github.com/TechnologyAdvice/stardust). Keep an eye for it as well.
| Raathigesh/Raathigesh.github.io | _posts/2016-07-2-Usefull-React-Components.md | Markdown | mit | 2,156 |
using System.Web;
using System.Web.Optimization;
namespace InsectCatalog
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.min.js",
"~/Scripts/angular-route.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| NewEvolution/InsectCatalog | InsectCatalog/App_Start/BundleConfig.cs | C# | mit | 1,459 |
class NdlStatAccept < ActiveRecord::Base
default_scope :order => :region
belongs_to :ndl_statistic
attr_accessible :donation, :production, :purchase, :region, :item_type
item_type_list = ['book', 'magazine', 'other_micro', 'other_av', 'other_file']
region_list = ['domestic', 'foreign', 'none']
validates_presence_of :item_type
validates_inclusion_of :item_type, :in => item_type_list
validates_inclusion_of :region, :in => region_list
end
| MiraitSystems/enju_trunk_statistics | app/models/ndl_stat_accept.rb | Ruby | mit | 462 |
# Arduino Yun Experiment
This project allows temperature and light sensor readings to be output as a web app.
## Board Setup

## Sketch Setup
Upload `api/api.ino` to the Yun. You should see `Waiting...` on the first row of the LCD display. Test the API in a browser by going to:
http://arduino.local/arduino/temperature
http://arduino.local/arduino/light
You should see output such as the examples below:
```javascript
{
"temperature": 20.58,
"measure": "C"
}
```
```javascript
{
"light": 10,
"measure": "lx"
}
```
The LCD display will also output the reading requsted as well as the current value.
## Web App Setup
Run the deploy script as follows to copy the files to the public `www` folder on the Yun web server:
./deploy
This script will prompt for a password unless you have setup SSH public key access.
Navigate to `http://arduino.local/yun.html` and you should see the web app running.
| pads/arduino-yun-experiment | README.md | Markdown | mit | 1,037 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct(){
parent:: __construct();
$this->load->model('engine_model');
}
public function add_url(){
$url = $_POST['url'];
$id = $_POST['id'];
$this->engine_model->add_user_url($id, $url);
}
public function remove_url(){
$url = $_POST['value'];
$this->engine_model->remove_user_url($url);
}
public function logout(){
if (!empty( $this->input->cookie('user') )) {
delete_cookie('user');
}
$this->load->view('welcome_message');
}
} | dav34111/bookmarks | application/controllers/user.php | PHP | mit | 591 |
<!DOCTYPE html>
<html lang="en">
<!--
Copyright 2021 David Stein
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> stein | resume </title><!-- Begin Jekyll SEO tag v2.6.1 -->
<meta name="generator" content="Jekyll v3.8.7" />
<meta property="og:title" content="resume" />
<meta name="author" content="David Stein" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="stein’s web site" />
<meta property="og:description" content="stein’s web site" />
<link rel="canonical" href="https://davidbstein.com/resume" />
<meta property="og:url" content="https://davidbstein.com/resume" />
<meta property="og:site_name" content="stein" />
<script type="application/ld+json">
{"description":"stein’s web site","author":{"@type":"Person","name":"David Stein"},"@type":"WebPage","url":"https://davidbstein.com/resume","headline":"resume","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="/assets/main.css"><link type="application/atom+xml" rel="alternate" href="https://davidbstein.com/feed.xml" title="stein" /></head>
<body><header id="site-header">
<div id="header-background" ></div>
<nav>
<div class="title" >
<a href="/" >stein</a>
</div>
<ul >
<li ><a href="/blog">blog</a></li>
<li ><a href="/about">about</a></li>
</ul></div>
</nav>
</header>
<div id="header-underlay"></div>
<script>
/*for source and licence see https://github.com/davidbstein/header-hider */
!function(){var i=function(){if(this.scrollY=0,this.old_scroll=window.onscroll,this.header=document.getElementsByTagName("header")[0],null==this.header)throw"in order to use the header hider you must have a <header>";this.header.style.transition="margin-top 0.2s ease-out 0s;",this.header_height=header.offsetHeight,this.hidden=!1,this.hide=function(){this.header.style.marginTop=-this.header_height+"px",this.hidden=!0}.bind(this),this.unhide=function(){this.header.style.marginTop=0,this.hidden=!1}.bind(this),this.unhide(),window.onscroll=function(){this.old_scroll&&this.old_scroll();var i=window.pageYOffset;i<64||i<this.scrollY?this.unhide():this.hide(),this.scrollY=i}.bind(this)};window.onload?window.onload=function(h){(void 0)(h),i()}:window.onload=i}();
</script>
<main aria-label="Content">
<div class="wrapper">
<article class="post">
<header class="post-header">
<h1 class="post-title">resume</h1>
</header>
<div class="post-content">
<p>My resume was last updated in January 2021.</p>
<p><a href="/static/resume.pdf">download pdf</a></p>
</div>
</article>
</div>
</main>
<footer>Copyright (c) David Stein</footer>
</body>
</html>
| davidbstein/davidbstein.com | docs/resume.html | HTML | mit | 3,831 |
require "day/tracker/version"
module Day
module Tracker
class Cli < Thor
FILE_PATH = File.expand_path("~/.day-tracker")
def initialize(*args)
super
FileUtils.touch FILE_PATH
end
desc "list", "list recorded days"
def list
puts File.read(FILE_PATH)
end
desc "add PROJECT_NAME [FRACTION]", "add a project for today"
def add(project, fraction=1)
entry = format_entry(project, fraction)
return if entry_exists?(entry)
open(FILE_PATH, 'a') do |file|
file.puts entry
end
list
end
no_commands do
def entry_exists?(entry)
File.readlines(FILE_PATH).grep(entry).any?
end
def format_entry(project, fraction)
Time.now.strftime("%B %d - #{project} - #{formatted_fraction(fraction)}")
end
def formatted_fraction(fraction)
{
"0.5" => "half",
".5" => "half",
"1" => "full"
}[fraction]
end
end
default_task :list
end
end
end
| opsb/day-tracker | lib/day/tracker.rb | Ruby | mit | 1,005 |
<!DOCTYPE html>
<html>
<head>
<title>metamachine v.0.03</title>
<meta charset="UTF-8">
<link href="style.css" type="text/css" rel="stylesheet">
<!--- <script type="text/javascript" src="main.js" async></script> -->
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="querymain.js"></script>
<script type="text/javascript" src="LifemirrorPlayer.js"></script>
</head>
<body>
<!--- <div id="player"> -->
<div id="middle">
<div id="header">
<h1>metamachine</h1>
<span>v.0.03</span>
</div>
<div id="menu">
<input id="attr1" type="range" min="0" max="5" step="1" value"1">Liebe</input><br>
<input id="attr2" type="range" min="0" max="5" step="1" value"1">Glück</input><br>
<input id="attr3" type="range" min="0" max="5" step="1" value"1">Tradition</input><br>
<input id="attr4" type="range" min="0" max="5" step="1" value"1">Abenteuer</input><br>
<input id="attr5" type="range" min="0" max="5" step="1" value"1">Perfektion</input><br>
<br>
<button id="generatePlaylist">Playliste generieren</button>
<br>
<p id="playlist"></p>
<div id="debug">
<ul id="XMLread"></ul>
</div>
</div>
</div>
</body>
</html>
| marvmartz/Project_MetaJS | index.html | HTML | mit | 1,271 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.