code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
--- layout: page title: Maddox - Oconnell Wedding date: 2016-05-24 author: Emma Mcfarland tags: weekly links, java status: published summary: Etiam eu accumsan lorem. Morbi faucibus velit nec. banner: images/banner/meeting-01.jpg booking: startDate: 10/18/2017 endDate: 10/20/2017 ctyhocn: WINWVHX groupCode: MOW published: true --- Etiam aliquam eros nec nunc faucibus, nec auctor libero faucibus. Nunc nisi sem, congue quis nulla sit amet, porttitor ullamcorper ante. In elementum lacus magna, sed rutrum nunc consectetur dictum. Donec finibus ac nisi vitae consequat. Ut et semper nibh, ac condimentum nisi. Etiam ornare varius massa, nec commodo sapien. Proin aliquet aliquam pulvinar. Proin commodo mauris gravida finibus iaculis. Vestibulum a turpis neque. Etiam varius, neque quis tincidunt lobortis, lectus lacus lobortis magna, vitae egestas metus nibh vitae turpis. Vestibulum ac fringilla quam, id mollis nulla. Fusce a ipsum neque. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas laoreet justo id auctor venenatis. Curabitur rutrum eget erat eget rhoncus. Praesent non orci id nisl rhoncus pulvinar. Suspendisse egestas nulla erat, id suscipit nisi semper vitae. Mauris metus neque, dignissim vitae pulvinar et, euismod ac massa. Cras malesuada pretium erat, eget rhoncus lacus rutrum nec. Vestibulum sed mauris sit amet ligula scelerisque interdum. Phasellus lacinia condimentum enim. Mauris id tortor hendrerit, mollis ex et, egestas libero. Aliquam erat volutpat. 1 Sed tincidunt augue vel orci porttitor feugiat 1 Vestibulum porta odio eget elit volutpat, ut blandit quam efficitur 1 Nunc interdum dolor sit amet elit viverra, et fermentum leo gravida 1 Cras ut massa eu ex varius porttitor vel ut odio. In nec leo et quam tincidunt vestibulum non at lectus. Vivamus pharetra aliquam vulputate. Sed eget rhoncus mi. Curabitur venenatis dolor sit amet finibus vulputate. Nunc eleifend malesuada ipsum, ac suscipit eros hendrerit eget. Ut et egestas mauris. Suspendisse ac ligula velit. Sed pulvinar purus eu dolor scelerisque, commodo efficitur eros dictum. Aenean suscipit sit amet nisi a tincidunt. Nulla cursus vel augue vitae viverra. Aliquam sodales hendrerit enim, imperdiet mattis urna. Suspendisse vitae ipsum dui. Nunc facilisis iaculis ex, et ornare massa. Etiam eget dapibus lorem. Aenean vehicula venenatis erat. Suspendisse ultrices sed dolor elementum luctus. Curabitur convallis gravida lobortis. Aenean sed mauris tortor.
KlishGroup/prose-pogs
pogs/W/WINWVHX/MOW/index.md
Markdown
mit
2,510
using System; using System.ServiceModel; namespace SoapCore.Tests.Wsdl.Services { [ServiceContract] public interface INullableEnumService { [OperationContract] NulEnum? GetEnum(string text); } public class NullableEnumService : INullableEnumService { public NulEnum? GetEnum(string text) { throw new NotImplementedException(); } } }
DigDes/SoapCore
src/SoapCore.Tests/Wsdl/Services/INullableEnumService.cs
C#
mit
355
var Game = { map: { width: 980, height: 62 * 12 }, tiles: { size: 62, count: [100, 12] }, sprite: { 8: 'LAND_LEFT', 2: 'LAND_MID', 10: 'LAND_RIGHT', 9: 'LAND', 5: 'WATER_TOP', 12: 'WATER', 4: 'STONE_WITH_MONEY', 11: 'STONE', 6: 'CACTUS', 13: 'GRASS', 7: 'START', 1: 'END' } }; Crafty.init(Game.map.width, Game.map.height, document.getElementById('game')); Crafty.background('url(./assets/images/bg.png)'); Crafty.scene('Loading');
luin/Love-and-Peace
src/game.js
JavaScript
mit
508
# Demo mode Smart meter has a demo mode that is intended to make demonstrating the product and system-level testing easier. Demo mode allows creating situations that would be hard to create otherwise (e.g. connection to cloud is lost between price request and parking event registering). Demo mode is to be used in development only. This document instructs how to configure, enable and use demo mode. ## Enable demo mode To enable demo mode, add line **demoMode;1** to smart meter configuration (config/global.txt). To disable demo mode, change this to **demoMode;0** or remove the line. ## Configure demo mode Demomode has it's own configuration file, that will be installed to **config/demoConfig.txt** in deploy directory after successful build. Edit this file to change demo mode settings. The configuration file consists of following lines: - Empty lines, which are ignored. - Comments starting with '#', which are ignored. - Price specification. - Key-value pairs separated with semicolon. Price specification sets a predefined value for parking price information. Give price information in format **price;price per hour (EUR):time limit (min):resolution (min)**, e.g. **price;1.2:120:1**. If price information is left unspecified, price is fetched from firebase like normally. Every other key-value pair will specify the number of parking event registering request and it's demonstrated value. The key represents the number of parking registering request. The first parking event reqistering request is indexed as '0', and each request after that will increase the index by one. Not all requests need to be defined. If an index is missing from configuration, smart meter will handle requests as in normal mode. The second part (value) is an integer representing the situation to be demonstrated on request specified by the key. The possible values are listed in the table below. Value | Explanation ---|--- 0 | Replace the actual payment token in request with a valid test token. Request is then forwarded to the cloud, and handled as normally. 1 | Request to the cloud times out. The request is not actually sent to the cloud, but smart meter will write a timeout error message to BLENode's response fifo. 2 | Payment token is invalid. The request is not actually sent to the cloud, but smart meter will write invalid token error message to BLENode's response fifo. 3 | Other error in the cloud. The request is not actually sent to the cloud, but smart meter will write error message to BLENode's response fifo. 4 | Forced Ok response. The request is not actually sent to the cloud, but smart meter will write OK message to BLENode's response fifo. any other | Unknown command. Smart meter responds with error message about unknown command. Example configuration: ``` # My demo config (config/demoConfig.txt) # Price is not fetched from cloud. price;1.2:120:1 # First request's payment token will be replaced with a valid test token 0;0 # Second request will time out. 1;1 # Third request is not defined, and is therefore handled normally. # Fourh request will have an invalid payment token, even if the actual token was valid. 3;2 # End of configuration. All requests after 4th are handled as normally. ``` ## Using demo mode Other than separate configuration, demo mode needs no user guidance. Use smart meter as normally. Requests defined in configuration will be handled according to specified action, and others are handled normally.
DriverCity/SPARK
src/smart_meter/doc/dev/demo_mode.md
Markdown
mit
3,474
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>uncss.io</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="css/main.min.css"/> <!--[if lt IE 9]> <script src="js/vendor/html5-3.6-respond-1.1.0.min.js"></script> <![endif]--> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <div class="jumbotron"> <div class="container"> <h1>U<span class="title-capitalize">n</span>CSS<span class="title-capitalize">.io</span></h1> <h2>Automatically remove unused CSS rules to speed up your site load time</h2> <ol> <li>Enter the URL of your page</li> <li>We will detect all the CSS files that you are loading and we will remove all the unused CSS rules</li> <li>Copy paste that new consolidated CSS file. That's the only rules you will need for that page.</li> <li>See the documentation on <a href="https://github.com/giakki/uncss">GitHub</a></li> </ol> <hr> <div class="row"> <form class="col-lg-8 col-lg-offset-2"> <div class="input-group"> <input type="text" class="form-control" placeholder="Insert your URL here" id="url-input" name="url-input"> <span class="input-group-btn"> <button class="btn btn-default" id="get-css" type="submit">Get CSS!</button> </span> </div> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-6 testimonial"> <div class="col-lg-10"> <p>"The fastest rule is the one that doesn’t exist. There’s a common strategy to combine stylesheet “modules” into one file for production. This makes for one big collection of rules, where some (lots) of them are likely not used by particular part of the site/application. Getting rid of unused rules is one of the best things your can do to optimize CSS performance"</p> <p>Source: <a href="http://perfectionkills.com/profiling-css-for-fun-and-profit-optimization-notes/">@kangax - perfectionkills.com</a></p> </div> <div class="col-lg-2"> <a href="https://twitter.com/kangax"> <img class="img-circle" alt="@kangax" src="img/kangax.png"> </a> </div> </div> <div class="col-lg-6 testimonial"> <div class="col-lg-10"> <p> "make sure that you get all your css as early as possible. Concatenate css files, minify them, remove redundant rules. Anything you can do to accelerate css, fetching of css, will help you get faster user experience"</p> <p>Ilya Grigorik (@igrigorik) is a web performance engineer and developer advocate at Google, where his focus is on making the web fast and driving adoption of performance best practices at Google and beyond.</p> <p><a href="http://parleys.com/play/5148922b0364bc17fc56ca0e/chapter45/about">Source</a></p> </div> <div class="col-lg-2"> <a href="https://twitter.com/igrigorik"> <img class="img-circle" alt="@igrigorik" src="img/igrigorik.png"> </a> </div> </div> </div> <div class="modal fade" id="results-modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" id="results-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Your Results!</h4> </div> <div class="modal-body" id="results-body"> <div id="spinner">Fetching results...</div> </div> <div class="modal-footer hidden" id="modal-footer"> <a href="" class="btn btn-primary" id="view-button">View stylesheet</a> <button type="button" class="btn btn-primary" id="copy-button">Copy to clipboard</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <hr> <footer> <p>&copy; Giacomo Martino, Xavier Damman, 2014</p> </footer> </div> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="js/scripts.min.js"></script> </body> </html>
giakki/uncss.io
dist/index.html
HTML
mit
5,689
#!/usr/bin/python import os import re from lxml import etree as et import pcbmode.config as config from . import messages as msg # pcbmode modules from . import utils from .point import Point def makeExcellon(manufacturer='default'): """ """ ns = {'pcbmode':config.cfg['ns']['pcbmode'], 'svg':config.cfg['ns']['svg']} # Open the board's SVG svg_in = utils.openBoardSVG() drills_layer = svg_in.find("//svg:g[@pcbmode:sheet='drills']", namespaces=ns) excellon = Excellon(drills_layer) # Save to file base_dir = os.path.join(config.cfg['base-dir'], config.cfg['locations']['build'], 'production') base_name = "%s_rev_%s" % (config.brd['config']['name'], config.brd['config']['rev']) filename_info = config.cfg['manufacturers'][manufacturer]['filenames']['drills'] add = '_%s.%s' % ('drills', filename_info['plated'].get('ext') or 'txt') filename = os.path.join(base_dir, base_name + add) with open(filename, "wb") as f: for line in excellon.getExcellon(): f.write(line) class Excellon(): """ """ def __init__(self, svg): """ """ self._svg = svg self._ns = {'pcbmode':config.cfg['ns']['pcbmode'], 'svg':config.cfg['ns']['svg']} # Get all drill paths except for the ones used in the # drill-index drill_paths = self._svg.findall(".//svg:g[@pcbmode:type='component-shapes']//svg:path", namespaces=self._ns) drills_dict = {} for drill_path in drill_paths: diameter = drill_path.get('{'+config.cfg['ns']['pcbmode']+'}diameter') location = self._getLocation(drill_path) if diameter not in drills_dict: drills_dict[diameter] = {} drills_dict[diameter]['locations'] = [] drills_dict[diameter]['locations'].append(location) self._preamble = self._createPreamble() self._content = self._createContent(drills_dict) self._postamble = self._createPostamble() def getExcellon(self): return (self._preamble+ self._content+ self._postamble) def _createContent(self, drills): """ """ ex = [] for i, diameter in enumerate(drills): # This is probably not necessary, but I'm not 100% certain # that if the item order of a dict is gurenteed. If not # the result can be quite devastating where drill # diameters are wrong! # Drill index must be greater than 0 drills[diameter]['index'] = i+1 ex.append("T%dC%s\n" % (i+1, diameter)) ex.append('M95\n') # End of a part program header for diameter in drills: ex.append("T%s\n" % drills[diameter]['index']) for coord in drills[diameter]['locations']: ex.append(self._getPoint(coord)) return ex def _createPreamble(self): """ """ ex = [] ex.append('M48\n') # Beginning of a part program header ex.append('METRIC,TZ\n') # Metric, trailing zeros ex.append('G90\n') # Absolute mode ex.append('M71\n') # Metric measuring mode return ex def _createPostamble(self): """ """ ex = [] ex.append('M30\n') # End of Program, rewind return ex def _getLocation(self, path): """ Returns the location of a path, factoring in all the transforms of its ancestors, and its own transform """ location = Point() # We need to get the transforms of all ancestors that have # one in order to get the location correctly ancestors = path.xpath("ancestor::*[@transform]") for ancestor in ancestors: transform = ancestor.get('transform') transform_data = utils.parseTransform(transform) # Add them up location += transform_data['location'] # Add the transform of the path itself transform = path.get('transform') if transform != None: transform_data = utils.parseTransform(transform) location += transform_data['location'] return location def _getPoint(self, point): """ Converts a Point type into an Excellon coordinate """ return "X%.6fY%.6f\n" % (point.x, -point.y)
ddm/pcbmode
pcbmode/utils/excellon.py
Python
mit
4,661
'use strict'; import _ from 'lodash'; import bluebird from 'bluebird'; import fs from 'fs'; import requireDir from 'require-dir'; import Logger from '../../logger'; bluebird.promisifyAll(fs); function main() { const imports = _.chain(requireDir('./importers')) .map('default') .map((importer) => importer.run()) .value(); return Promise.all(imports); } Logger.info('base.data.imports.imports: Running...'); main() .then(() => { Logger.info('base.data.imports.imports: Done!'); process.exit(0); }) .catch((error) => { Logger.error('base.data.imports.imports:', error); process.exit(1); });
mehmetbajin/gt-course-surveys
server/src/server/base/data/imports/imports.js
JavaScript
mit
635
// FriendlyNameAttribute.cs created with MonoDevelop // User: ben at 1:31 P 19/03/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // using System; namespace EmergeTk.Model { public class FriendlyNameAttribute : Attribute { string name; public string Name { get { return name; } set { name = value; } } public string[] FieldNames { get { return fieldNames; } set { fieldNames = value; } } //field names are used for generating friendly names for vector types, such as enums. string[] fieldNames; public FriendlyNameAttribute() { } public FriendlyNameAttribute( string name ) { this.name = name; } } }
bennidhamma/EmergeTk
server/Model/FriendlyNameAttribute.cs
C#
mit
736
Ext.define('Category.view.GenericList', { extend: 'Ext.grid.Panel', alias: 'widget.genericlist', store: 'Generic', title: Raptor.getTag('category_header'), iconCls:'', initComponent: function() { this.columns = [{ header:Raptor.getTag('category_name'), dataIndex: 'name', flex: 1 }]; this.dockedItems = [{ dock: 'top', xtype: 'toolbar', items: [{ xtype: 'button', text: Raptor.getTag('add'), privilegeName:'insert', action:'addAction', iconCls:'icon-add' },{ xtype: 'button', text: Raptor.getTag('edit'), disabled:true, privilegeName:'edit/:id', action:'editAction', iconCls:'icon-edit' },{ xtype: 'button', text: Raptor.getTag('delete'), disabled:true, privilegeName:'delete/:id', action:'deleteAction', iconCls:'icon-del' }] }]; this.callParent(); } });
williamamed/Raptor.js
@raptorjs-production/troodon/Resources/category/js/app/view/GenericList.js
JavaScript
mit
1,321
using System; using static LanguageExt.Prelude; namespace LanguageExt.UnitsOfMeasure { /// <summary> /// Numeric VelocitySquared value /// Handles unit conversions automatically /// </summary> public struct VelocitySq : IComparable<VelocitySq>, IEquatable<VelocitySq> { readonly double Value; internal VelocitySq(double length) { Value = length; } public override string ToString() => Value + " m/s²"; public bool Equals(VelocitySq other) => Value.Equals(other.Value); public bool Equals(VelocitySq other, double epsilon) => Math.Abs(other.Value - Value) < epsilon; public override bool Equals(object obj) => obj == null ? false : obj is Length ? Equals((Length)obj) : false; public override int GetHashCode() => Value.GetHashCode(); public int CompareTo(VelocitySq other) => Value.CompareTo(other.Value); public VelocitySq Append(VelocitySq rhs) => new VelocitySq(Value + rhs.Value); public VelocitySq Subtract(VelocitySq rhs) => new VelocitySq(Value - rhs.Value); public VelocitySq Multiply(double rhs) => new VelocitySq(Value * rhs); public VelocitySq Divide(double rhs) => new VelocitySq(Value / rhs); public static VelocitySq operator *(VelocitySq lhs, double rhs) => lhs.Multiply(rhs); public static VelocitySq operator *(double lhs, VelocitySq rhs) => rhs.Multiply(lhs); public static VelocitySq operator +(VelocitySq lhs, VelocitySq rhs) => lhs.Append(rhs); public static VelocitySq operator -(VelocitySq lhs, VelocitySq rhs) => lhs.Subtract(rhs); public static VelocitySq operator /(VelocitySq lhs, double rhs) => lhs.Divide(rhs); public static double operator /(VelocitySq lhs, VelocitySq rhs) => lhs.Value / rhs.Value; public static bool operator ==(VelocitySq lhs, VelocitySq rhs) => lhs.Equals(rhs); public static bool operator !=(VelocitySq lhs, VelocitySq rhs) => !lhs.Equals(rhs); public static bool operator >(VelocitySq lhs, VelocitySq rhs) => lhs.Value > rhs.Value; public static bool operator <(VelocitySq lhs, VelocitySq rhs) => lhs.Value < rhs.Value; public static bool operator >=(VelocitySq lhs, VelocitySq rhs) => lhs.Value >= rhs.Value; public static bool operator <=(VelocitySq lhs, VelocitySq rhs) => lhs.Value <= rhs.Value; public Velocity Sqrt() => new Velocity(Math.Sqrt(Value)); public VelocitySq Round() => new VelocitySq(Math.Round(Value)); public VelocitySq Abs() => new VelocitySq(Math.Abs(Value)); public VelocitySq Min(VelocitySq rhs) => new VelocitySq(Math.Min(Value, rhs.Value)); public VelocitySq Max(VelocitySq rhs) => new VelocitySq(Math.Max(Value, rhs.Value)); public double MetresPerSecond2 => Value; } }
slantstack/Slant
src/Slant/DataTypes/UnitsOfMeasure/VelocitySq.cs
C#
mit
3,292
// // Lexer.cpp // lut-lang // // Created by Mehdi Kitane on 13/03/2015. // Copyright (c) 2015 H4314. All rights reserved. // #include "Lexer.h" #include <string> #include <regex> #include <iostream> #include "TokenType.h" #include "ErrorHandler.h" using std::cout; using std::endl; using std::smatch; using std::string; using std::regex_search; using std ::smatch; // Regexs const char keyword_str[] = "^(const |var |ecrire |lire )"; const char identifier_str[] = "^([a-zA-Z][a-zA-Z0-9]*)"; const char number_str[] = "^([0-9]*\\.?[0-9]+)"; const char single_operators_str[] = "^(\\+|-|\\*|\\/|\\(|\\)|;|=|,)"; const char affectation_str[] = "^(:=)"; const std::regex keyword(keyword_str); const std::regex identifier(identifier_str); const std::regex number(number_str); const std::regex single_operators(single_operators_str); const std::regex affectation(affectation_str); int Lexer::find_first_not_of(string str) { string::iterator it; int index = 0; for (it = str.begin(); it < str.end(); it++, index++) { switch ( str.at(index) ) { case ' ': this->column++; break; case '\t': break; case '\n': this->line++; this->column = 0; break; case '\r': break; case '\f': break; case '\v': default: return index; break; } } return -1; } string& Lexer::ltrim(string& s) { s.erase(0, find_first_not_of(s)); return s; } Lexer::Lexer(string inString) : inputString(inString) { this->currentToken = new ASTTokenNode(TokenType::INVALID_SYMBOL); this->line = 0; this->column = 0; this->column_next_incrementation = 0; } bool Lexer::has_next() { // remove spaces before analyzing // we remove left spaces and not right to handle cases like "const " ltrim(inputString); if ( inputString.length() <= 0 ) { currentToken = new ASTTokenNode(TokenType::ENDOFFILE); return false; } return true; } ASTTokenNode* Lexer::top() { return currentToken; } void Lexer::shift() { if ( !has_next() ) return; this->column += this->column_next_incrementation; std::smatch m; if ( !analyze(inputString, m) ) { ErrorHandler::getInstance().LexicalError(this->getLine(), this->getColumn(), inputString.at(0)); ErrorHandler::getInstance().outputErrors(); currentToken = new ASTTokenNode(TokenType::INVALID_SYMBOL); inputString.erase(0, 1); // not sure return; } this->column_next_incrementation = (int)m.length(); inputString = m.suffix().str(); } bool Lexer::analyze(string s, smatch &m) { if ( std::regex_search(inputString, m, keyword) ) { std::string currentTokenValue = m.str(); switch (currentTokenValue[0]) { case 'c': currentToken = new ASTTokenNode(TokenType::CONST); break; case 'v': currentToken = new ASTTokenNode(TokenType::VAR); break; case 'e': currentToken = new ASTTokenNode(TokenType::WRITE); break; case 'l': currentToken = new ASTTokenNode(TokenType::READ); break; default: #warning "symbole non reconnu" return false; } } else if ( std::regex_search(inputString, m, identifier) ) { std::string currentTokenValue = m.str(); currentToken = new ASTTokenNode(TokenType::ID, currentTokenValue); } else if ( std::regex_search(inputString, m, number) ) { std::string currentTokenValue = m.str(); currentToken = new ASTTokenNode(TokenType::VAL, currentTokenValue); } else if ( std::regex_search(inputString, m, single_operators) ) { std::string currentTokenValue = m.str(); switch (currentTokenValue[0]) { case '+': currentToken = new ASTTokenNode(TokenType::ADD, "+"); break; case '-': currentToken = new ASTTokenNode(TokenType::SUB, "-"); break; case '*': currentToken = new ASTTokenNode(TokenType::MUL, "*"); break; case '/': currentToken = new ASTTokenNode(TokenType::DIV, "/"); break; case '(': currentToken = new ASTTokenNode(TokenType::PO); break; case ')': currentToken = new ASTTokenNode(TokenType::PF); break; case ';': currentToken = new ASTTokenNode(TokenType::PV); break; case '=': currentToken = new ASTTokenNode(TokenType::EQ); break; case ',': currentToken = new ASTTokenNode(TokenType::V); break; default: #warning "symbole non reconnu" return false; } } else if ( std::regex_search(inputString, m, affectation) ) { currentToken = new ASTTokenNode(TokenType::AFF); } else { #warning "symbole non reconnu" return false; } return true; } int Lexer::getLine() { return this->line+1; } int Lexer::getColumn() { return this->column+1; }
hexa2/lut-lang
src/Lexer.cpp
C++
mit
4,860
#define NC0_As 0x0E #define NC0_B 0x0D #define NC1_C 0x15 #define NC1_Cs 0x1E #define NC1_D 0x1D #define NC1_Ds 0x26 #define NC1_E 0x24 #define NC1_F 0x2D #define NC1_Fs 0x2E #define NC1_G 0x2C #define NC1_Gs 0x36 #define NC1_A 0x35 #define NC1_As 0x3D #define NC1_B 0x3C #define NC2_C 0x43 #define NC2_Cs 0x46 #define NC2_D 0x44 #define NC2_Ds 0x45 #define NC2_E 0x4D #define NC2_F 0x54 #define NC2_Fs 0x55 #define NC2_G 0x5B #define NC2_Gs 0x5D #define NC2_A 0x12 #define NC2_As 0x58 #define NC2_B 0x1A #define NC_OCTAVEUP 0x05 #define NC_OCTAVEDOWN 0x06 #define NC_INSTRUP 0x04 #define NC_INSTRDOWN 0x0C #define NC_TABLEUP 0x03 #define NC_TABLEDOWN 0x0B #define NC_PULSETOGGLE 0x0A #define NC_TABLERUN 0x29 #define NC_NOP 0x00
iLambda/chipguitar
firmware/inc/keycodes.h
C
mit
1,058
<?php /** * This file is part of the Redsys package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ namespace Redsys\Tests\Api; use Redsys\Api\Titular; class TitularTest extends \PHPUnit_Framework_TestCase { public function testGetValueShouldReturnValue() { $titular = new Titular("Lorem ipsum"); $this->assertEquals("Lorem ipsum", $titular->getValue()); } public function testToStringShouldReturnString() { $titular = new Titular("Lorem ipsum"); $this->assertEquals("Lorem ipsum", (string)$titular); } /** * @expectedException \LengthException */ public function testTooLongValueShouldThrowException() { new Titular(str_repeat("abcdefghij", 6) . "z"); } }
rmhdev/redsys
tests/Redsys/Tests/Api/TitularTest.php
PHP
mit
866
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("KnowledgeCenter.Domain")] [assembly: AssemblyDescription("")] [assembly: Guid("34163851-767a-42f4-9f09-7d1c6af2bd11")]
Socres/KnowledgeCenter
src/Domain/KnowledgeCenter.Domain/Properties/AssemblyInfo.cs
C#
mit
212
repo_the_first ==============
alanmcgovern/repo_the_first
README.md
Markdown
mit
30
--- layout: page title: Copeland King Trade Executive Retreat date: 2016-05-24 author: Dennis David tags: weekly links, java status: published summary: Vivamus facilisis sem a turpis volutpat. banner: images/banner/leisure-05.jpg booking: startDate: 08/16/2017 endDate: 08/20/2017 ctyhocn: SFOCCHX groupCode: CKTER published: true --- Vivamus lacus orci, malesuada vel accumsan a, ornare non neque. Vestibulum imperdiet erat eu dictum venenatis. Pellentesque leo arcu, ornare a varius at, lacinia vel magna. Quisque scelerisque feugiat nisl id tempus. Mauris iaculis eros nulla, eget feugiat justo posuere eget. Etiam tincidunt diam nibh, porttitor consectetur orci ornare sit amet. Nullam sollicitudin velit ipsum, vel porta metus fringilla nec. Proin eu suscipit lectus. Suspendisse fermentum a lectus ac cursus. Sed finibus tincidunt risus, sit amet ullamcorper ante porta sit amet. In vestibulum iaculis nulla, a pharetra elit molestie in. Nunc mollis velit ac dolor venenatis volutpat. Nunc dictum vestibulum ex quis efficitur. Aenean nisl dolor, tempor nec tortor vel, interdum ullamcorper felis. Phasellus sit amet venenatis arcu. Curabitur suscipit luctus tellus, nec consectetur massa consectetur ut. Nunc consectetur, ex at finibus ultrices, ipsum lorem elementum mauris, non posuere mauris risus ac tortor. Nam egestas lacus eu euismod vestibulum. Sed eget sodales augue. Aliquam consectetur condimentum odio non euismod. Nam fermentum, sapien sit amet fringilla malesuada, nisl neque finibus lorem, at efficitur tortor purus quis velit. Mauris aliquet dignissim libero in ornare. Etiam auctor nulla nec ipsum porttitor, sed pulvinar quam elementum. Pellentesque egestas pellentesque velit, nec consectetur quam. Nullam blandit interdum nisi. Fusce ullamcorper non tortor vitae sollicitudin. Morbi ullamcorper aliquam nulla at sagittis. * Sed at nisi sit amet est consequat vulputate * Quisque varius mauris scelerisque pretium porttitor * Nulla tempor tellus et sapien tincidunt pellentesque eu in orci * Integer tempor urna aliquam, fermentum sem vel, facilisis ante * Nulla eget ante nec justo luctus pharetra et vitae metus * Nulla sed neque in orci feugiat ultrices quis a lacus. Duis quis magna nunc. Aliquam quis tincidunt nunc. Nunc eleifend, nibh eget mollis tincidunt, lacus lorem commodo nulla, nec vulputate libero ante vel lectus. Suspendisse eu elit odio. Aenean feugiat sapien et diam tempor finibus vitae eu justo. Nam faucibus libero eu volutpat tincidunt. Sed eu elit leo. Praesent tempor arcu erat, a porta massa porta sed. Proin dolor erat, varius in enim a, euismod vulputate enim. Cras mattis mi id ex dictum fermentum. Proin ut eleifend orci. Curabitur quis eros eu tellus dapibus varius eu ut risus. Phasellus non mollis lectus.
KlishGroup/prose-pogs
pogs/S/SFOCCHX/CKTER/index.md
Markdown
mit
2,774
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; 9773579b-2139-46de-a809-2f30cf25a4c8 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#Hazzik.Owin.Security.TradeMe">Hazzik.Owin.Security.TradeMe</a></strong></td> <td class="text-center">98.92 %</td> <td class="text-center">92.99 %</td> <td class="text-center">100.00 %</td> <td class="text-center">92.99 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="Hazzik.Owin.Security.TradeMe"><h3>Hazzik.Owin.Security.TradeMe</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Net.Http.WebRequestHandler</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_ServerCertificateValidationCallback(System.Net.Security.RemoteCertificateValidationCallback)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Net.Security.RemoteCertificateValidationCallback</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Not supported for HTTP - use new Handler and ignorable server certificate errors instead</td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Object,System.IntPtr)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Not supported for HTTP - use new Handler and ignorable server certificate errors instead</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Net.Security.SslPolicyErrors</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Not supported for HTTP - use new Handler and ignorable server certificate errors instead</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Claims.Claim</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.String,System.String,System.String,System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Claims.ClaimsIdentity</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Collections.Generic.IEnumerable{System.Security.Claims.Claim},System.String,System.String,System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.String,System.String,System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">AddClaim(System.Security.Claims.Claim)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_AuthenticationType</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_Claims</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_NameClaimType</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_RoleClaimType</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Cryptography.HashAlgorithm</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">ComputeHash(System.Byte[])</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Cryptography.HMACSHA1</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Currently there is no workaround, but we are working on it. Please check back.</td> </tr> <tr> <td style="padding-left:2em">#ctor</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Currently there is no workaround, but we are working on it. Please check back.</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Cryptography.KeyedHashAlgorithm</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_Key(System.Byte[])</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Cryptography.X509Certificates.X509Certificate</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Security.Cryptography.X509Certificates.X509Chain</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Text.Encoding</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_ASCII</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Type</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>.GetTypeInfo().Assembly</td> </tr> <tr> <td style="padding-left:2em">get_Assembly</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>.GetTypeInfo().Assembly</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
kuhlenh/port-to-core
Reports/ha/hazzik.owin.security.trademe.1.0.0/Hazzik.Owin.Security.TradeMe-net45.html
HTML
mit
27,782
# Update for Chrome 71 Due to abuse of users with the Speech Synthesis API (ADS, Fake system warnings), Google decided to remove the usage of the API in the browser when it's not triggered by an user gesture (click, touch etc.). This means that calling for example <code>artyom.say("Hello")</code> if it's not wrapped inside an user event won't work. So on every page load, the user will need to click at least once time per page to allow the usage of the API in the website, otherwise the following exception will be raised: "[Deprecation] speechSynthesis.speak() without user activation is no longer allowed since M71, around December 2018. See https://www.chromestatus.com/feature/5687444770914304 for more details" For more information, visit the bug or [this entry in the forum](https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/WsnBm53M4Pc). To bypass this error, the user will need to interact manually with the website at least once, for example with a click: ```html <button id="btn">Allow Voice Synthesis</button> <script src="artyom.window.js"></script> <script> var Jarvis = new Artyom(); // Needed user interaction at least once in the website to make // it work automatically without user interaction later... thanks google .i. document.getElementById("btn").addEventListener("click", function(){ Jarvis.say("Hello World !"); }, false); </script> ``` <p align="center"> <img src="https://raw.githubusercontent.com/sdkcarlos/artyom.js/master/public/images/artyomjs-logo.png" width="256" title="Artyom logo"> </p> # Table of Contents - [About Artyom](#about-artyom) * [Speech Recognition](#speech-recognition) * [Voice Synthesis](#voice-synthesis) - [Installation](#installation) * [NPM](#npm) * [Bower](#bower) - [How to use](#how-to-use) - [Basic usage](#basic-usage) - [All you need to know about Artyom](#all-you-need-to-know-about-artyom) - [Development](#development) * [Building Artyom from source](#building-artyom-from-source) * [Testing](#testing) - [Languages](#languages) - [Demonstrations](#demonstrations) - [Thanks](#thanks) # About Artyom Artyom.js is a robust and useful wrapper of the webkitSpeechRecognition and speechSynthesis APIs. Besides, artyom allows you to add dynamic commands to your web app (website). Artyom is constantly updated with new gadgets and awesome features, so be sure to star and watch this repository to be aware of any update. The main features of Artyom are: ### Speech Recognition - Quick recognition of voice commands. - Add commands easily. - Smart commands (usage of wildcards and regular expressions). - Create a dictation object to convert voice to text easily. - Simulate commands without microphone. - Execution keyword to execute a command immediately after the use of the keyword. - Pause and resume command recognition. - Artyom has available the soundex algorithm to increase the accuracy of the recognition of commands (disabled by default). - Use a remote command processor service instead of local processing with Javascript. - Works both in desktop browser and mobile device. ### Voice Synthesis - Synthesize extreme huge blocks of text (+20K words according to the last test). - onStart and onEnd callbacks **will be always executed independently of the text length**. - Works both in desktop browser and mobile device. Read [the changelog to be informed about changes and additions in Artyom.js](http://docs.ourcodeworld.com/projects/artyom-js/documentation/getting-started/official-changelog) # Installation #### NPM ```batch npm install artyom.js ``` #### Bower ```batch bower install artyom.js ``` Or just download a .zip package with the source code, minified file and commands examples : [download .zip file](https://github.com/sdkcarlos/artyom.js/raw/master/public/artyom-source.zip) # How to use Artyom is totally written in TypeScript, but it's transpiled on every version to JavaScript. 2 files are built namely `artyom.js` (used with Bundlers like Webpack, Browserify etc.) and `artyom.window.js` (only for the web browser). As everyone seems to use a bundler nowadays, for the module loader used is CommonJS: ```javascript // Using the /build/artyom.js file import Artyom from './artyom.js'; const Jarvis = new Artyom(); Jarvis.say("Hello World !"); ``` Alternatively, if you are of the old school and just want to use it with a script tag, you will need to use the `artyom.window.js` file instead: ```html <script src="artyom.window.js"></script> <script> var Jarvis = new Artyom(); Jarvis.say("Hello World !"); </script> ``` The source code of artyom handles a single TypeScript file `/source/artyom.ts`. # Basic usage Writing code with artyom is very simple: ```javascript // With ES6,TypeScript etc import Artyom from './artyom.js'; // Create a variable that stores your instance const artyom = new Artyom(); // Or if you are using it in the browser // var artyom = new Artyom();// or `new window.Artyom()` // Add command (Short code artisan way) artyom.on(['Good morning','Good afternoon']).then((i) => { switch (i) { case 0: artyom.say("Good morning, how are you?"); break; case 1: artyom.say("Good afternoon, how are you?"); break; } }); // Smart command (Short code artisan way), set the second parameter of .on to true artyom.on(['Repeat after me *'] , true).then((i,wildcard) => { artyom.say("You've said : " + wildcard); }); // or add some commandsDemostrations in the normal way artyom.addCommands([ { indexes: ['Hello','Hi','is someone there'], action: (i) => { artyom.say("Hello, it's me"); } }, { indexes: ['Repeat after me *'], smart:true, action: (i,wildcard) => { artyom.say("You've said : "+ wildcard); } }, // The smart commands support regular expressions { indexes: [/Good Morning/i], smart:true, action: (i,wildcard) => { artyom.say("You've said : "+ wildcard); } }, { indexes: ['shut down yourself'], action: (i,wildcard) => { artyom.fatality().then(() => { console.log("Artyom succesfully stopped"); }); } }, ]); // Start the commands ! artyom.initialize({ lang: "en-GB", // GreatBritain english continuous: true, // Listen forever soundex: true,// Use the soundex algorithm to increase accuracy debug: true, // Show messages in the console executionKeyword: "and do it now", listen: true, // Start to listen commands ! // If providen, you can only trigger a command if you say its name // e.g to trigger Good Morning, you need to say "Jarvis Good Morning" name: "Jarvis" }).then(() => { console.log("Artyom has been succesfully initialized"); }).catch((err) => { console.error("Artyom couldn't be initialized: ", err); }); /** * To speech text */ artyom.say("Hello, this is a demo text. The next text will be spoken in Spanish",{ onStart: () => { console.log("Reading ..."); }, onEnd: () => { console.log("No more text to talk"); // Force the language of a single speechSynthesis artyom.say("Hola, esto está en Español", { lang:"es-ES" }); } }); ``` # All you need to know about Artyom - [Documentation and FAQ](http://docs.ourcodeworld.com/projects/artyom-js) Do not hesitate to create a ticket on the issues area of the Github repository for any question, problem or inconvenient that you may have about artyom. # Development ## Building Artyom from source On every update, we build the latest version that can be retrieved from `/build` (for the browser and module). However, if you are willing to create your own version of Artyom, you would just need to modify the source file `/source/artyom.ts` and generate the build files using the following commands. If you want to create the Browser version, you will need as first remove the `export default` keywords at the beginning of the class and run then the following command: ```bash npm run build-artyom-window ``` If you want to create the Module version with CommonJS (for webpack, browserify etc) just run: ```bash npm run build-artyom-module ``` ## Testing If you're interested in modifying or working with Artyom, or *you just simply want to test it quickly in your environment*, we recommend you to use the little Sandbox utility of Artyom. Using Webpack, the Artyom Sandbox creates an HTTPS server accessible at https://localhost:3000, here Artyom will be accesible in Continuous mode too. Start by cloning the repository of artyom: ```bash git clone https://github.com/sdkcarlos/artyom.js/ cd artyom.js ``` Switch to the sandbox directory: ```bash cd sandbox ``` Then install the dependencies: ```bash npm install ``` And start the Webpack dev server using: ```bash npm start ``` and finally access to the [https://localhost:3000](https://localhost:3000) address from your browser and you will see a little UI interface to interact with Artyom. This is only meant to work on Artyom, so it still in development. # Languages Artyom provides **complete** support for the following languages. Every language needs an initialization code that needs to be provided in the lang property at the initialization. | |Description |Code for initialization| ------------- | ------------- | ------------- | |<img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-usa.png" alt="Supported language"/>| English (USA)<br/>English (Great Britain) Great Britain| en-US<br/>en-GB | |<img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-spanish.png" alt="Supported language"/>| Español | es-ES | |<img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-german.png" alt="Supported language"/>| Deutsch (German) | de-DE | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-italy.png" alt="Supported language"/> | Italiano |it-IT | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-france.png" alt="Supported language"/> | Français |fr-FR | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-japan.png" alt="Supported language"/> | Japanese 日本人 | ja-JP | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-russia.png" alt="Supported language"/> | Russian | ru-RU | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-brasil.png" alt="Supported language"/> | Brazil | pt-PT | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-netherlands.png" alt="Supported language"/> | Dutch (netherlands)| nl-NL | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-poland.png" alt="Supported language"/> | Polski (polonia)| pl-PL | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-indonesia.png" alt="Supported language"/> | Indonesian (Indonesia)| id-ID | | <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-china.png" alt="Supported language"/> | Chinese (Cantonese[ 粤語(香港)] <br/> Mandarin[普通话(中国大陆)])| Cantonese<br/>zh-HK<br/> Mandarin<br />zh-CN| |<img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/flag-hindi.png" alt="Supported language" />| Hindi (India) | hi-IN | # Demonstrations - [Homepage](https://sdkcarlos.github.io/sites/artyom.html) - [Continuous mode J.A.R.V.I.S](https://sdkcarlos.github.io/jarvis.html) - [Sticky Notes](https://sdkcarlos.github.io/demo-sites/artyom/artyom_sticky_notes.html) # Thanks Working with artyom is cool and easy, read the documentation to discover more awesome features. Thanks for visiting the repository ! <p align="center"> <img src="https://raw.githubusercontent.com/sdkcarlos/sdkcarlos.github.io/master/sites/artyom-resources/images/artyom_make_sandwich.jpg" alt="Artyom example use" width="256"/> </p>
sdkcarlos/artyom.js
README.md
Markdown
mit
12,659
#include "src/math/float/log10f.c" #include "log.h" int main(void) { test(log10f, log10); }
jdh8/metallic
test/native/math/float/log10f.c
C
mit
97
<?php namespace XeroPHP\Reports; class AgedReceivablesByContact { /** * @var string[] */ private $headers; /** * @var mixed[] */ private $rows; /** * @param string[] $headers * @param mixed[] $rows */ public function __construct(array $headers, array $rows = []) { $this->headers = $headers; $this->rows = $rows; } /** * @return string[] */ public function getHeaders() { return $this->headers; } /** * @return mixed[] */ public function getRows() { return $this->rows; } }
cosmic-beacon/xero-php
src/XeroPHP/Reports/AgedReceivablesByContact.php
PHP
mit
630
# mrb\_manager [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/rrreeeyyy/mrb_manager?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) mruby binary manager having a affinity for mgem ## Installation Install it yourself as: $ gem install mrb_manager Afterwards you will still need to add ```eval "$(mrbm init)"``` to your profile. You'll only ever have to do this once. ## Usage ### Install mruby with current active mgems You should be able to: $ mgem add mruby-redis $ mrbm install If ```-t tag_name``` specified, you can install tagged mruby $ mgem add mryby-redis $ mgem add mruby-http2 $ mrbm install -t redis-and-http2 ### Uninstall mruby You should be able to: # list all available mruby $ mrbm list ID CREATED VERSION TAG cfb43c1811c5 1 month ago 1.1.0 $ mrbm uninstall cfb43c1811c5 If you tagged: $ mrbm list ID CREATED VERSION TAG cf3889727b2a 1 month ago 1.0.0 redis-and-http2 $ mrbm uninstall -t redis-and-http2 ## Contributing 1. Fork it ( https://github.com/rrreeeyyy/mrb_manager/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
rrreeeyyy/mrb_manager
README.md
Markdown
mit
1,328
var searchData= [ ['nalloc',['NALLOC',['../dwarfDbgInt_8h.html#a30e913ccf93d7ea095a144407af0f9a5',1,'dwarfDbgInt.h']]], ['name',['name',['../structattrValues.html#ac7cb0154aaced069f3b1d24a4b40bf26',1,'attrValues']]], ['nextcompileunitoffset',['nextCompileUnitOffset',['../structcompileUnit.html#a1f5c469b922f6fcfe3abe6b5dd983495',1,'compileUnit']]], ['numaddchild',['numAddChild',['../dwarfDbgGetDbgInfo_8c.html#a6620daa01bc49c37e1850f9101cd240b',1,'dwarfDbgGetDbgInfo.c']]], ['numaddsibling',['numAddSibling',['../dwarfDbgGetDbgInfo_8c.html#a5f08554c0dc92b8611b48e024e84c7d5',1,'dwarfDbgGetDbgInfo.c']]], ['numattr',['numAttr',['../structdieInfo.html#aa7815765cabb001eff45e8d908b733ff',1,'dieInfo']]], ['numattrstr',['numAttrStr',['../structdwarfDbgCompileUnitInfo.html#a3f9747b4bf3a3c420e2b9658f1e3face',1,'dwarfDbgCompileUnitInfo']]], ['numchildren',['numChildren',['../structdieAndChildrenInfo.html#a280ccfdcd796e9b7bd7fb365a02ac281',1,'dieAndChildrenInfo']]], ['numciefde',['numCieFde',['../structframeInfo.html#a9bc9dfa7dfbe5161b9454c22803336ec',1,'frameInfo']]], ['numcompileunit',['numCompileUnit',['../structdwarfDbgCompileUnitInfo.html#a24a90186d262c29e8f3aec7816eb0692',1,'dwarfDbgCompileUnitInfo']]], ['numdieandchildren',['numDieAndChildren',['../structcompileUnit.html#a2d3ebcbf3cef4a2a1b777411fa12ad1e',1,'compileUnit']]], ['numdies',['numDies',['../dwarfDbgGetDbgInfo_8c.html#acc7b29b6d4c897948ace423095d48374',1,'dwarfDbgGetDbgInfo.c']]], ['numdirname',['numDirName',['../structdirNamesInfo.html#a36bc650195a2492fdc4ce208ee2fc9b1',1,'dirNamesInfo']]], ['numdwarraytype',['numDwArrayType',['../structdwarfDbgTypeInfo.html#a4731409d5947b1ace3cb0e6d22c82085',1,'dwarfDbgTypeInfo']]], ['numdwbasetype',['numDwBaseType',['../structdwarfDbgTypeInfo.html#a99d053257682ec963ca7ba41febee943',1,'dwarfDbgTypeInfo']]], ['numdwconsttype',['numDwConstType',['../structdwarfDbgTypeInfo.html#a9073033a9af6498d353d3074fcd6e776',1,'dwarfDbgTypeInfo']]], ['numdwenumerationtype',['numDwEnumerationType',['../structdwarfDbgTypeInfo.html#a0c3c6e13970688bc030fcc0ab03be937',1,'dwarfDbgTypeInfo']]], ['numdwenumeratortype',['numDwEnumeratorType',['../structdwarfDbgTypeInfo.html#a131bebca9296b13ae01bee9091a47e87',1,'dwarfDbgTypeInfo']]], ['numdwmember',['numDwMember',['../structdwarfDbgTypeInfo.html#a0c32301131e1174173a6687c7643ee25',1,'dwarfDbgTypeInfo']]], ['numdwpointertype',['numDwPointerType',['../structdwarfDbgTypeInfo.html#a317ed6269cb72dd3b7027e75de016d41',1,'dwarfDbgTypeInfo']]], ['numdwstructuretype',['numDwStructureType',['../structdwarfDbgTypeInfo.html#a225af72daa609f73f608df45c7690a6b',1,'dwarfDbgTypeInfo']]], ['numdwsubroutinetype',['numDwSubroutineType',['../structdwarfDbgTypeInfo.html#a2ba56760d9d3697582e6fb77abbb38e3',1,'dwarfDbgTypeInfo']]], ['numdwtypedef',['numDwTypeDef',['../structdwarfDbgTypeInfo.html#a1b78f04c8216ec36e16296c78d35abdb',1,'dwarfDbgTypeInfo']]], ['numdwuniontype',['numDwUnionType',['../structdwarfDbgTypeInfo.html#a3c34aae02d2c0125e9e1eee64247f6c9',1,'dwarfDbgTypeInfo']]], ['numdwvolatiletype',['numDwVolatileType',['../structdwarfDbgTypeInfo.html#a4c92bb8ff7f43382caa3651465ea9d61',1,'dwarfDbgTypeInfo']]], ['numfde',['numFde',['../structcieFde.html#a080816ba7436820c85f5327f1b5f59aa',1,'cieFde::numFde()'],['../structframeInfo.html#a1dabaf73bfd8ec4e746dd8032396b3a5',1,'frameInfo::numFde()']]], ['numfileinfo',['numFileInfo',['../structcompileUnit.html#a6fb20bccb16ae86ef9b4f87dd0ed1327',1,'compileUnit']]], ['numfileline',['numFileLine',['../structfileInfo.html#a1931d7c00f70afbf960c6c4521bdcd84',1,'fileInfo']]], ['numformalparameterinfo',['numFormalParameterInfo',['../structsubProgramInfo.html#a2ccc0b535ec89eefbc9b1c8fc8fd61d0',1,'subProgramInfo']]], ['numframeregcol',['numFrameRegCol',['../structframeDataEntry.html#ad5a00c5ef02350b1e388ab26a774fa48',1,'frameDataEntry']]], ['numlocentry',['numLocEntry',['../structlocationInfo.html#a72a38f9b38b05c2278bfcb6cee811015',1,'locationInfo']]], ['numpathname',['numPathName',['../structpathNamesInfo.html#a57a942792bec3a1198db069eff6158e5',1,'pathNamesInfo']]], ['numrangeinfo',['numRangeInfo',['../structcompileUnit.html#aabfa5a93c0791354cf2357eee5e9c259',1,'compileUnit']]], ['numsiblings',['numSiblings',['../structdieAndChildrenInfo.html#a594643b40a2e2c26d4f99c990250b67b',1,'dieAndChildrenInfo::numSiblings()'],['../dwarfDbgGetDbgInfo_8c.html#ab34dbb2cc194c304000747b02081d960',1,'numSiblings():&#160;dwarfDbgGetDbgInfo.c']]], ['numsourcefile',['numSourceFile',['../structcompileUnit.html#a004d068e8e8ea12f5f5f04bea1860860',1,'compileUnit']]], ['numsubprograminfo',['numSubProgramInfo',['../structcompileUnit.html#a61551a73c12d2c6a7e2bd35037940a21',1,'compileUnit']]], ['numtypestr',['numTypeStr',['../structdwarfDbgTypeInfo.html#a954ab297265cb3b7e36f3ce5d74367c9',1,'dwarfDbgTypeInfo']]], ['numvariableinfo',['numVariableInfo',['../structsubProgramInfo.html#aee427adb0c32497900dd9eb0a00b1ac5',1,'subProgramInfo']]] ];
apwiede/nodemcu-firmware
docs/dwarfDbg/search/all_c.js
JavaScript
mit
5,000
<?php namespace Mastercel\ChartBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Solicitudespagos * * @ORM\Table(name="SolicitudesPagos", indexes={@ORM\Index(name="Indice_1", columns={"DteSolicitud", "TmeSolicitud"}), @ORM\Index(name="Indice_2", columns={"DteActualizacion"}), @ORM\Index(name="Indice_3", columns={"NumEstadoComunicacion"})}) * @ORM\Entity */ class Solicitudespagos { /** * @var integer * * @ORM\Column(name="NumSolicitud_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $numsolicitudId = '0'; /** * @var integer * * @ORM\Column(name="NumAlmacenSolicitud_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $numalmacensolicitudId = '0'; /** * @var \DateTime * * @ORM\Column(name="DteSolicitud", type="datetime", nullable=true) */ private $dtesolicitud; /** * @var \DateTime * * @ORM\Column(name="TmeSolicitud", type="datetime", nullable=true) */ private $tmesolicitud; /** * @var \DateTime * * @ORM\Column(name="DteVencimiento", type="datetime", nullable=true) */ private $dtevencimiento; /** * @var integer * * @ORM\Column(name="NumEmpresa_id", type="integer", nullable=true) */ private $numempresaId = '0'; /** * @var integer * * @ORM\Column(name="NumMoneda_id", type="integer", nullable=true) */ private $nummonedaId = '0'; /** * @var integer * * @ORM\Column(name="NumEjecutivo_id", type="integer", nullable=true) */ private $numejecutivoId = '0'; /** * @var integer * * @ORM\Column(name="NumProveedor_id", type="integer", nullable=true) */ private $numproveedorId = '0'; /** * @var integer * * @ORM\Column(name="NumCategoria_id", type="integer", nullable=true) */ private $numcategoriaId = '0'; /** * @var integer * * @ORM\Column(name="NumAutorizador_id", type="integer", nullable=true) */ private $numautorizadorId = '0'; /** * @var integer * * @ORM\Column(name="NumCreadoPor_id", type="integer", nullable=true) */ private $numcreadoporId = '0'; /** * @var \DateTime * * @ORM\Column(name="DteCreacion", type="datetime", nullable=true) */ private $dtecreacion; /** * @var integer * * @ORM\Column(name="NumActualizadoPor_id", type="integer", nullable=true) */ private $numactualizadoporId = '0'; /** * @var \DateTime * * @ORM\Column(name="DteActualizacion", type="datetime", nullable=true) */ private $dteactualizacion; /** * @var integer * * @ORM\Column(name="NumTipoEstado", type="integer", nullable=true) */ private $numtipoestado = '0'; /** * @var integer * * @ORM\Column(name="NumEstadoComunicacion", type="integer", nullable=true) */ private $numestadocomunicacion = '0'; /** * Set numsolicitudId * * @param integer $numsolicitudId * @return Solicitudespagos */ public function setNumsolicitudId($numsolicitudId) { $this->numsolicitudId = $numsolicitudId; return $this; } /** * Get numsolicitudId * * @return integer */ public function getNumsolicitudId() { return $this->numsolicitudId; } /** * Set numalmacensolicitudId * * @param integer $numalmacensolicitudId * @return Solicitudespagos */ public function setNumalmacensolicitudId($numalmacensolicitudId) { $this->numalmacensolicitudId = $numalmacensolicitudId; return $this; } /** * Get numalmacensolicitudId * * @return integer */ public function getNumalmacensolicitudId() { return $this->numalmacensolicitudId; } /** * Set dtesolicitud * * @param \DateTime $dtesolicitud * @return Solicitudespagos */ public function setDtesolicitud($dtesolicitud) { $this->dtesolicitud = $dtesolicitud; return $this; } /** * Get dtesolicitud * * @return \DateTime */ public function getDtesolicitud() { return $this->dtesolicitud; } /** * Set tmesolicitud * * @param \DateTime $tmesolicitud * @return Solicitudespagos */ public function setTmesolicitud($tmesolicitud) { $this->tmesolicitud = $tmesolicitud; return $this; } /** * Get tmesolicitud * * @return \DateTime */ public function getTmesolicitud() { return $this->tmesolicitud; } /** * Set dtevencimiento * * @param \DateTime $dtevencimiento * @return Solicitudespagos */ public function setDtevencimiento($dtevencimiento) { $this->dtevencimiento = $dtevencimiento; return $this; } /** * Get dtevencimiento * * @return \DateTime */ public function getDtevencimiento() { return $this->dtevencimiento; } /** * Set numempresaId * * @param integer $numempresaId * @return Solicitudespagos */ public function setNumempresaId($numempresaId) { $this->numempresaId = $numempresaId; return $this; } /** * Get numempresaId * * @return integer */ public function getNumempresaId() { return $this->numempresaId; } /** * Set nummonedaId * * @param integer $nummonedaId * @return Solicitudespagos */ public function setNummonedaId($nummonedaId) { $this->nummonedaId = $nummonedaId; return $this; } /** * Get nummonedaId * * @return integer */ public function getNummonedaId() { return $this->nummonedaId; } /** * Set numejecutivoId * * @param integer $numejecutivoId * @return Solicitudespagos */ public function setNumejecutivoId($numejecutivoId) { $this->numejecutivoId = $numejecutivoId; return $this; } /** * Get numejecutivoId * * @return integer */ public function getNumejecutivoId() { return $this->numejecutivoId; } /** * Set numproveedorId * * @param integer $numproveedorId * @return Solicitudespagos */ public function setNumproveedorId($numproveedorId) { $this->numproveedorId = $numproveedorId; return $this; } /** * Get numproveedorId * * @return integer */ public function getNumproveedorId() { return $this->numproveedorId; } /** * Set numcategoriaId * * @param integer $numcategoriaId * @return Solicitudespagos */ public function setNumcategoriaId($numcategoriaId) { $this->numcategoriaId = $numcategoriaId; return $this; } /** * Get numcategoriaId * * @return integer */ public function getNumcategoriaId() { return $this->numcategoriaId; } /** * Set numautorizadorId * * @param integer $numautorizadorId * @return Solicitudespagos */ public function setNumautorizadorId($numautorizadorId) { $this->numautorizadorId = $numautorizadorId; return $this; } /** * Get numautorizadorId * * @return integer */ public function getNumautorizadorId() { return $this->numautorizadorId; } /** * Set numcreadoporId * * @param integer $numcreadoporId * @return Solicitudespagos */ public function setNumcreadoporId($numcreadoporId) { $this->numcreadoporId = $numcreadoporId; return $this; } /** * Get numcreadoporId * * @return integer */ public function getNumcreadoporId() { return $this->numcreadoporId; } /** * Set dtecreacion * * @param \DateTime $dtecreacion * @return Solicitudespagos */ public function setDtecreacion($dtecreacion) { $this->dtecreacion = $dtecreacion; return $this; } /** * Get dtecreacion * * @return \DateTime */ public function getDtecreacion() { return $this->dtecreacion; } /** * Set numactualizadoporId * * @param integer $numactualizadoporId * @return Solicitudespagos */ public function setNumactualizadoporId($numactualizadoporId) { $this->numactualizadoporId = $numactualizadoporId; return $this; } /** * Get numactualizadoporId * * @return integer */ public function getNumactualizadoporId() { return $this->numactualizadoporId; } /** * Set dteactualizacion * * @param \DateTime $dteactualizacion * @return Solicitudespagos */ public function setDteactualizacion($dteactualizacion) { $this->dteactualizacion = $dteactualizacion; return $this; } /** * Get dteactualizacion * * @return \DateTime */ public function getDteactualizacion() { return $this->dteactualizacion; } /** * Set numtipoestado * * @param integer $numtipoestado * @return Solicitudespagos */ public function setNumtipoestado($numtipoestado) { $this->numtipoestado = $numtipoestado; return $this; } /** * Get numtipoestado * * @return integer */ public function getNumtipoestado() { return $this->numtipoestado; } /** * Set numestadocomunicacion * * @param integer $numestadocomunicacion * @return Solicitudespagos */ public function setNumestadocomunicacion($numestadocomunicacion) { $this->numestadocomunicacion = $numestadocomunicacion; return $this; } /** * Get numestadocomunicacion * * @return integer */ public function getNumestadocomunicacion() { return $this->numestadocomunicacion; } }
pablo28jg/ejemplosgraficas
src/Mastercel/ChartBundle/Entity/Solicitudespagos.php
PHP
mit
10,419
const moment = require('moment') const expect = require('chai').expect const sinon = require('sinon') const proxyquire = require('proxyquire') const breadcrumbHelper = require('../../helpers/breadcrumb-helper') const orgUnitConstant = require('../../../app/constants/organisation-unit.js') const activeStartDate = moment('25-12-2017', 'DD-MM-YYYY').toDate() // 2017-12-25T00:00:00.000Z const activeEndDate = moment('25-12-2018', 'DD-MM-YYYY').toDate() // 2018-12-25T00:00:00.000Z const breadcrumbs = breadcrumbHelper.TEAM_BREADCRUMBS const expectedReductionExport = [ { offenderManager: 'Test_Forename Test_Surname', reason: 'Disability', amount: 5, startDate: activeStartDate, endDate: activeEndDate, status: 'ACTIVE', additionalNotes: 'New Test Note' }] let getReductionsData let exportReductionService let getBreadcrumbsStub beforeEach(function () { getReductionsData = sinon.stub() getBreadcrumbsStub = sinon.stub().resolves(breadcrumbs) exportReductionService = proxyquire('../../../app/services/get-reductions-export', { './data/get-reduction-notes-export': getReductionsData, './get-breadcrumbs': getBreadcrumbsStub }) }) describe('services/get-reductions-export', function () { it('should return the expected reductions exports for team level', function () { getReductionsData.resolves(expectedReductionExport) return exportReductionService(1, orgUnitConstant.TEAM.name) .then(function (result) { expect(getReductionsData.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true) expect(getBreadcrumbsStub.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true) expect(result.reductionNotes[0].offenderManager).to.be.eql(expectedReductionExport[0].offenderManager) expect(result.reductionNotes[0].reason).to.be.eql(expectedReductionExport[0].reason) expect(result.reductionNotes[0].amount).to.be.eql(expectedReductionExport[0].amount) expect(result.reductionNotes[0].startDate).to.be.eql('25 12 2017, 00:00') expect(result.reductionNotes[0].endDate).to.be.eql('25 12 2018, 00:00') expect(result.reductionNotes[0].status).to.be.eql(expectedReductionExport[0].status) expect(result.reductionNotes[0].additionalNotes).to.be.eql(expectedReductionExport[0].additionalNotes) }) }) })
ministryofjustice/wmt-web
test/unit/services/test-get-reduction-export.js
JavaScript
mit
2,361
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ProjectData; using Tools; using ProjectBLL; using System.Data; using Approve.RuleCenter; using System.Text; using System.Collections; using Approve.RuleApp; public partial class JSDW_DesignDoc_Report : Page { ProjectDB db = new ProjectDB(); RCenter rc = new RCenter(); protected void Page_Load(object sender, EventArgs e) { pageTool tool = new pageTool(this.Page); tool.ExecuteScript("tab();"); if (Session["FIsApprove"] != null && Session["FIsApprove"].ToString() == "1") { this.RegisterStartupScript(Guid.NewGuid().ToString(), "<script>FIsApprove();</script>"); } if (!IsPostBack) { btnSave.Attributes["onclick"] = "return checkInfo();"; BindControl(); showInfo(); } } //绑定 private void BindControl() { //备案部门 string deptId = ComFunction.GetDefaultDept(); StringBuilder sb = new StringBuilder(); sb.Append("select case FLevel when 1 then FFullName when 2 then FName when 3 then FName end FName,"); sb.Append("FNumber from cf_Sys_ManageDept "); sb.Append("where fnumber like '" + deptId + "%' "); sb.Append("and fname<>'市辖区' "); sb.Append("order by left(FNumber,4),flevel"); DataTable dt = rc.GetTable(sb.ToString()); p_FManageDeptId.DataSource = dt; p_FManageDeptId.DataSource = dt; p_FManageDeptId.DataTextField = "FName"; p_FManageDeptId.DataValueField = "FNumber"; p_FManageDeptId.DataBind(); } //显示 private void showInfo() { string FAppId = EConvert.ToString(Session["FAppId"]); var app = (from t in db.CF_App_List where t.FId == FAppId select new { t.FName, t.FYear, t.FLinkId, t.FBaseName, t.FPrjId, t.FState, }).FirstOrDefault(); pageTool tool = new pageTool(this.Page, "p_"); if (app != null) { t_FName.Text = app.FName; //已提交不能修改 if (app.FState == 1 || app.FState == 6) { tool.ExecuteScript("btnEnable();"); } //显示工程信息 CF_Prj_BaseInfo prj = db.CF_Prj_BaseInfo.Where(t => t.FId == app.FPrjId).FirstOrDefault(); if (prj != null) { tool.fillPageControl(prj); } } } /// <summary> /// 验证附件是否上传 /// </summary> /// <returns></returns> bool IsUploadFile(int? FMTypeId, string FAppId) { CF_Prj_BaseInfo prj = (from p in db.CF_Prj_BaseInfo join a in db.CF_App_List on p.FId equals a.FPrjId where a.FId == FAppId select p).FirstOrDefault(); var v =false ; if (prj != null) { v = db.CF_Sys_PrjList.Count(t => t.FIsMust == 1 && t.FManageType == FMTypeId && t.FIsPrjType.Contains(prj.FType.ToString()) && db.CF_AppPrj_FileOther.Count(o => o.FPrjFileId == t.FId && o.FAppId == FAppId) < 1) > 0; } return v; } public void Report() { RCenter rc = new RCenter(); pageTool tool = new pageTool(this.Page); string fDeptNumber = ComFunction.GetDefaultDept(); if (fDeptNumber == null || fDeptNumber == "") { tool.showMessage("系统出错,请配置默认管理部门"); return; } string FAppId = EConvert.ToString(Session["FAppId"]); var app = (from t in db.CF_App_List where t.FId == FAppId select t).FirstOrDefault(); SortedList[] sl = new SortedList[1]; if (app != null) { //验证必需的附件是否上传 if (IsUploadFile(app.FManageTypeId, FAppId)) { tool.showMessage("“上传行政批文、上传设计文件”菜单中存在未上传的附件(必需上传的),请先上传!"); return; } CF_Prj_BaseInfo prj = db.CF_Prj_BaseInfo.Where(t => t.FId == app.FPrjId).FirstOrDefault(); if (prj != null) { sl[0] = new SortedList(); sl[0].Add("FID", app.FId); sl[0].Add("FAppId", app.FId); sl[0].Add("FBaseInfoId", app.FBaseinfoId); sl[0].Add("FManageTypeId", app.FManageTypeId); sl[0].Add("FListId", "19301"); sl[0].Add("FTypeId", "1930100"); sl[0].Add("FLevelId", "1930100"); sl[0].Add("FIsPrime", 0); //sl.Add("FAppDeptId", row["FAppDeptId"].ToString()); //sl.Add("FAppDeptName", row["FAppDeptName"].ToString()); sl[0].Add("FAppTime", DateTime.Now); sl[0].Add("FIsNew", 0); sl[0].Add("FIsBase", 0); sl[0].Add("FIsTemp", 0); sl[0].Add("FUpDept", p_FManageDeptId.SelectedValue); sl[0].Add("FEmpId", prj.FId); sl[0].Add("FEmpName", prj.FPrjName); //存设计单位 var s = (from t in db.CF_Prj_Ent join a in db.CF_App_List on t.FAppId equals a.FId where a.FPrjId == app.FPrjId && a.FManageTypeId == 291 && t.FEntType == 155 && a.FState == 6 select new { t.FId, t.FBaseInfoId, t.FName, t.FLevelName, t.FCertiNo, t.FMoney, t.FPlanDate, t.FAppId }).FirstOrDefault(); if (s != null) { sl[0].Add("FLeadId", s.FBaseInfoId); sl[0].Add("FLeadName", s.FName); } StringBuilder sb = new StringBuilder(); sb.Append("update CF_App_List set FUpDeptId=" + p_FManageDeptId.SelectedValue + ","); sb.Append("ftime=getdate() where fid = '" + FAppId + "'"); rc.PExcute(sb.ToString()); string fsystemid = CurrentEntUser.SystemId; RApp ra = new RApp(); if (ra.EntStartProcessKCSJ(app.FBaseinfoId, FAppId, app.FYear.ToString(), DateTime.Now.Month.ToString(), fsystemid, fDeptNumber, p_FManageDeptId.SelectedValue, sl)) { sb.Remove(0, sb.Length); this.Session["FIsApprove"] = 1; tool.showMessageAndRunFunction("上报成功!", "location.href=location.href"); } } } } //保存按钮 protected void btnSave_Click(object sender, EventArgs e) { Report(); } }
coojee2012/pm3
SurveyDesign/JSDW/DesignDoc/Report.aspx.cs
C#
mit
7,357
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpEnumsShouldHaveZeroValueFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicEnumsShouldHaveZeroValueFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class EnumsShouldHaveZeroValueFixerTests { [Fact] public async Task CSharp_EnumsShouldZeroValueFlagsRenameAsync() { var code = @" public class Outer { [System.Flags] public enum E { A = 0, B = 3 } } [System.Flags] public enum E2 { A2 = 0, B2 = 1 } [System.Flags] public enum E3 { A3 = (ushort)0, B3 = (ushort)1 } [System.Flags] public enum E4 { A4 = 0, B4 = (int)2 // Sample comment } [System.Flags] public enum NoZeroValuedField { A5 = 1, B5 = 2 }"; var expectedFixedCode = @" public class Outer { [System.Flags] public enum E { None = 0, B = 3 } } [System.Flags] public enum E2 { None = 0, B2 = 1 } [System.Flags] public enum E3 { None = (ushort)0, B3 = (ushort)1 } [System.Flags] public enum E4 { None = 0, B4 = (int)2 // Sample comment } [System.Flags] public enum NoZeroValuedField { A5 = 1, B5 = 2 }"; await VerifyCS.VerifyCodeFixAsync( code, new[] { VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(7, 9, 7, 10).WithArguments("E", "A"), VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(15, 5, 15, 7).WithArguments("E2", "A2"), VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(22, 5, 22, 7).WithArguments("E3", "A3"), VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(29, 5, 29, 7).WithArguments("E4", "A4"), }, expectedFixedCode); } [Fact] public async Task CSharp_EnumsShouldZeroValueFlagsMultipleZeroAsync() { var code = @"// Some comment public class Outer { [System.Flags] public enum E { None = 0, A = 0 } } // Some comment [System.Flags] public enum E2 { None = 0, A = None }"; var expectedFixedCode = @"// Some comment public class Outer { [System.Flags] public enum E { None = 0 } } // Some comment [System.Flags] public enum E2 { None = 0 }"; await VerifyCS.VerifyCodeFixAsync( code, new[] { VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(5, 17, 5, 18).WithArguments("E"), VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(13, 13, 13, 15).WithArguments("E2"), }, expectedFixedCode); } [Fact] public async Task CSharp_EnumsShouldZeroValueNotFlagsNoZeroValueAsync() { var code = @" public class Outer { public enum E { A = 1 } public enum E2 { None = 1, A = 2 } } public enum E3 { None = 0, A = 1 } public enum E4 { None = 0, A = 0 } "; var expectedFixedCode = @" public class Outer { public enum E { None, A = 1 } public enum E2 { None, A = 2 } } public enum E3 { None = 0, A = 1 } public enum E4 { None = 0, A = 0 } "; await VerifyCS.VerifyCodeFixAsync( code, new[] { VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(4, 17, 4, 18).WithArguments("E"), VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(9, 17, 9, 19).WithArguments("E2"), }, expectedFixedCode); } [Fact] public async Task VisualBasic_EnumsShouldZeroValueFlagsRenameAsync() { var code = @" Public Class Outer <System.Flags> Public Enum E A = 0 B = 1 End Enum End Class <System.Flags> Public Enum E2 A2 = 0 B2 = 1 End Enum <System.Flags> Public Enum E3 A3 = CUShort(0) B3 = CUShort(1) End Enum <System.Flags> Public Enum NoZeroValuedField A5 = 1 B5 = 2 End Enum "; var expectedFixedCode = @" Public Class Outer <System.Flags> Public Enum E None = 0 B = 1 End Enum End Class <System.Flags> Public Enum E2 None = 0 B2 = 1 End Enum <System.Flags> Public Enum E3 None = CUShort(0) B3 = CUShort(1) End Enum <System.Flags> Public Enum NoZeroValuedField A5 = 1 B5 = 2 End Enum "; await VerifyVB.VerifyCodeFixAsync( code, new[] { VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"), }, expectedFixedCode); } [WorkItem(836193, "DevDiv")] [Fact] public async Task VisualBasic_EnumsShouldZeroValueFlagsRename_AttributeListHasTriviaAsync() { var code = @" Public Class Outer <System.Flags> _ Public Enum E A = 0 B = 1 End Enum End Class <System.Flags> _ Public Enum E2 A2 = 0 B2 = 1 End Enum <System.Flags> _ Public Enum E3 A3 = CUShort(0) B3 = CUShort(1) End Enum <System.Flags> _ Public Enum NoZeroValuedField A5 = 1 B5 = 2 End Enum "; var expectedFixedCode = @" Public Class Outer <System.Flags> _ Public Enum E None = 0 B = 1 End Enum End Class <System.Flags> _ Public Enum E2 None = 0 B2 = 1 End Enum <System.Flags> _ Public Enum E3 None = CUShort(0) B3 = CUShort(1) End Enum <System.Flags> _ Public Enum NoZeroValuedField A5 = 1 B5 = 2 End Enum "; await VerifyVB.VerifyCodeFixAsync( code, new[] { VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"), }, expectedFixedCode); } [Fact] public async Task VisualBasic_EnumsShouldZeroValueFlagsMultipleZeroAsync() { var code = @" Public Class Outer <System.Flags> Public Enum E None = 0 A = 0 End Enum End Class <System.Flags> Public Enum E2 None = 0 A = None End Enum <System.Flags> Public Enum E3 A3 = 0 B3 = CUInt(0) ' Not a constant End Enum"; var expectedFixedCode = @" Public Class Outer <System.Flags> Public Enum E None = 0 End Enum End Class <System.Flags> Public Enum E2 None = 0 End Enum <System.Flags> Public Enum E3 None End Enum"; await VerifyVB.VerifyCodeFixAsync( code, new[] { VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(4, 17, 4, 18).WithArguments("E"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(11, 13, 11, 15).WithArguments("E2"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(17, 13, 17, 15).WithArguments("E3"), }, expectedFixedCode); } [Fact] public async Task VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValueAsync() { var code = @" Public Class C Public Enum E A = 1 End Enum Public Enum E2 None = 1 A = 2 End Enum End Class Public Enum E3 None = 0 A = 1 End Enum Public Enum E4 None = 0 A = 0 End Enum "; var expectedFixedCode = @" Public Class C Public Enum E None A = 1 End Enum Public Enum E2 None A = 2 End Enum End Class Public Enum E3 None = 0 A = 1 End Enum Public Enum E4 None = 0 A = 0 End Enum "; await VerifyVB.VerifyCodeFixAsync( code, new[] { VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(3, 17, 3, 18).WithArguments("E"), VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(7, 17, 7, 19).WithArguments("E2"), }, expectedFixedCode); } } }
dotnet/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.Fixer.cs
C#
mit
9,759
/** * Conversion: * All dynamic tweaked dom id or class names are prefixed with 't-'. */ /** * Config */ var PRIVATE_TOKEN = 'xYDh7cpVX8BS2unon1hp'; /** * Globals. */ var autocompleteOpts, projectOpts, currentProjectID, currentProjectPath; $(function () { initGlobals(); handleAll(); mapUrlHandler(location.pathname, [ { pattern: /^\/[^\/]+\/[^\/]+$/, handle: handleProjectDashboard }, { pattern: /^.+\/tree\/.+/, handle: handleTreeView }, { pattern: /^.+\/blob\/[^\/]+\/.+\.md$/, handle: handleMdBlobView } ]); }); $(document).ajaxSuccess(function (event, xhr, settings) { mapUrlHandler(settings.url, [ { pattern: /.+\?limit=20/, handle: handleDashboardActivities }, { pattern: /.+\/refs\/.+\/logs_tree\/.+/, handle: handleLogsTree }, { pattern: /.+notes\.js\?target_type=issue.+/, handle: handleIssueComments } ]); }); /** * Parse useful data from dom elements and assign them to globals for later use. */ function initGlobals () { autocompleteOpts = JSON.parse($('.search-autocomplete-json').attr('data-autocomplete-opts')); projectOpts = _.where(autocompleteOpts, function (opt) { if (opt.label.indexOf('project:') !== -1) { return true; } }); currentUser = $('.profile-pic').attr('href').slice(3); currentProjectID = $(document.body).attr('data-project-id'); currentProjectPath = '/'; if ($('h1.project_name span').length) { currentProjectPath += $('h1.project_name span').text() .replace(/\s/, '').replace(/\s/, '').replace(' ', '-').toLowerCase(); } else { currentProjectPath += currentUser + '/' + $('h1.project_name').text().replace(' ', '-').toLowerCase(); } currentBranch = $('.project-refs-select').val(); console.log(currentUser, currentProjectID, currentProjectPath, currentBranch); } /** * Document loaded url handlers. */ /** * Handle tweak tasks for all pages. */ function handleAll() { $('.home a').attr('href', $('.home a').attr('href') + '#'); addProjectSelect(); } /** * Handle tweak tasks for project dashboard page. */ function handleProjectDashboard() { // Nothing to do. } /** * Handle tweak tasks for files tree view. */ function handleTreeView() { genMdFileTOCAndAdjustHyperlink(); } /** * Handle tweak tasks for markdown file blob view. */ function handleMdBlobView() { var slideLink = $('<a class="btn btn-tiny" target="_blank">slide</a>') .attr('href', '/reveal/md.html?p=' + location.pathname.replace('blob', 'raw')); $('.file-title .options .btn-group a:nth-child(2)').after(slideLink); genMdFileTOCAndAdjustHyperlink(); } /** * Add project select on the top bar. */ function addProjectSelect() { var projectSelectForm = $('<form class="navbar-form pull-left">' + '<select id="t-project-list"></select>' + '</form>'); $('.navbar .container .nav li:nth-child(2)').after(projectSelectForm); var options = projectOpts.map(function (project) { return $('<option />').val(project.url.toLowerCase()).text(project.label.slice(9)); }); if (!$('h1.project_name span').length) { options.unshift('<option>Go to Project</option>'); } $('#t-project-list').append(options) .val(currentProjectPath) .change(function () { location.href = $(this).val(); }); } /** * Generate TOC for markdown file. */ function genMdFileTOCAndAdjustHyperlink() { // Assume there is only one .file-holder. var fileHolder = $('.file-holder'); if (fileHolder.length !== 1) { return; } var fileTitle = fileHolder.find('.file-title'), fileContent = fileHolder.find('.file-content'); fileTitle.wrapInner('<div class="t-file-title-header" />') .scrollToFixed(); var fileTitleFooter = $('<div class="t-file-title-footer"><div class="t-file-title-toc navbar-inner" /></div>') .appendTo(fileTitle) .hide(); var fileTitleToc = fileTitleFooter.find('.t-file-title-toc') .tocify({ context: fileContent, selectors: 'h1,h2,h3,h4,h5,h6', showAndHide: false, hashGenerator: 'pretty', scrollTo: 38 }); // Some special characters will cause tocify hash error, replace them with empty string. fileHolder.find('[data-unique]').each(function () { $(this).attr('data-unique', $(this).attr('data-unique').replace(/\./g, '')); }); $('<span class="t-file-title-toc-toggler options">' + '<div class="btn-group tree-btn-group">' + '<a class="btn btn-tiny" title="Table of Content, \'m\' for shortcut.">TOC</a>' + '</div>' + '</span>') .click(function () { fileTitleFooter.toggle(); }) .appendTo(fileTitle.find('.t-file-title-header')); $(document).keyup(function(e) { switch (e.which) { case 27: fileTitleFooter.hide(); break; case 77: fileTitleFooter.toggle(); break; } }); // Jumpt to ahchor if has one. if (location.hash) { var anchor = location.hash.slice(1); fileTitleToc.find('li[data-unique="' + anchor + '"] a').click(); } // Adjust hyperlink. fileContent.find('a').each(function () { var href = $(this).attr('href'); // Sine 6-2-stable, gitlab will handle relative links when rendering markdown, // but it didn't work, all relative links fallback to wikis path, // I didn't have much time to figure out why, so I did this quick fix. var gitlabPrefixedWikisPath = currentProjectPath + '/wikis/'; var gitlabPrefixedWikisPathIndex = href.indexOf(gitlabPrefixedWikisPath); if (gitlabPrefixedWikisPathIndex != -1) { href = href.slice(gitlabPrefixedWikisPath.length); } // If not start with '/' and doesn't have '//', consider it as a relative path. if (/^[^\/]/.test(href) && !/.*\/\/.*/.test(href)) { var middlePath; // If end with .ext, this is a file path, otherwise is a directory path. if (/.*\.[^\/]+$/.test(href)) { middlePath = '/blob/'; } else { middlePath = '/tree/'; } $(this).attr('href', currentProjectPath + middlePath + currentBranch + '/' + href); } }); } /** * Ajax success url handlers. */ /** * Handle tweak tasks for dashboard activities. */ function handleDashboardActivities() { // Nothing to do. } /** * Handle tweak tasks for issue comments. */ function handleIssueComments() { $('.note-image-attach').each(function () { var img = $(this); var wrapper = $('<a class="t-fancybox-note-image-attach" rel="gallery-note-image-attach" />') .attr('href', img.attr('src')) .attr('title', img.attr('alt')); img.wrap(wrapper); wrapper.commonFancybox(); }); $('.t-fancybox-note-image-attach').commonFancybox(); } /** * Handle tweak tasks for git logs tree. */ function handleLogsTree() { // Nothing to do. } /** * Helpers. */ function mapUrlHandler(url, handlers) { handlers.forEach(function (handler) { if (handler.pattern.test(url)) { handler.handle(); } }); } function mySetInterval(fn, interval) { setTimeout(function () { fn(function () { mySetInterval(fn, interval); }); }, interval); } function myGitLabAPIGet(url, data, cb) { $.get('/api/v3/' + url + '?private_token=' + PRIVATE_TOKEN, data, function (data) { cb(data); }); } /** * Extensions */ if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } (function ($) { $.fn.extend({ commonFancybox: function () { $(this).fancybox({ closeBtn: false, helpers: { title: { type : 'inside' }, buttons: {} } }); } }); })(jQuery);
inetfuture/gitlab-tweak
public/tweak.js
JavaScript
mit
7,663
import axios from 'axios' import pipelineApi from './api' import { addMessage } from '../../../client/utils/flash-messages' import { transformValueForAPI } from '../../../client/utils/date' function transformValuesForApi(values, oldValues = {}) { const data = { name: values.name, status: values.category, } function addValue(key, value) { const existingValue = oldValues[key] const hasExistingValue = Array.isArray(existingValue) ? !!existingValue.length : !!existingValue if (hasExistingValue || (Array.isArray(value) ? value.length : value)) { data[key] = value || null } } addValue('likelihood_to_win', parseInt(values.likelihood, 10)) addValue('sector', values.sector?.value) addValue( 'contacts', values.contacts ? values.contacts.map(({ value }) => value) : [] ) addValue('potential_value', values.export_value) addValue('expected_win_date', transformValueForAPI(values.expected_win_date)) return data } export async function getPipelineByCompany({ companyId }) { const { data } = await pipelineApi.list({ company_id: companyId }) return { companyId, count: data.count, results: data.results, } } export async function addCompanyToPipeline({ values, companyId }) { const { data } = await pipelineApi.create({ company: companyId, ...transformValuesForApi(values), }) addMessage('success', `You added ${values.name} to your pipeline`) return data } export async function getPipelineItem({ pipelineItemId }) { const { data } = await pipelineApi.get(pipelineItemId) return data } export async function getCompanyContacts({ companyId, features }) { const contactEndpointVersion = features['address-area-contact-required-field'] ? 'v4' : 'v3' const { data } = await axios.get( `/api-proxy/${contactEndpointVersion}/contact`, { params: { company_id: companyId, limit: 500 }, } ) return data.results } export async function editPipelineItem({ values, pipelineItemId, currentPipelineItem, }) { const { data } = await pipelineApi.update( pipelineItemId, transformValuesForApi(values, currentPipelineItem) ) addMessage('success', `You saved changes to ${values.name}`) return data } export async function archivePipelineItem({ values, pipelineItemId, projectName, }) { const { data } = await pipelineApi.archive(pipelineItemId, { reason: values.reason, }) addMessage('success', `You archived ${projectName}`) return data } export async function unarchivePipelineItem({ projectName, pipelineItemId }) { const { data } = await pipelineApi.unarchive(pipelineItemId) addMessage('success', `You unarchived ${projectName}`) return data } export async function deletePipelineItem({ projectName, pipelineItemId }) { const { status } = await pipelineApi.delete(pipelineItemId) addMessage('success', `You deleted ${projectName} from your pipeline`) return status }
uktrade/data-hub-fe-beta2
src/apps/my-pipeline/client/tasks.js
JavaScript
mit
2,963
var global = require('../../global'); module.exports = function (data, offset) { var items = data.items.map(invoiceNote => { var invoiceItem = invoiceNote.items.map(dataItem => { var _items = dataItem.items.map(item => { dueDate = new Date(dataItem.deliveryOrderSupplierDoDate); dueDate.setDate(dueDate.getDate() + item.paymentDueDays); return { deliveryOrderNo: dataItem.deliveryOrderNo, date: dataItem.deliveryOrderDate, purchaseRequestRefNo: item.purchaseRequestRefNo, product: item.product.name, productDesc: item.product.description, quantity: item.deliveredQuantity, uom: item.purchaseOrderUom.unit, unit: item.unit, price: item.pricePerDealUnit, priceTotal: item.pricePerDealUnit * item.deliveredQuantity, correction: item.correction, dueDate: dueDate, paymentMethod: item.paymentMethod, currRate: item.kursRate, } }); _items = [].concat.apply([], _items); return _items; }) invoiceItem = [].concat.apply([], invoiceItem); return invoiceItem; }); items = [].concat.apply([], items); var dueDate, paymentMethod; var dueDates = items.map(item => { return item.dueDate }) dueDate = Math.max.apply(null, dueDates); paymentMethod = items[0].paymentMethod; var useIncomeTax = data.items .map((item) => item.useIncomeTax) .reduce((prev, curr, index) => { return prev && curr }, true); var useVat = data.items .map((item) => item.useVat) .reduce((prev, curr, index) => { return prev && curr }, true); var vatRate = 0; if (useVat) { vatRate = data.items[0].vat.rate; } var sumByUnit = []; items.reduce(function (res, value) { if (!res[value.unit]) { res[value.unit] = { priceTotal: 0, unit: value.unit }; sumByUnit.push(res[value.unit]) } res[value.unit].priceTotal += value.priceTotal return res; }, {}); var locale = global.config.locale; var moment = require('moment'); moment.locale(locale.name); var header = [ { stack: [ 'PT. DAN LIRIS', 'Head Office : ', 'Kelurahan Banaran, Kecamatan Grogol', 'Sukoharjo 57193 - INDONESIA', 'PO.BOX 166 Solo 57100', 'Telp. (0271) 740888, 714400', 'Fax. (0271) 735222, 740777' ], alignment: "left", style: ['size06', 'bold'] }, { alignment: "center", text: 'NOTA INTERN', style: ['size08', 'bold'] }, '\n' ]; var subHeader = [ { columns: [ { width: '50%', stack: [ { columns: [{ width: '25%', text: 'No. Nota Intern', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.no, style: ['size06'] }] }, { columns: [{ width: '25%', text: 'Kode Supplier', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.supplier.code, style: ['size06'] }] }, { columns: [{ width: '25%', text: 'Nama Supplier', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.supplier.name, style: ['size06'] }] } ] }, { width: '50%', stack: [ { columns: [{ width: '28%', text: 'Tgl. Nota Intern', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: `${moment(data.date).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06'] }] }, { columns: [{ width: '28%', text: 'Tgl. Jatuh Tempo', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: `${moment(dueDate).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06'] }] },{ columns: [{ width: '28%', text: 'Term Pembayaran', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: paymentMethod, style: ['size06'] }] }, ] } ] }, { text: '\n', style: ['size06'] } ]; var thead = [ { text: 'No. Surat Jalan', style: ['size06', 'bold', 'center'] }, { text: 'Tgl. Surat Jalan', style: ['size06', 'bold', 'center'] }, { text: 'Nomor referensi PR', style: ['size06', 'bold', 'center'] }, { text: 'Keterangan Barang', style: ['size06', 'bold', 'center'] }, { text: 'Jumlah', style: ['size06', 'bold', 'center'] }, { text: 'Satuan', style: ['size06', 'bold', 'center'] }, { text: 'Harga Satuan', style: ['size06', 'bold', 'center'] }, { text: 'Harga Total', style: ['size06', 'bold', 'center'] } ]; var tbody = items.map(function (item, index) { return [{ text: item.deliveryOrderNo, style: ['size06', 'left'] }, { text: `${moment(item.date).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06', 'left'] }, { text: item.purchaseRequestRefNo, style: ['size06', 'left'] }, { text: `${item.product};${item.productDesc}`, style: ['size06', 'left'] }, { text: item.quantity, style: ['size06', 'right'] }, { text: item.uom, style: ['size06', 'left'] }, { text: parseFloat(item.price).toLocaleString(locale, locale.currency), style: ['size06', 'right'] }, { text: parseFloat(item.priceTotal).toLocaleString(locale, locale.currency), style: ['size06', 'right'] }]; }); tbody = tbody.length > 0 ? tbody : [ [{ text: "tidak ada barang", style: ['size06', 'center'], colSpan: 8 }, "", "", "", "", "", "", ""] ]; var table = [{ table: { widths: ['12%', '12%', '10%', '25%', '7%', '7%', '12%', '15%'], headerRows: 1, body: [].concat([thead], tbody) } }]; var unitK1 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2A"); var unitK2 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2B"); var unitK3 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2C"); var unitK4 = sumByUnit.find((item) => item.unit.toUpperCase() == "C1A"); var unit2D = sumByUnit.find((item) => item.unit.toUpperCase() == "C1B"); var sum = sumByUnit.map(item => item.priceTotal) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var sumKoreksi = items.map(item => item.correction) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var sumByCurrency = items.map(item => item.priceTotal * item.currRate) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var incomeTaxTotal = useIncomeTax ? sumByCurrency * 0.1 : 0; var vatTotal = useVat ? sumByCurrency * vatRate / 100 : 0; var sumTotal = sumByCurrency - vatTotal + incomeTaxTotal + sumKoreksi; var subFooter = [ { text: '\n', style: ['size06'] }, { columns: [ { stack: [ { columns: [ { width: '25%', text: 'Total K1 (2A)' }, { width: '2%', text: ':' }, { width: '*', text: unitK1 ? parseFloat(unitK1.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K2 (2B)' }, { width: '2%', text: ':' }, { width: '*', text: unitK2 ? parseFloat(unitK2.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K3 (2C)' }, { width: '2%', text: ':' }, { width: '*', text: unitK3 ? parseFloat(unitK3.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K4 (1)' }, { width: '2%', text: ':' }, { width: '*', text: unitK4 ? parseFloat(unitK4.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total 2D' }, { width: '2%', text: ':' }, { width: '*', text: unit2D ? parseFloat(unit2D.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, ] }, { stack: [ { columns: [ { width: '45%', text: 'Total Harga Pokok (DPP)' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sum).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Mata Uang' }, { width: '2%', text: ':' }, { width: '*', text: data.currency.code } ] }, { columns: [ { width: '45%', text: 'Total Harga Pokok (Rp)' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sum * data.currency.rate).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota Koreksi' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sumKoreksi).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota PPN' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(incomeTaxTotal).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota PPH' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(vatTotal).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total yang harus dibayar' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sumTotal).toLocaleString(locale, locale.currency) } ] }, ] } ], style: ['size07'] }]; var footer = ['\n\n', { alignment: "center", table: { widths: ['33%', '33%', '33%'], body: [ [ { text: 'Administrasi', style: ['size06', 'bold', 'center'] }, { text: 'Staff Pembelian', style: ['size06', 'bold', 'center'] }, { text: 'Verifikasi', style: ['size06', 'bold', 'center'] } ], [ { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] }, { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] }, { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] } ] ] } }]; var dd = { pageSize: 'A5', pageOrientation: 'portrait', pageMargins: 20, content: [].concat(header, subHeader, table, subFooter, footer), styles: { size06: { fontSize: 6 }, size07: { fontSize: 7 }, size08: { fontSize: 8 }, size09: { fontSize: 9 }, size10: { fontSize: 10 }, bold: { bold: true }, center: { alignment: 'center' }, left: { alignment: 'left' }, right: { alignment: 'right' }, justify: { alignment: 'justify' } } }; return dd; };
indriHutabalian/dl-module
src/pdf/definitions/garment-intern-note.js
JavaScript
mit
21,593
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>coqffi: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / coqffi - 1.0.0~beta7</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> coqffi <small> 1.0.0~beta7 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-20 02:39:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-20 02:39:21 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.8.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-community/coqffi&quot; dev-repo: &quot;git+https://github.com/coq-community/coqffi.git&quot; bug-reports: &quot;https://github.com/coq-community/coqffi/issues&quot; license: &quot;MIT&quot; synopsis: &quot;Tool for generating Coq FFI bindings to OCaml libraries&quot; description: &quot;&quot;&quot; `coqffi` generates the necessary Coq boilerplate to use OCaml functions in a Coq development, and configures the Coq extraction mechanism accordingly.&quot;&quot;&quot; build: [ [&quot;./src-prepare.sh&quot;] [&quot;dune&quot; &quot;build&quot; &quot;-p&quot; name &quot;-j&quot; jobs] ] depends: [ &quot;ocaml&quot; {&gt;= &quot;4.08&quot; &amp; &lt; &quot;4.13~&quot; } &quot;dune&quot; {&gt;= &quot;2.5&quot;} &quot;coq&quot; {(&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.14~&quot;) | = &quot;dev&quot;} &quot;cmdliner&quot; {&gt;= &quot;1.0.4&quot;} &quot;sexplib&quot; {&gt;= &quot;0.14&quot;} ] tags: [ &quot;category:Miscellaneous/Coq Extensions&quot; &quot;keyword:foreign function interface&quot; &quot;keyword:extraction&quot; &quot;keyword:OCaml&quot; &quot;logpath:CoqFFI&quot; ] authors: [ &quot;Thomas Letan&quot; &quot;Li-yao Xia&quot; &quot;Yann Régis-Gianas&quot; &quot;Yannick Zakowski&quot; ] url { src: &quot;https://github.com/coq-community/coqffi/archive/1.0.0-beta7.tar.gz&quot; checksum: &quot;sha512=0f9d2893f59f8d09caec83f8476a2e7a511a7044516d639e4283b4187a86cf1563e60f1647cd12ae06e7e395bbc5dfedf5d798af3eb6baf81c0c2e482e14507b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-coqffi.1.0.0~beta7 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-coqffi -&gt; ocaml &gt;= 4.08 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coqffi.1.0.0~beta7</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.1/coqffi/1.0.0~beta7.html
HTML
mit
7,357
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>bignums: 3 m 34 s 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+2 / bignums - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> bignums <small> 8.7.0 <span class="label label-success">3 m 34 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-11-14 19:55:30 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-14 19:55:30 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.7.1+2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq/bignums&quot; dev-repo: &quot;git+https://github.com/coq/bignums.git&quot; bug-reports: &quot;https://github.com/coq/bignums/issues&quot; authors: [ &quot;Laurent Théry&quot; &quot;Benjamin Grégoire&quot; &quot;Arnaud Spiwack&quot; &quot;Evgeny Makarov&quot; &quot;Pierre Letouzey&quot; ] license: &quot;LGPL-2.1-only&quot; build: [ [make &quot;-j%{jobs}%&quot; {ocaml:version &gt;= &quot;4.06&quot;}] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword:integer numbers&quot; &quot;keyword:rational numbers&quot; &quot;keyword:arithmetic&quot; &quot;keyword:arbitrary-precision&quot; &quot;category:Miscellaneous/Coq Extensions&quot; &quot;category:Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;category:Mathematics/Arithmetic and Number Theory/Rational numbers&quot; &quot;date:2017-06-15&quot; &quot;logpath:Bignums&quot; ] synopsis: &quot;Bignums, the Coq library of arbitrary large numbers&quot; description: &quot;Provides BigN, BigZ, BigQ that used to be part of Coq standard library &lt; 8.7.&quot; url { src: &quot;https://github.com/coq/bignums/archive/V8.7.0.tar.gz&quot; checksum: &quot;md5=1d5f18f15675cfac64df59b3405e64d3&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-bignums.8.7.0 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-bignums.8.7.0 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>13 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-bignums.8.7.0 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 m 34 s</dd> </dl> <h2>Installation size</h2> <p>Total: 10 M</p> <ul> <li>1 M <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/BigN.vo</code></li> <li>777 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.vo</code></li> <li>712 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.vo</code></li> <li>641 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.vo</code></li> <li>610 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake.vo</code></li> <li>549 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.glob</code></li> <li>366 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.vo</code></li> <li>344 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.glob</code></li> <li>306 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/QMake.vo</code></li> <li>295 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.vo</code></li> <li>290 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.vo</code></li> <li>274 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.vo</code></li> <li>265 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.vo</code></li> <li>263 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake.glob</code></li> <li>211 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.vo</code></li> <li>209 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.vo</code></li> <li>200 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.glob</code></li> <li>197 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.glob</code></li> <li>197 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.glob</code></li> <li>189 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.vo</code></li> <li>181 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.glob</code></li> <li>177 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.vo</code></li> <li>151 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.glob</code></li> <li>145 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/QMake.glob</code></li> <li>138 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.vo</code></li> <li>116 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigNumPrelude.vo</code></li> <li>116 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.glob</code></li> <li>101 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.vo</code></li> <li>96 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.vo</code></li> <li>92 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.vo</code></li> <li>87 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.glob</code></li> <li>80 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.vo</code></li> <li>74 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.glob</code></li> <li>72 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.glob</code></li> <li>69 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.glob</code></li> <li>69 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmxs</code></li> <li>68 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigNumPrelude.glob</code></li> <li>62 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.glob</code></li> <li>61 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.glob</code></li> <li>60 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.vo</code></li> <li>56 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.v</code></li> <li>52 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake.v</code></li> <li>48 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.v</code></li> <li>37 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.glob</code></li> <li>35 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/QMake.v</code></li> <li>35 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.glob</code></li> <li>33 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.v</code></li> <li>31 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.glob</code></li> <li>28 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.v</code></li> <li>24 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.v</code></li> <li>20 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/BigN.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.v</code></li> <li>13 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigNumPrelude.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmi</code></li> <li>9 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmx</code></li> <li>7 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigN/BigN.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmxa</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-bignums.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1+2/bignums/8.7.0.html
HTML
mit
15,814
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>persistent-union-find: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / persistent-union-find - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> persistent-union-find <small> 8.10.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2021-04-06 21:49:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-04-06 21:49:33 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.1 Official release 4.11.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;http://www.lri.fr/~filliatr/puf/&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/PersistentUnionFind&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: program verification&quot; &quot;keyword: union-find&quot; &quot;keyword: data structures&quot; &quot;keyword: Tarjan&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; ] authors: [ &quot;Jean-Christophe Filliâtre&quot; ] bug-reports: &quot;https://github.com/coq-contribs/persistent-union-find/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/persistent-union-find.git&quot; synopsis: &quot;Persistent Union Find&quot; description: &quot;&quot;&quot; Correctness proof of the Ocaml implementation of a persistent union-find data structure. See http://www.lri.fr/~filliatr/puf/ for more details.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/persistent-union-find/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=9d860c3649cb724e3f5e513d1b1ff60b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-persistent-union-find.8.10.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-persistent-union-find -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-persistent-union-find.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.11.1-2.0.7/released/8.11.1/persistent-union-find/8.10.0.html
HTML
mit
6,977
// // StoreAppleReceiptParser.hpp // Pods // // Created by eps on 7/3/20. // #ifndef EE_X_STORE_APPLE_RECEIPT_PARSER_HPP #define EE_X_STORE_APPLE_RECEIPT_PARSER_HPP #include <string> #include "ee/store/StoreFwd.hpp" namespace ee { namespace store { class AppleReceiptParser { public: AppleReceiptParser(); std::shared_ptr<AppleReceipt> parse(const std::string& receiptData); private: IMessageBridge& bridge_; }; } // namespace store } // namespace ee #endif /* EE_X_STORE_APPLE_RECEIPT_PARSER_HPP */
Senspark/ee-x
src/cpp/ee/store/private/StoreAppleReceiptParser.hpp
C++
mit
522
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.network; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.network.models.DdosProtectionPlan; import com.azure.resourcemanager.test.utils.TestUtilities; import com.azure.core.management.Region; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DdosProtectionPlanTests extends NetworkManagementTest { @Test public void canCRUDDdosProtectionPlan() throws Exception { String ppName = generateRandomResourceName("ddosplan", 15); DdosProtectionPlan pPlan = networkManager .ddosProtectionPlans() .define(ppName) .withRegion(locationOrDefault(Region.US_SOUTH_CENTRAL)) .withNewResourceGroup(rgName) .withTag("tag1", "value1") .create(); Assertions.assertEquals("value1", pPlan.tags().get("tag1")); PagedIterable<DdosProtectionPlan> ppList = networkManager.ddosProtectionPlans().list(); Assertions.assertTrue(TestUtilities.getSize(ppList) > 0); ppList = networkManager.ddosProtectionPlans().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.getSize(ppList) > 0); networkManager.ddosProtectionPlans().deleteById(pPlan.id()); ppList = networkManager.ddosProtectionPlans().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.isEmpty(ppList)); } }
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java
Java
mit
1,570
"""Run tests for the kmeans portion of the kmeans module""" import kmeans.kmeans.kmeans as kmeans import numpy as np import random def test_1dim_distance(): """See if this contraption works in 1 dimension""" num1 = random.random() num2 = random.random() assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2) def test_ndim_distance(): """Test to see if changing val by 1 does what it ought to do convert to float to integer because floating arithmetic makes testing analytic functions a mess""" rand = random.random point1 = [rand(), rand(), rand(), rand(), rand(), rand()] point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1 assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1 def test_maxiters(): """ensure the iteration ceiling works""" # assert kmeans.should_iter([], [], iterations=29) == True assert kmeans.should_iter([], [], iterations=30) == False assert kmeans.should_iter([], [], iterations=31) == False def test_random_centroid_dimensions(): """ensure the correct number of dimensions""" dimensions = random.randrange(1, 100) k = random.randrange(1, 100) centroids = kmeans.random_centroids(k, dimensions) for centroid in centroids: assert len(centroid) == dimensions def test_iterated_centroid(): """ensure that the average across each dimension is returned""" new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\ [[100, 200, 300]], [(0, 0), (1, 0)]) np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\ rtol=1e-5)
moradology/kmeans
tests/testkmeans.py
Python
mit
1,642
const multiples = '(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)' const here = 'fraction-tagger' // plural-ordinals like 'hundredths' are already tagged as Fraction by compromise const tagFractions = function (doc) { // hundred doc.match(multiples).tag('#Multiple', here) // half a penny doc.match('[(half|quarter)] of? (a|an)', 0).tag('Fraction', 'millionth') // nearly half doc.match('#Adverb [half]', 0).tag('Fraction', 'nearly-half') // half the doc.match('[half] the', 0).tag('Fraction', 'half-the') // two-halves doc.match('#Value (halves|halfs|quarters)').tag('Fraction', 'two-halves') // ---ordinals as fractions--- // a fifth doc.match('a #Ordinal').tag('Fraction', 'a-quarter') // seven fifths doc.match('(#Fraction && /s$/)').lookBefore('#Cardinal+$').tag('Fraction') // one third of .. doc.match('[#Cardinal+ #Ordinal] of .', 0).tag('Fraction', 'ordinal-of') // 100th of doc.match('[(#NumericValue && #Ordinal)] of .', 0).tag('Fraction', 'num-ordinal-of') // a twenty fifth doc.match('(a|one) #Cardinal?+ #Ordinal').tag('Fraction', 'a-ordinal') // doc.match('(a|one) [#Ordinal]', 0).tag('Fraction', 'a-ordinal') // values.if('#Ordinal$').tag('Fraction', '4-fifths') // seven quarters // values.tag('Fraction', '4-quarters') // doc.match('(#Value && !#Ordinal)+ (#Ordinal|#Fraction)').tag('Fraction', '4-fifths') // 12 and seven fifths // doc.match('#Value+ and #Value+ (#Ordinal|half|quarter|#Fraction)').tag('Fraction', 'val-and-ord') // fixups // doc.match('#Cardinal+? (second|seconds)').unTag('Fraction', '3 seconds') // doc.match('#Ordinal (half|quarter)').unTag('Fraction', '2nd quarter') // doc.match('#Ordinal #Ordinal+').unTag('Fraction') // doc.match('[#Cardinal+? (second|seconds)] of (a|an)', 0).tag('Fraction', here) // doc.match(multiples).tag('#Multiple', here) // // '3 out of 5' doc.match('#Cardinal+ out? of every? #Cardinal').tag('Fraction', here) // // one and a half // doc.match('#Cardinal and a (#Fraction && #Value)').tag('Fraction', here) // fraction - 'a third of a slice' // TODO:fixme // m = doc.match(`[(#Cardinal|a) ${ordinals}] of (a|an|the)`, 0).tag('Fraction', 'ord-of') // tag 'thirds' as a ordinal // m.match('.$').tag('Ordinal', 'plural-ordinal') return doc } module.exports = tagFractions
nlp-compromise/nlp_compromise
plugins/numbers/src/tagger/fractions.js
JavaScript
mit
2,380
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { range: '-480', containers: 'fluid', lockViewport: true, grid: { collapse: true } } } }; $(document).ready(function () { $("#calculate").click(function () { var opOne = $("#opOneID").val(); var opTwo = $("#opTwoID").val(); var selected = $('#mathFunction :selected').val(); if (opOne.length != 0) { $("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page. } else if (opTwo.length != 0) { $("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page. } }); $("#clear").click(function () { $("#opOneID").val(''); $("#opTwoID").val(''); $("#resultID").val(''); }); $("#pnlRemove").click(function () { /* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the manchester United chrest with the image that ] was the front panel image] this only shows the panels being changed by using code*/ var imageName = 'img/v8liv.PNG'; var changepnl = $('#btmpnl'); var pnlID = $('#v8front'); $(pnlID).hide(); // hide the front panel $('#btmpnl').attr('src', imageName); // change the bottom image to v8rear.PNG }); $('#mathFunction :selected').val(); $('#mathFunction').change(function () { /* this fucntion calls the calucate funtion with the number to be converted with the conversion type which comes from the select tag, eg pk is pounds to kilo's this function fires when the select dropdown box changes */ var opOne = $("#opOneID").val(); var opTwo = $("#opTwoID").val(); var selected = $('#mathFunction :selected').val(); // console.log($('#conversion :selected').val()); //write it out to the console to verify what was $("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page. }).change(); }); function process(selected, opOne,opTwo) { switch (selected) { case "+": return Calc.AddNo(opOne,opTwo); break; case "-": return Calc.SubNo(opOne, opTwo); break; case "/": return Calc.DivideNo(opOne, opTwo); break; case "*": return Calc.MultplyNo(opOne, opTwo); break; default: return "Error ! "; // code to be executed if n is different from case 1 and 2 } }
akabob/ARIA_CA2_Code
js/sk1.js
JavaScript
mit
3,079
# phase-0-gps-1 GPS 1.1(pair with Tom Goldenberg)
karanaditya993/phase-0-gps-1
README.md
Markdown
mit
50
(function(app, undefined) { 'use strict'; if(!app) throw new Error('Application "app" namespace not found.'); //---------------------------------------------------------------------------- console.log( 'hello world' ); console.log( 'Application Running...' ); //---------------------------------------------------------------------------- // @begin: renders app.render.jquery(); app.render.vanilla(); // @end: renders //---------------------------------------------------------------------------- // @begin: to_jquery app.to_jquery.run(); // @end: to_jquery //---------------------------------------------------------------------------- // @begin: mustache app.menu.render(); app.menu.option.reset(); // @begin: mustache //---------------------------------------------------------------------------- })(window.app);
soudev/requirejs-steps
src/01/scripts/app.js
JavaScript
mit
867
{-# LANGUAGE CPP #-} module Database.Orville.PostgreSQL.Plan.Explanation ( Explanation , noExplanation , explainStep , explanationSteps ) where newtype Explanation = Explanation ([String] -> [String]) #if MIN_VERSION_base(4,11,0) instance Semigroup Explanation where (<>) = appendExplanation #endif instance Monoid Explanation where mempty = noExplanation mappend = appendExplanation appendExplanation :: Explanation -> Explanation -> Explanation appendExplanation (Explanation front) (Explanation back) = Explanation (front . back) noExplanation :: Explanation noExplanation = Explanation id explainStep :: String -> Explanation explainStep str = Explanation (str:) explanationSteps :: Explanation -> [String] explanationSteps (Explanation prependTo) = prependTo []
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/Plan/Explanation.hs
Haskell
mit
800
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KUI.Controls { public class FlatAccentButton : FlatButton { protected override void OnPaintBackground(PaintEventArgs pevent) { pevent.Graphics.FillRectangle( MouseOver ? Theme.ForeBrush : Theme.AccentBrush, ClientRectangle); } public override void DrawShadow(Graphics g) { if (HasShadow) { for (int i = 0; i < ShadowLevel; i++) { g.DrawRectangle( new Pen(Theme.AccentColor.Shade(Theme.ShadowSize, i)), ShadeRect(i)); } } } } }
TheKronks/KUI
KUI/Controls/FlatAccentButton.cs
C#
mit
848
// crm114_config.h -- Configuration for CRM114 library. // Copyright 2001-2010 William S. Yerazunis. // // This file is part of the CRM114 Library. // // The CRM114 Library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The CRM114 Library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the CRM114 Library. If not, see <http://www.gnu.org/licenses/>. // // Derived from engine version of crm114_config.h. /////////////////////////////////////////////////////////////////// // Some things here you can change with relative impunity. // Other things, not so much. Where there are limiting factors // noted, please obey them or you may break something important. // And, of course, realize that this is LGPLed software with // NO WARRANTY - make any changes and that goes double. /////////////////////////////////////////////////////////////////// #ifndef __CRM114_CONFIG_H__ #define __CRM114_CONFIG_H__ // Do you want all the classifiers? Or just the "production // ready ones"? Comment the next line out if you want everything. //#define PRODUCTION_CLASSIFIERS_ONLY // // // As used in the library: #define STATISTICS_FILE_IDENT_STRING_MAX 1024 #define CLASSNAME_LENGTH 31 #define DEFAULT_HOW_MANY_CLASSES 2 #define DEFAULT_CLASS_SIZE (1<<23) // 8 megabytes // Markov family config // do we use Sparse Binary Polynomial Hashing (sensitive to both // sequence and spacing of individual words), Token Grab Bag, or // Token Sequence Sensitive? Testing against the SpamAssassin // "hard" database shows that SBPH, TGB, and TGB2, are somewhat // more accurate than TSS, and about 50% more accurate than First // Order Only. However, that's for English, and other natural // languages may show a different statistical distribution. // // Choose ONE of the following: // SBPH, TGB2, TGB, TSS, or ARBITRARY_WINDOW_LEN: // // *** DANGER, WILL ROBINSON *** You MUST rebuild your .css files from // samples of text if you change this. // // // Sparse Binary Polynomial Hashing #define SBPH // // Token Grab Bag, noaliasing //#define TGB2 // // Token Grab Bag, aliasing //#define TGB // // Token Sequence Sensitive //#define TSS // // First Order Only (i.e. single words, like SpamBayes) // Note- if you use FOO, you must turn off weights!! //#define FOO // // Generalized format for the window length. // // DO NOT SET THIS TO MORE THAN 10 WITHOUT LENGTHENING hctable // the classifier modules !!!!!! "hctable" contains the pipeline // hashing coefficients and needs to be extended to 2 * WINDOW_LEN // // Generic window length code //#define ARBITRARY_WINDOW_LENGTH // #define MARKOVIAN_WINDOW_LEN 5 // #define OSB_BAYES_WINDOW_LEN 5 // // DO NOT set this to more than 5 without lengthening the // htup1 and htup2 tables in crm_unified_bayes.c // #define UNIFIED_BAYES_WINDOW_LEN 5 // // Unified tokenization pipeline length. // maximum window length _ever_. #define UNIFIED_WINDOW_MAX 32 // // maximum number of iterations or phases of a pipeline, // maximum number of rows in a matrix of coefficients #define UNIFIED_ITERS_MAX 64 // // Now, choose whether we want to use the "old" or the "new" local // probability calculation. The "old" one works slightly better // for SBPH and much better for TSS, the "new" one works slightly // better for TGB and TGB2, and _much_ better for FOO // // The current default (not necessarily optimal) // is Markovian SBPH, STATIC_LOCAL_PROBABILITIES, // LOCAL_PROB_DENOM = 16, and SUPER_MARKOV // //#define LOCAL_PROB_DENOM 2.0 #define LOCAL_PROB_DENOM 16.0 //#define LOCAL_PROB_DENOM 256.0 #define STATIC_LOCAL_PROBABILITIES //#define LENGTHBASED_LOCAL_PROBABILITIES // //#define ENTROPIC_WEIGHTS //#define MARKOV_WEIGHTS #define SUPER_MARKOV_WEIGHTS //#define BREYER_CHHABRA_SIEFKES_WEIGHTS //#define BREYER_CHHABRA_SIEFKES_BASE7_WEIGHTS //#define BCS_MWS_WEIGHTS //#define BCS_EXP_WEIGHTS // // // Do we take only the maximum probability feature? // //#define USE_PEAK // // // Should we use stochastic microgrooming, or weight-distance microgrooming- // Make sure ONE of these is turned on. //#define STOCHASTIC_AMNESIA #define WEIGHT_DISTANCE_AMNESIA #if (! defined (STOCHASTIC_AMNESIA) && ! defined (WEIGHT_DISTANCE_AMNESIA)) #error Neither STOCHASTIC_AMNESIA nor WEIGHT_DISTANCE_AMNESIA defined #elif (defined (STOCHASTIC_AMNESIA) && defined (WEIGHT_DISTANCE_AMNESIA)) #error Both STOCHASTIC_AMNESIA and WEIGHT_DISTANCE_AMNESIA defined #endif // // define the default max chain length in a .css file that triggers // autogrooming, the rescale factor when we rescale, and how often // we rescale, and what chance (mask and key) for any particular // slot to get rescaled when a rescale is triggered for that slot chain. //#define MARKOV_MICROGROOM_CHAIN_LENGTH 1024 #define MARKOV_MICROGROOM_CHAIN_LENGTH 256 //#define MARKOV_MICROGROOM_CHAIN_LENGTH 64 #define MARKOV_MICROGROOM_RESCALE_FACTOR .75 #define MARKOV_MICROGROOM_STOCHASTIC_MASK 0x0000000F #define MARKOV_MICROGROOM_STOCHASTIC_KEY 0x00000001 #define MARKOV_MICROGROOM_STOP_AFTER 32 // maximum number of buckets groom-zeroed // define the default number of buckets in a learning file hash table // (note that this should be a prime number, or at least one with a // lot of big factors) // // this value (2097153) is one more than 2 megs, for a .css of 24 megs //#define DEFAULT_SPARSE_SPECTRUM_FILE_LENGTH 2097153 // // this value (1048577) is one more than a meg, for a .css of 12 megs // for the Markovian, and half that for OSB classifiers #define DEFAULT_SPARSE_SPECTRUM_FILE_LENGTH 1048577 #define DEFAULT_MARKOVIAN_SPARSE_SPECTRUM_FILE_LENGTH 1048577 #define DEFAULT_OSB_BAYES_SPARSE_SPECTRUM_FILE_LENGTH 524287 // Mersenne prime // How big is a feature bucket? Is it a byte, a short, a long, // a float, whatever. :) //#define MARKOV_FEATUREBUCKET_VALUE_MAX 32767 #define MARKOV_FEATUREBUCKET_VALUE_MAX 1000000000 #define MARKOV_FEATUREBUCKET_HISTOGRAM_MAX 4096 // end Markov family config // define default internal debug level #define DEFAULT_INTERNAL_TRACE_LEVEL 0 // define default user debug level #define DEFAULT_USER_TRACE_LEVEL 0 //// // Winnow algorithm parameters here... // #define OSB_WINNOW_WINDOW_LEN 5 #define OSB_WINNOW_PROMOTION 1.23 #define OSB_WINNOW_DEMOTION 0.83 #define DEFAULT_WINNOW_SPARSE_SPECTRUM_FILE_LENGTH 1048577 // For the hyperspace matcher, we need to define a few things. //#define DEFAULT_HYPERSPACE_BUCKETCOUNT 1000000 #define DEFAULT_HYPERSPACE_BUCKETCOUNT 100 // Stuff for bit-entropic configuration // Define the size of our alphabet, and how many bits per alph. #define ENTROPY_ALPHABET_SIZE 2 #define ENTROPY_CHAR_SIZE 1 #define ENTROPY_CHAR_BITMASK 0x1 // What fraction of the nodes in a bit-entropic file should be // referenceable from the FIR prior arithmetical encoding // lookaside table? 0.01 is 1% == average of 100 steps to find // the best node. 0.2 is 20% or 5 steps to find the best node. #define BIT_ENTROPIC_FIR_LOOKASIDE_FRACTION 0.1 #define BIT_ENTROPIC_FIR_LOOKASIDE_STEP_LIMIT 128 #define BIT_ENTROPIC_FIR_PRIOR_BIT_WEIGHT 0.5 #define BIT_ENTROPIC_SHUFFLE_HEIGHT 1024 // was 256 #define BIT_ENTROPIC_SHUFFLE_WIDTH 1024 // was 256 #define BIT_ENTROPIC_PROBABILITY_NERF 0.0000000000000000001 //#define DEFAULT_BIT_ENTROPY_FILE_LENGTH 2000000 #define DEFAULT_BIT_ENTROPY_FILE_LENGTH 1000000 // Defines for the svm classifier // All defines you should want to use without getting into // the nitty details of the SVM are here. For nitty detail // defines, see crm114_matrix_util.h, crm114_svm_quad_prog.h, // crm114_matrix.h, and crm114_svm_lib_fncts.h #define MAX_SVM_FEATURES 100000 //per example #define SVM_INTERNAL_TRACE_LEVEL 3 //the debug level when crm114__internal_trace is //on #define SVM_ACCURACY 1e-3 //The accuracy to which to run the solver //This is the average margin violation NOT //accounted for by the slack variable. #define SV_TOLERANCE 0.01 //An example is a support vector if //theta*y*x <= 1 + SV_TOLERANCE. //The smaller SV_TOLERANCE, the fewer //examples will be tagged as support //vectors. This will make it faster to //learn new examples, but possibly less //accurate. #define SVM_ADD_CONSTANT 1 //Define this to be 1 if you want a //constant offset in the classification //ie h(x) = theta*x + b where b is //the offset. If you don't want //a constant offset (just h(x) = theta*x), //define this to be 0. #define SVM_HOLE_FRAC 0.25 //Size of the "hole" left at the end of //the file to allow for quick appends //without having to forcibly unmap the //file. This is as a fraction of the //size of the file without the hole. So //setting it to 1 doubles the file size. //If you don't want a hole left, set //this to 0. #define SVM_MAX_SOLVER_ITERATIONS 200 //absolute maximum number of loops the //solver is allowed #define SVM_CHECK 100 //every SVM_CHECK we look to see if //the accuracy is better than //SVM_CHECK_FACTOR*SVM_ACCURACY. //If it is, we exit the solver loop. #define SVM_CHECK_FACTOR 2 //every SVM_CHECK we look to see if //the accuracy is better than //SVM_CHECK_FACTOR*SVM_ACCURACY. //If it is, we exit the solver loop. //defines for SVM microgrooming #define SVM_GROOM_OLD 10000 //we groom only if there are this many //examples (or more) not being used in //solving #define SVM_GROOM_FRAC 0.9 //we keep this fraction of examples after //grooming //defines for svm_smart_mode #define SVM_BASE_EXAMPLES 1000 //the number of examples we need to see //before we train #define SVM_INCR_FRAC 0.1 //if more than this fraction of examples //are appended, we do a fromstart rather //than use the incremental method. // Defines for the PCA classifier // All defines you should want to use without getting into // the nitty details of the PCA are here. For nitty detail // defines, see crm114_matrix_util.h and crm114_pca_lib_fncts.h #define PCA_INTERNAL_TRACE_LEVEL 3 //the debug level when crm114__internal_trace is on #define PCA_ACCURACY 1e-8 //accuracy to which to run the solver #define MAX_PCA_ITERATIONS 1000 //maximum number of solver iterations #define PCA_CLASS_MAG 50 //the starting class magnitudes. if this //is too small, the solver will double it //and resolve. if it is too large, the //solver will be less accurate. #define PCA_REDO_FRAC 0.001 //if we get this fraction of training //examples wrong with class mag enabled, we //retrain with class mag doubled. #define PCA_MAX_REDOS 20 //The maximum number of redos allowed when //trying to find the correct class mag. #define PCA_HOLE_FRAC 0.25 //Size of the "hole" left at the end of //the file to allow for quick appends //without having to forcibly unmap the file. //This is as a fraction of the size of the //file without the hole. So setting it to //1 doubles the file size. If you don't //want a hole left, set this to 0. //defines for PCA microgrooming #define PCA_GROOM_OLD 10000 //we groom only if there are this many //examples (or more) present #define PCA_GROOM_FRAC 0.9 //we keep this fraction of examples after //grooming // DANGER DANGER DANGER DANGER DANGER // CHANGE THESE AT YOUR PERIL- YOUR .CSS FILES WILL NOT BE // FORWARD COMPATIBLE WITH ANYONE ELSES IF YOU CHANGE THESE. // how many classes per datablock can the library support? #define CRM114_MAX_CLASSES 128 // FSCM uses two blocks / class #define CRM114_MAX_BLOCKS (2 * CRM114_MAX_CLASSES) // Maximum length of a stored regex (ugly! But we need a max length // in the mapping. GROT GROT GROT ) #define MAX_REGEX 4096 // /// END OF DANGER DANGER DANGER DANGER ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////// // // Improved FSCM-specific parameters // ///////////////////////////////////////////// // this is 2^18 + 1 // This determines the tradeoff in memory vs. speed/accuracy. //define FSCM_DEFAULT_PREFIX_TABLE_CELLS 262145 // // This is 1 meg + 1 #define FSCM_DEFAULT_PREFIX_TABLE_CELLS 1048577 // How long are our prefixes? Original prefix was 3 but that's // rather suboptimal for best speed. 6 looks pretty good for speed and // accuracy. // prefix length 6 and thickness 10 (200 multiplier) yields 29 / 4147 // //#define FSCM_DEFAULT_CODE_PREFIX_LEN 3 #define FSCM_DEFAULT_CODE_PREFIX_LEN 6 // The chain cache is a speedup for the FSCM match // It's indexed modulo the chainstart, with associativity 1.0 #define FSCM_CHAIN_CACHE_SIZE FSCM_DEFAULT_PREFIX_TABLE_CELLS // How much space to start out initially for the forwarding index area #define FSCM_DEFAULT_FORWARD_CHAIN_CELLS 1048577 //////////////////////////////////////////// // // Neural Net parameters // //////////////////////////////////////////// #define NN_RETINA_SIZE 8192 #define NN_FIRST_LAYER_SIZE 8 #define NN_HIDDEN_LAYER_SIZE 8 // Neural Net training setups // // Note- convergence seems to work well at // alpha 0.2 init_noise 0.5 stoch_noise 0.1 gain_noise 0.00000001 // alpha 0.2 init_noise 0.2 stoch_noise 0.1 gain_noise 0.00000001 // alpha 0.2 init_noise 0.2 stoch_noise 0.05 gain_noise 0.00000001 // alpha 0.2 init_noise 0.2 stoch_noise 0.05 gain_noise 0.00000001 // alpha 0.2 init_noise 0.2 stoch_noise 0.05 gain_noise 2.0 // alpha 0.2 init_noise 0.2 stoch_noise 0.05 gain_noise 2.0 zerotr 0.9999 #define NN_DEFAULT_ALPHA 0.2 // Initialization noise magnitude #define NN_INITIALIZATION_NOISE_MAGNITUDE 0.2 // Stochastic noise magnitude #define NN_DEFAULT_STOCH_NOISE 0.05 // Gain noise magnitude #define NN_DEFAULT_GAIN_NOISE 2.0 // Zero-tracking factor - factor the weights move toward zero every epoch #define NN_ZERO_TRACKING 0.9999 // Threshold for back propagation #define NN_INTERNAL_TRAINING_THRESHOLD 0.1 // Just use 1 neuron excitation per token coming in. #define NN_N_PUMPS 1 // How many training cycles before we punt out #define NN_MAX_TRAINING_CYCLES 500 // When doing a "nuke and retry", allow this many training cycles. #define NN_MAX_TRAINING_CYCLES_FROMSTART 5000 // How often do we cause a punt (we punt every 0th epoch modulo this number) #define NN_FROMSTART_PUNTING 10000000 // After how many "not needed" cycles do we microgroom this doc away? #define NN_MICROGROOM_THRESHOLD 1000000 // use the sparse retina design? No, it's not good. #define NN_SPARSE_RETINA 0 // End of configurable parameters. #endif // !__CRM114_CONFIG_H__
alisaifee/pycrm114
include/crm114_config.h
C
mit
17,035
using MortgageCalc.Models; using System; using System.Collections.Generic; namespace MortgageCalc.Calculators { public class InterestOnlyScheduleBuilder { private RateCalc _calc = new RateCalc(6); // initialize with 6 decimal places private decimal _monthlyPayment; private decimal _principal; private decimal _rate; private int _term; public InterestOnlyScheduleBuilder(decimal principal, decimal rate, int term) { this._principal = principal; this._rate = rate; this._term = term; this._monthlyPayment = this._calc.Interest(principal, rate); } public Schedule Schedule() { return new Schedule { MonthlyPayment = Math.Round(this._monthlyPayment, 2), CostOfCredit = Math.Round(this._monthlyPayment * this._term, 2) }; } } }
shanegray/mortgage-calc
Calculators/InterestOnlyScheduleBuilder.cs
C#
mit
947
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"> <title>grapp-core-ajax tests</title> <script src="../lib/web-component-tester/browser.js"></script> </head> <body> <script> WCT.loadSuites([ 'basic.html', ]); </script> <script src="//localhost:35729/livereload.js"></script> </body> </html>
grappendorf/grapp-core-ajax
test/index.html
HTML
mit
437
import Ember from 'ember'; import CheckboxMixin from '../mixins/checkbox-mixin'; export default Ember.Component.extend(CheckboxMixin, { type: 'checkbox', checked: false, onChange: function() { this.set('checked', this.$('input').prop('checked')); this.sendAction("action", { checked: this.get('checked'), value: this.get('value') }); } });
CrshOverride/Semantic-UI-Ember
addon/components/ui-checkbox.js
JavaScript
mit
374
@ParametersAreNonnullByDefault package org.zalando.problem.spring.web.advice; import javax.annotation.ParametersAreNonnullByDefault;
zalando/problem-spring-web
problem-spring-web/src/main/java/org/zalando/problem/spring/web/advice/package-info.java
Java
mit
135
<?php use Stringizer\Stringizer; /** * Date Unit Tests */ class DateTest extends PHPUnit_Framework_TestCase { public function testValidDate() { date_default_timezone_set('America/Vancouver'); $s = new Stringizer("January 1st"); $this->assertEquals(true, $s->isDate()); $s = new Stringizer("2015-03-15"); $this->assertEquals(true, $s->isDate()); $s = new Stringizer("1 week ago"); $this->assertEquals(true, $s->isDate()); } public function testInValidDate() { date_default_timezone_set('America/Vancouver'); $s = new Stringizer("Bad Date Input"); $this->assertEquals(false, $s->isDate()); } }
jasonlam604/Stringizer
tests/DateTest.php
PHP
mit
705
""" Django settings for ross project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'jtn=n8&nq9jgir8_z1ck40^c1s22d%=)z5qsm*q(bku*_=^sg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ross.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ross.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
rossplt/ross-django-utils
ross/settings.py
Python
mit
3,090
//////////////////////////////////////////////////////////////////////////////// //worldgenerator.cs //Created on: 2015-8-21, 18:18 // //Project VoxelEngine //Copyright C bajsko 2015. All rights Reserved. //////////////////////////////////////////////////////////////////////////////// using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using VoxelEngine.Game.Blocks; using VoxelEngine.GameConsole; using VoxelEngine.Utility; namespace VoxelEngine.Game { public class WorldGenerator { private World mWorldRef; public WorldGenerator(World worldRef) { this.mWorldRef = worldRef; } public Chunk GenerateChunk(int xp, int yp, int zp) { Chunk chunk = null; chunk = new Chunk(new Vector3(xp, yp, zp)); Vector3 chunkPosBlock = new Vector3(xp, yp, zp) * Chunk.CHUNK_SIZE; int treeDensity = 2; float stoneBaseHeight = 0; float stoneBaseNoise = 0.05f; float stoneBaseNoiseHeight = 4; float stoneMountainHeight = 48; float stoneMountainFrequency = 0.008f; float stoneMinHeight = -12; float dirtBaseHeight = 1; float dirtNoise = 0.04f; float dirtNoiseHeight = 3; for (int x = (int)chunkPosBlock.X - 5; x < chunkPosBlock.X + Chunk.CHUNK_SIZE + 5; x++) { for(int z = (int)chunkPosBlock.Z - 5; z < chunkPosBlock.Z + Chunk.CHUNK_SIZE + 5; z++) { int stoneHeight = (int)Math.Floor(stoneBaseHeight); stoneHeight += (int)Math.Floor(GetNoiseValue(x, 0, z, stoneMountainFrequency, (int)(stoneMountainHeight))); if (stoneHeight < stoneMinHeight) stoneHeight = (int)Math.Floor((stoneMinHeight)); stoneHeight += (int)Math.Floor(GetNoiseValue(x, 0, z, stoneBaseNoise, (int)(stoneBaseNoiseHeight))); int dirtHeight = stoneHeight + (int)(dirtBaseHeight); dirtHeight += (int)Math.Floor(GetNoiseValue(x, 100, z, dirtNoise, (int)(dirtNoiseHeight))); for (int y = (int)chunkPosBlock.Y - 10; y < chunkPosBlock.Y+Chunk.CHUNK_SIZE + 10; y++) { //from world block space to local chunk space int xfactor = (int)chunkPosBlock.X; int yfactor = (int)chunkPosBlock.Y; int zfactor = (int)chunkPosBlock.Z; if (y <= stoneHeight) chunk.SetBlock(x-xfactor, y-yfactor, z-zfactor, new Block(BlockType.Stone)); else if (y <= dirtHeight) { chunk.SetBlock(x - xfactor, y - yfactor, z - zfactor, new Block(BlockType.Grass)); if (y == dirtHeight && GetNoiseValue(x, 0, z, 0.2f, 100) < treeDensity) { //CreateTree(x, y, z); } } } } } //chunk.ApplySunlight(); return chunk; } public Chunk GenerateChunk(Vector3 position) { return GenerateChunk((int)position.X, (int)position.Y, (int)position.Z); } private void CreateTree(int x, int y, int z) { //TODO: //major performance hit here... //fix.. Random random = new Random(); int trunkLength = random.Next(5, 10); for(int yy = y; yy < y + trunkLength; yy++) { mWorldRef.SetBlock(x, yy+1, z, new Block(BlockType.Log)); } int leavesStart = y+trunkLength; for(int xi = -3; xi <= 3; xi++) { for(int yi = 0; yi <= 1; yi++) { for(int zi = -3; zi <= 3; zi++) { mWorldRef.SetBlock(x + xi, leavesStart + yi, z + zi, new Block(BlockType.Leaves)); } } } for(int xi = -2; xi <= 2; xi++) { for(int zi = -2; zi <= 2; zi++) { mWorldRef.SetBlock(x + xi, leavesStart + 2, z + zi, new Block(BlockType.Leaves)); } } mWorldRef.SetBlock(x - 1, leavesStart + 3, z, new Block(BlockType.Leaves)); mWorldRef.SetBlock(x + 1, leavesStart + 3, z, new Block(BlockType.Leaves)); mWorldRef.SetBlock(x, leavesStart + 3, z - 1, new Block(BlockType.Leaves)); mWorldRef.SetBlock(x, leavesStart + 3, z + 1, new Block(BlockType.Leaves)); } private int GetNoiseValue(int x, int z, float scale, int max) { int value = (int)((Noise.Generate(x*scale, 0, z*scale)) * (max / 2f)); return value; } private float GetNoiseValue(int x, int y, int z, float scale, int max) { int value = (int)Math.Floor((Noise.Generate(x * scale, y * scale, z * scale) + 1f) * (max / 2f)); return value; } } }
bajsko/VoxelEngine
Game/WorldGenerator.cs
C#
mit
5,364
"use strict" var express = require('express'); var app = express(); var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); var router = express.Router(); router.get('/accidents', function(req, res) { var query = { index: 'wildmap', type: 'accidents', size: 10000, body: { query: { bool: { must: [ { match_all: {} } ] } } } } var animal_type = req.query.animal_type; var day_type = req.query.day_type; var season = req.query.season; if(animal_type && animal_type!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.animal_type": animal_type } }); } if(day_type && day_type!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.day_type": day_type } }); } if(season && season!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.season": season } }); } console.log(query); client.search(query).then(function (resp) { console.log(resp.hits.hits); var response = resp.hits.hits.map(function(e){ return e._source.pin; }) res.send(response); }, function (err) { console.log(err.message); res.status(500).end(); }); }); app.use('/api', router); var port = process.env.PORT || 8080; app.listen(port); console.log("Backend is running on port " + port);
Jugendhackt/wildmap
backend/index.js
JavaScript
mit
1,488
var generatetask = require('../source/ajgenesis/tasks/generate'), createtask = require('../create'), path = require('path'), fs = require('fs'), ajgenesis = require('ajgenesis'); exports['generate'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); ajgenesis.createDirectory('build'); process.chdir('build'); generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync('app.rb')); test.ok(fs.existsSync('public')); //test.ok(fs.existsSync(path.join('views', 'index.erb'))); test.ok(fs.existsSync('views')); test.ok(fs.existsSync(path.join('views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentlist.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentnew.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentview.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentedit.erb'))); test.ok(fs.existsSync(path.join('views', 'employeelist.erb'))); test.ok(fs.existsSync(path.join('views', 'employeenew.erb'))); test.ok(fs.existsSync(path.join('views', 'employeeview.erb'))); test.ok(fs.existsSync(path.join('views', 'employeeedit.erb'))); test.ok(fs.existsSync(path.join('entities'))); test.ok(fs.existsSync(path.join('entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('entities', 'department.rb'))); test.ok(fs.existsSync(path.join('entities', 'employee.rb'))); test.ok(fs.existsSync('controllers')); test.ok(fs.existsSync(path.join('controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); } exports['generate in directory'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); model.builddir = 'build'; if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync(path.join('build', 'app.rb'))); test.ok(fs.existsSync(path.join('build', 'public'))); test.ok(fs.existsSync(path.join('build', 'views'))); //test.ok(fs.existsSync(path.join('views', 'index.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('build', 'entities'))); test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); } exports['create and generate'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); createtask(null, ['build'], ajgenesis, function (err, result) { test.equal(err, null); test.ok(fs.existsSync('build')); model.builddir = 'build'; generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync(path.join('build', 'app.rb'))); test.ok(fs.existsSync(path.join('build', 'public'))); test.ok(fs.existsSync(path.join('build', 'views'))); test.ok(fs.existsSync(path.join('build', 'views', 'index.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentnew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentedit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeelist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeenew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeeview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeeedit.erb'))); test.ok(fs.existsSync(path.join('build', 'entities'))); test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); }); } function removeDirSync(dirname) { var filenames = fs.readdirSync(dirname); filenames.forEach(function (filename) { filename = path.join(dirname, filename); if (isDirectory(filename)) removeDirSync(filename); else removeFileSync(filename); }); fs.rmdirSync(dirname); } function removeFileSync(filename) { fs.unlinkSync(filename); } function isDirectory(filename) { try { var stats = fs.lstatSync(filename); return stats.isDirectory(); } catch (err) { return false; } }
ajlopez/AjGenesisNode-Sinatra
test/generate.js
JavaScript
mit
9,507
#include <math.h> #include <stdio.h> #include <pthread.h> #include <stdlib.h> #define THREAD_COUNT 4 typedef struct { int start; int end; } range_t; void *calculate_range(void* range) { range_t* curr_range = (range_t*)range; void* result = (void*)1; for (int i = curr_range->start; i < curr_range->end; i++) { double a = cos(i) * cos(i) + sin(i) * sin(i); if (a > 1.0005 || a < 0.9995) { result = (void*)0; } } free(curr_range); return result; } int main() { pthread_t threads[THREAD_COUNT]; int arg_start = 0; for (int i = 0; i < THREAD_COUNT; i++) { range_t *curr_range = (range_t*)malloc(sizeof(range_t)); curr_range->start = arg_start; curr_range->end = arg_start + 25000000; int res = pthread_create(&threads[i], NULL, calculate_range, curr_range); if (res != 0) { perror("Could not spawn new thread"); exit(-1); } arg_start = curr_range->end; } long final_result = 1; for (int i = 0; i < THREAD_COUNT; i++) { void *thread_result; int res = pthread_join(threads[i], (void **)&thread_result); if (res != 0) { perror("Could not spawn thread"); exit(-1); } final_result <<= (long)thread_result; } if (final_result & (1 << 4)) { printf("OK!\n"); } else { printf("Not OK!\n"); } return 0; }
arnaudoff/elsys
2015-2016/operating-systems/threads_homework/main.c
C
mit
1,476
package com.virtualfactory.screen.layer.components; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEventSubscriber; import de.lessvoid.nifty.controls.ButtonClickedEvent; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.window.WindowControl; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.render.NiftyImage; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import com.virtualfactory.engine.GameEngine; import com.virtualfactory.utils.CommonBuilders; import com.virtualfactory.utils.Pair; import java.util.Properties; /** * * @author David */ public class FlowChartScreenController implements Controller { private Nifty nifty; private Screen screen; private WindowControl winControls; private boolean isVisible; private GameEngine gameEngine; final CommonBuilders common = new CommonBuilders(); private NiftyImage flowChartImage; @Override public void bind( final Nifty nifty, final Screen screen, final Element element, final Properties parameter, final Attributes controlDefinitionAttributes) { this.nifty = nifty; this.screen = screen; this.winControls = screen.findNiftyControl("winFlowChartControl", WindowControl.class); Attributes x = new Attributes(); x.set("hideOnClose", "true"); this.winControls.bind(nifty, screen, winControls.getElement(), null, x); isVisible = false; } public boolean isIsVisible() { return isVisible; } public void setIsVisible(boolean isVisible) { this.isVisible = isVisible; } @Override public void init(Properties parameter, Attributes controlDefinitionAttributes) { } @Override public void onStartScreen() { } @Override public void onFocus(boolean getFocus) { } @Override public boolean inputEvent(final NiftyInputEvent inputEvent) { return false; } public void loadWindowControl(GameEngine game,int index, Pair<Integer,Integer> position){ this.gameEngine = game; if (index == -1){ winControls.getElement().setVisible(false); winControls.getContent().hide(); isVisible = false; }else{ winControls.getElement().setVisible(true); winControls.getContent().show(); isVisible = true; if (position != null){ if (winControls.getWidth() + position.getFirst() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth()) position.setFirst(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth() - winControls.getWidth()); if (winControls.getHeight() + position.getSecond() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight()) position.setSecond(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight() - winControls.getHeight()); winControls.getElement().setConstraintX(new SizeValue(position.getFirst() + "px")); winControls.getElement().setConstraintY(new SizeValue(position.getSecond() + "px")); winControls.getElement().getParent().layoutElements(); } winControls.getElement().setConstraintX(null); winControls.getElement().setConstraintY(null); } loadValues(index); } private void loadValues(int index){ if (index == -1){ flowChartImage = nifty.createImage("Models/Flows/none.png", false); screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage); }else{ flowChartImage = nifty.createImage("Models/Flows/" + gameEngine.getGameData().getCurrentGame().getFlowImage(), false); screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage); } } @NiftyEventSubscriber(id="closeFlowChart") public void onCloseFlowChartButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); loadWindowControl(gameEngine, -1, null); } }
uprm-gaming/virtual-factory
src/com/virtualfactory/screen/layer/components/FlowChartScreenController.java
Java
mit
4,455
const S$ = require('S$'); function loadSrc(obj, src) { throw src; } const cookies = S$.symbol('Cookie', ''); const world = {}; if (cookies) { if (/iPhone/.exec(cookies)) { loadSrc(world, '/resources/' + cookies); } loadSrc(world, '/resources/unknown'); } else { loadSrc(world, '/resources/fresh'); }
ExpoSEJS/ExpoSE
tests/regex/cookies/t1.js
JavaScript
mit
332
--- layout: post title: "Problem 2_0" modified: categories: /AcceleratedC++/ch2 excerpt: tags: [] image: feature: date: 2015-09-25T00:37:18-07:00 --- [Github Source](https://github.com/patricknyu/AcceleratedCPlusPlus/tree/master/ch2/Question2_0) ###Q: Compile and run the program presented in this chapter. ###A: ```c++ #include <iostream> #include <string> // say what standard-library names we use using std::cin; using std::endl; using std::cout; using std::string; int main() { // ask for the person's name cout << "Please enter your first name: "; // read the name string name; cin >> name; // build the message that we intend to write const string greeting = "Hello, " + name + "!"; // the number of blanks surrounding the greeting const int pad = 1; // the number of rows and columns to write const int rows = pad * 2 + 3; const string::size_type cols = greeting.size() + pad * 2 + 2; // write a blank line to separate the output from the input cout << endl; // write rows rows of output // invariant: we have written r rows so far for (int r = 0; r != rows; ++r) { string::size_type c = 0; // invariant: we have written c characters so far in the current row while (c != cols) { // is it time to write the greeting? if (r == pad + 1 && c == pad + 1) { cout << greeting; c += greeting.size(); } else { // are we on the border? if (r == 0 || r == rows - 1 ||c == 0 || c == cols - 1) cout << "*"; else cout << " "; ++c; } } cout << endl; } return 0; } ```
patricknyu/patricknyu.github.io
_posts/AcceleratedC++/ch2/2015-09-25-problem-2_0.markdown
Markdown
mit
1,557
module.exports = function (seneca, util) { //var Joi = util.Joi }
senecajs/seneca-dynamo-store
dynamo-store-doc.js
JavaScript
mit
68
package Digivolver; public class Digivolution{ private Digimon digimon; private int minDp = 0; private int maxDp = 0; public boolean isWithinDp(int minDp, int maxDp){ return this.minDp<=maxDp && this.maxDp>=minDp; } public Digivolution(Digimon digimon, int minDp, int maxDp) { this.digimon = digimon; this.minDp = minDp; this.maxDp = maxDp; } public Digimon getDigimon() { return digimon; } public void setDigimon(Digimon digimon) { this.digimon = digimon; } public int getMinDp(){ return minDp; } public int getMaxDp(){ return maxDp; } }
mp-pinheiro/DW2Digivolver
src/Digivolver/Digivolution.java
Java
mit
580
import re import hashlib FNAME_MATCH = re.compile(r'/([^/]+)$') # From the last slash to the end of the string PREFIX = re.compile(r'([^:]+://)(/)?(.+)') # Check for a prefix like data:// def getParentAndBase(path): match = PREFIX.match(path) if match is None: if path.endswith('/'): stripped_path = path[:-1] else: stripped_path = path base = FNAME_MATCH.search(stripped_path) if base is None: raise ValueError('Invalid path') parent = FNAME_MATCH.sub('', stripped_path) return parent, base.group(1) else: prefix, leading_slash, uri = match.groups() parts = uri.split('/') parent_path = '/'.join(parts[:-1]) if leading_slash is not None: parent_path = '{prefix}/{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1])) else: parent_path = '{prefix}{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1])) return parent_path, parts[-1] def pathJoin(parent, base): if parent.endswith('/'): return parent + base return parent + '/' + base def md5_for_file(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return str(hash_md5.hexdigest()) def md5_for_str(content): hash_md5 = hashlib.md5() hash_md5.update(content.encode()) return str(hash_md5.hexdigest())
algorithmiaio/algorithmia-python
Algorithmia/util.py
Python
mit
1,473
#ifndef VECTOR4_H #define VECTOR4_H #include "gamemath_internal.h" GAMEMATH_NAMESPACE_BEGIN GAMEMATH_ALIGNEDTYPE_PRE class GAMEMATH_ALIGNEDTYPE_MID Vector4 : public AlignedAllocation { friend class Matrix4; friend GAMEMATH_INLINE Vector4 operator +(const Vector4 &a, const Vector4 &b); friend GAMEMATH_INLINE Vector4 operator -(const Vector4 &a, const Vector4 &b); friend GAMEMATH_INLINE Vector4 operator *(const float, const Vector4 &vector); friend GAMEMATH_INLINE Vector4 operator *(const Vector4 &vector, const float); friend class Ray3d; friend class Box3d; public: Vector4(); Vector4(const float x, const float y, const float z, const float w); #if !defined(GAMEMATH_NO_INTRINSICS) Vector4(const __m128 value); #endif /** * Returns the x component of this vector. */ float x() const; /** * Returns the y component of this vector. */ float y() const; /** * Returns the z component of this vector. */ float z() const; /** * Returns the w component of this vector. Usually 1 means this is a position vector, while 0 * means this is a directional vector. */ float w() const; /** * Changes the X component of this vector. */ void setX(float x); /** * Changes the Y component of this vector. */ void setY(float y); /** * Changes the Z component of this vector. */ void setZ(float z); /** * Changes the W component of this vector. */ void setW(float w); /** * Computes the squared length of this vector. This method is significantly * faster than computing the normal length, since the square root can be omitted. */ float lengthSquared() const; /** * Computes this vector's length. */ float length() const; /** * Normalizes this vector by dividing its components by this vectors length. */ Vector4 &normalize(); /** * Normalizes using a reciprocal square root, which only has 11-bit precision. Use this if the * result doesn't need to be very precisely normalized. */ Vector4 &normalizeEstimated(); /** * Normalizes this vector and returns it in a new object, while leaving this object untouched. */ Vector4 normalized() const; /** * Computes the dot product between this and another vector. */ float dot(const Vector4 &vector) const; /** Returns the absolute of this vector. */ Vector4 absolute() const; /** Returns true if one of the components of this vector are negative or positive infinity. */ bool isInfinite() const; /** * Computes the three-dimensional cross product of two vectors, interpreting both vectors as directional vectors * (w=0). If either vector's w is not zero, the result may be wrong. * * @return this x vector */ Vector4 cross(const Vector4 &vector) const; /** * Adds another vector to this vector. */ Vector4 &operator +=(const Vector4 &vector); /** * Multiplies this vector with a scalar factor. * Only the x,y, and z components of the vector are multiplied. */ Vector4 &operator *=(const float factor); /** * Subtracts another vector from this vector. */ Vector4 &operator -=(const Vector4 &vector); /** * Returns a negated version of this vector, negating only the x, y, and z components. */ Vector4 operator -() const; #if !defined(GAMEMATH_NO_INTRINSICS) operator __m128() const; #endif /** Checks two vectors for equality. */ bool operator ==(const Vector4 &other) const; const float *data() const; float *data(); private: #if !defined(GAMEMATH_NO_INTRINSICS) union { struct { float mX; float mY; float mZ; float mW; }; __m128 mSse; }; #else float mX; float mY; float mZ; float mW; #endif // GAMEMATH_NO_INTRINSICS } GAMEMATH_ALIGNEDTYPE_POST; GAMEMATH_INLINE float Vector4::x() const { return mX; } GAMEMATH_INLINE float Vector4::y() const { return mY; } GAMEMATH_INLINE float Vector4::z() const { return mZ; } GAMEMATH_INLINE float Vector4::w() const { return mW; } GAMEMATH_INLINE void Vector4::setX(float x) { mX = x; } GAMEMATH_INLINE void Vector4::setY(float y) { mY = y; } GAMEMATH_INLINE void Vector4::setZ(float z) { mZ = z; } GAMEMATH_INLINE void Vector4::setW(float w) { mW = w; } GAMEMATH_INLINE const float *Vector4::data() const { return &mX; } GAMEMATH_INLINE float *Vector4::data() { return &mX; } GAMEMATH_NAMESPACE_END #if !defined(GAMEMATH_NO_INTRINSICS) #include "vector4_sse.h" #else #include "vector4_sisd.h" #endif // GAMEMATH_NO_INTRINSICS #endif // VECTOR4_H
GrognardsFromHell/EvilTemple-GameMath
include/vector4.h
C
mit
5,340
/** * @file query.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2017-2021 TileDB, 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. * * @section DESCRIPTION * * This file implements class Query. */ #include "tiledb/sm/query/query.h" #include "tiledb/common/heap_memory.h" #include "tiledb/common/logger.h" #include "tiledb/common/memory.h" #include "tiledb/sm/array/array.h" #include "tiledb/sm/enums/query_status.h" #include "tiledb/sm/enums/query_type.h" #include "tiledb/sm/fragment/fragment_metadata.h" #include "tiledb/sm/misc/parse_argument.h" #include "tiledb/sm/query/dense_reader.h" #include "tiledb/sm/query/global_order_writer.h" #include "tiledb/sm/query/ordered_writer.h" #include "tiledb/sm/query/query_condition.h" #include "tiledb/sm/query/reader.h" #include "tiledb/sm/query/sparse_global_order_reader.h" #include "tiledb/sm/query/sparse_unordered_with_dups_reader.h" #include "tiledb/sm/query/unordered_writer.h" #include "tiledb/sm/rest/rest_client.h" #include "tiledb/sm/storage_manager/storage_manager.h" #include "tiledb/sm/tile/writer_tile.h" #include <cassert> #include <iostream> #include <sstream> using namespace tiledb::common; using namespace tiledb::sm::stats; namespace tiledb { namespace sm { /* ****************************** */ /* CONSTRUCTORS & DESTRUCTORS */ /* ****************************** */ Query::Query(StorageManager* storage_manager, Array* array, URI fragment_uri) : array_(array) , array_schema_(array->array_schema_latest_ptr()) , layout_(Layout::ROW_MAJOR) , storage_manager_(storage_manager) , stats_(storage_manager_->stats()->create_child("Query")) , logger_(storage_manager->logger()->clone("Query", ++logger_id_)) , has_coords_buffer_(false) , has_zipped_coords_buffer_(false) , coord_buffer_is_set_(false) , coord_data_buffer_is_set_(false) , coord_offsets_buffer_is_set_(false) , data_buffer_name_("") , offsets_buffer_name_("") , disable_check_global_order_(false) , fragment_uri_(fragment_uri) { assert(array->is_open()); auto st = array->get_query_type(&type_); assert(st.ok()); if (type_ == QueryType::WRITE) { subarray_ = Subarray(array, stats_, logger_); } else { subarray_ = Subarray(array, Layout::ROW_MAJOR, stats_, logger_); } fragment_metadata_ = array->fragment_metadata(); coords_info_.coords_buffer_ = nullptr; coords_info_.coords_buffer_size_ = nullptr; coords_info_.coords_num_ = 0; coords_info_.has_coords_ = false; callback_ = nullptr; callback_data_ = nullptr; status_ = QueryStatus::UNINITIALIZED; if (storage_manager != nullptr) config_ = storage_manager->config(); // Set initial subarray configuration subarray_.set_config(config_); rest_scratch_ = make_shared<Buffer>(HERE()); } Query::~Query() { bool found = false; bool use_malloc_trim = false; const Status& st = config_.get<bool>("sm.mem.malloc_trim", &use_malloc_trim, &found); if (st.ok() && found && use_malloc_trim) { tdb_malloc_trim(); } }; /* ****************************** */ /* API */ /* ****************************** */ Status Query::add_range( unsigned dim_idx, const void* start, const void* end, const void* stride) { if (dim_idx >= array_schema_->dim_num()) return logger_->status( Status_QueryError("Cannot add range; Invalid dimension index")); if (start == nullptr || end == nullptr) return logger_->status( Status_QueryError("Cannot add range; Invalid range")); if (stride != nullptr) return logger_->status(Status_QueryError( "Cannot add range; Setting range stride is currently unsupported")); if (array_schema_->domain()->dimension(dim_idx)->var_size()) return logger_->status( Status_QueryError("Cannot add range; Range must be fixed-sized")); // Prepare a temp range std::vector<uint8_t> range; auto coord_size = array_schema_->dimension(dim_idx)->coord_size(); range.resize(2 * coord_size); std::memcpy(&range[0], start, coord_size); std::memcpy(&range[coord_size], end, coord_size); bool read_range_oob_error = true; if (type_ == QueryType::READ) { // Get read_range_oob config setting bool found = false; std::string read_range_oob = config_.get("sm.read_range_oob", &found); assert(found); if (read_range_oob != "error" && read_range_oob != "warn") return logger_->status(Status_QueryError( "Invalid value " + read_range_oob + " for sm.read_range_obb. Acceptable values are 'error' or 'warn'.")); read_range_oob_error = read_range_oob == "error"; } else { if (!array_schema_->dense()) return logger_->status( Status_QueryError("Adding a subarray range to a write query is not " "supported in sparse arrays")); if (subarray_.is_set(dim_idx)) return logger_->status( Status_QueryError("Cannot add range; Multi-range dense writes " "are not supported")); } // Add range Range r(&range[0], 2 * coord_size); return subarray_.add_range(dim_idx, std::move(r), read_range_oob_error); } Status Query::add_range_var( unsigned dim_idx, const void* start, uint64_t start_size, const void* end, uint64_t end_size) { if (dim_idx >= array_schema_->dim_num()) return logger_->status( Status_QueryError("Cannot add range; Invalid dimension index")); if ((start == nullptr && start_size != 0) || (end == nullptr && end_size != 0)) return logger_->status( Status_QueryError("Cannot add range; Invalid range")); if (!array_schema_->domain()->dimension(dim_idx)->var_size()) return logger_->status( Status_QueryError("Cannot add range; Range must be variable-sized")); if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot add range; Function applicable only to reads")); // Get read_range_oob config setting bool found = false; std::string read_range_oob = config_.get("sm.read_range_oob", &found); assert(found); if (read_range_oob != "error" && read_range_oob != "warn") return logger_->status(Status_QueryError( "Invalid value " + read_range_oob + " for sm.read_range_obb. Acceptable values are 'error' or 'warn'.")); // Add range Range r; r.set_range_var(start, start_size, end, end_size); return subarray_.add_range(dim_idx, std::move(r), read_range_oob == "error"); } Status Query::get_range_num(unsigned dim_idx, uint64_t* range_num) const { if (type_ == QueryType::WRITE && !array_schema_->dense()) return logger_->status( Status_QueryError("Getting the number of ranges from a write query " "is not applicable to sparse arrays")); return subarray_.get_range_num(dim_idx, range_num); } Status Query::get_range( unsigned dim_idx, uint64_t range_idx, const void** start, const void** end, const void** stride) const { if (type_ == QueryType::WRITE && !array_schema_->dense()) return logger_->status( Status_QueryError("Getting a range from a write query is not " "applicable to sparse arrays")); *stride = nullptr; return subarray_.get_range(dim_idx, range_idx, start, end); } Status Query::get_range_var_size( unsigned dim_idx, uint64_t range_idx, uint64_t* start_size, uint64_t* end_size) const { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Getting a var range size from a write query is not applicable")); return subarray_.get_range_var_size(dim_idx, range_idx, start_size, end_size); ; } Status Query::get_range_var( unsigned dim_idx, uint64_t range_idx, void* start, void* end) const { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Getting a var range from a write query is not applicable")); uint64_t start_size = 0; uint64_t end_size = 0; subarray_.get_range_var_size(dim_idx, range_idx, &start_size, &end_size); const void* range_start; const void* range_end; const void* stride; RETURN_NOT_OK( get_range(dim_idx, range_idx, &range_start, &range_end, &stride)); std::memcpy(start, range_start, start_size); std::memcpy(end, range_end, end_size); return Status::Ok(); } Status Query::add_range_by_name( const std::string& dim_name, const void* start, const void* end, const void* stride) { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return add_range(dim_idx, start, end, stride); } Status Query::add_range_var_by_name( const std::string& dim_name, const void* start, uint64_t start_size, const void* end, uint64_t end_size) { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return add_range_var(dim_idx, start, start_size, end, end_size); } Status Query::get_range_num_from_name( const std::string& dim_name, uint64_t* range_num) const { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return get_range_num(dim_idx, range_num); } Status Query::get_range_from_name( const std::string& dim_name, uint64_t range_idx, const void** start, const void** end, const void** stride) const { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return get_range(dim_idx, range_idx, start, end, stride); } Status Query::get_range_var_size_from_name( const std::string& dim_name, uint64_t range_idx, uint64_t* start_size, uint64_t* end_size) const { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return get_range_var_size(dim_idx, range_idx, start_size, end_size); } Status Query::get_range_var_from_name( const std::string& dim_name, uint64_t range_idx, void* start, void* end) const { unsigned dim_idx; RETURN_NOT_OK( array_schema_->domain()->get_dimension_index(dim_name, &dim_idx)); return get_range_var(dim_idx, range_idx, start, end); } Status Query::get_est_result_size(const char* name, uint64_t* size) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get estimated result size; Operation currently " "unsupported for write queries")); if (name == nullptr) return logger_->status(Status_QueryError( "Cannot get estimated result size; Name cannot be null")); if (name == constants::coords && !array_schema_->domain()->all_dims_same_type()) return logger_->status(Status_QueryError( "Cannot get estimated result size; Not applicable to zipped " "coordinates in arrays with heterogeneous domain")); if (name == constants::coords && !array_schema_->domain()->all_dims_fixed()) return logger_->status(Status_QueryError( "Cannot get estimated result size; Not applicable to zipped " "coordinates in arrays with domains with variable-sized dimensions")); if (array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string( "Cannot get estimated result size; Input attribute/dimension '") + name + "' is nullable")); if (array_->is_remote() && !subarray_.est_result_size_computed()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status( Status_QueryError("Error in query estimate result size; remote " "array with no rest client.")); RETURN_NOT_OK( rest_client->get_query_est_result_sizes(array_->array_uri(), this)); } return subarray_.get_est_result_size_internal( name, size, &config_, storage_manager_->compute_tp()); } Status Query::get_est_result_size( const char* name, uint64_t* size_off, uint64_t* size_val) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get estimated result size; Operation currently " "unsupported for write queries")); if (array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string( "Cannot get estimated result size; Input attribute/dimension '") + name + "' is nullable")); if (array_->is_remote() && !subarray_.est_result_size_computed()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status( Status_QueryError("Error in query estimate result size; remote " "array with no rest client.")); RETURN_NOT_OK( rest_client->get_query_est_result_sizes(array_->array_uri(), this)); } return subarray_.get_est_result_size( name, size_off, size_val, &config_, storage_manager_->compute_tp()); } Status Query::get_est_result_size_nullable( const char* name, uint64_t* size_val, uint64_t* size_validity) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get estimated result size; Operation currently " "unsupported for write queries")); if (name == nullptr) return logger_->status(Status_QueryError( "Cannot get estimated result size; Name cannot be null")); if (!array_schema_->attribute(name)) return logger_->status(Status_QueryError( "Cannot get estimated result size; Nullable API is only" "applicable to attributes")); if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot get estimated result size; Input attribute '") + name + "' is not nullable")); if (array_->is_remote() && !subarray_.est_result_size_computed()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status( Status_QueryError("Error in query estimate result size; remote " "array with no rest client.")); return logger_->status( Status_QueryError("Error in query estimate result size; unimplemented " "for nullable attributes in remote arrays.")); } return subarray_.get_est_result_size_nullable( name, size_val, size_validity, &config_, storage_manager_->compute_tp()); } Status Query::get_est_result_size_nullable( const char* name, uint64_t* size_off, uint64_t* size_val, uint64_t* size_validity) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get estimated result size; Operation currently " "unsupported for write queries")); if (!array_schema_->attribute(name)) return logger_->status(Status_QueryError( "Cannot get estimated result size; Nullable API is only" "applicable to attributes")); if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot get estimated result size; Input attribute '") + name + "' is not nullable")); if (array_->is_remote() && !subarray_.est_result_size_computed()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status( Status_QueryError("Error in query estimate result size; remote " "array with no rest client.")); return logger_->status( Status_QueryError("Error in query estimate result size; unimplemented " "for nullable attributes in remote arrays.")); } return subarray_.get_est_result_size_nullable( name, size_off, size_val, size_validity, &config_, storage_manager_->compute_tp()); } std::unordered_map<std::string, Subarray::ResultSize> Query::get_est_result_size_map() { return subarray_.get_est_result_size_map( &config_, storage_manager_->compute_tp()); } std::unordered_map<std::string, Subarray::MemorySize> Query::get_max_mem_size_map() { return subarray_.get_max_mem_size_map( &config_, storage_manager_->compute_tp()); } Status Query::get_written_fragment_num(uint32_t* num) const { if (type_ != QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get number of fragments; Applicable only to WRITE mode")); *num = (uint32_t)written_fragment_info_.size(); return Status::Ok(); } Status Query::get_written_fragment_uri(uint32_t idx, const char** uri) const { if (type_ != QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get fragment URI; Applicable only to WRITE mode")); auto num = (uint32_t)written_fragment_info_.size(); if (idx >= num) return logger_->status( Status_QueryError("Cannot get fragment URI; Invalid fragment index")); *uri = written_fragment_info_[idx].uri_.c_str(); return Status::Ok(); } Status Query::get_written_fragment_timestamp_range( uint32_t idx, uint64_t* t1, uint64_t* t2) const { if (type_ != QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot get fragment timestamp range; Applicable only to WRITE mode")); auto num = (uint32_t)written_fragment_info_.size(); if (idx >= num) return logger_->status(Status_QueryError( "Cannot get fragment timestamp range; Invalid fragment index")); *t1 = written_fragment_info_[idx].timestamp_range_.first; *t2 = written_fragment_info_[idx].timestamp_range_.second; return Status::Ok(); } const Array* Query::array() const { return array_; } Array* Query::array() { return array_; } const ArraySchema& Query::array_schema() const { return *(array_schema_.get()); } std::vector<std::string> Query::buffer_names() const { std::vector<std::string> ret; // Add to the buffer names the attributes, as well as the dimensions only if // coords_buffer_ has not been set for (const auto& it : buffers_) { if (!array_schema_->is_dim(it.first) || (!coords_info_.coords_buffer_)) ret.push_back(it.first); } // Special zipped coordinates name if (coords_info_.coords_buffer_) ret.push_back(constants::coords); return ret; } QueryBuffer Query::buffer(const std::string& name) const { // Special zipped coordinates if (type_ == QueryType::WRITE && name == constants::coords) return QueryBuffer( coords_info_.coords_buffer_, nullptr, coords_info_.coords_buffer_size_, nullptr); // Attribute or dimension auto buf = buffers_.find(name); if (buf != buffers_.end()) return buf->second; // Named buffer does not exist return QueryBuffer{}; } Status Query::finalize() { if (status_ == QueryStatus::UNINITIALIZED) return Status::Ok(); if (array_->is_remote()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status(Status_QueryError( "Error in query finalize; remote array with no rest client.")); return rest_client->finalize_query_to_rest(array_->array_uri(), this); } RETURN_NOT_OK(strategy_->finalize()); status_ = QueryStatus::COMPLETED; return Status::Ok(); } Status Query::get_buffer( const char* name, void** buffer, uint64_t** buffer_size) const { // Check attribute if (name != constants::coords) { if (array_schema_->attribute(name) == nullptr && array_schema_->dimension(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute/dimension name '") + name + "'")); } if (array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is var-sized")); return get_data_buffer(name, buffer, buffer_size); } Status Query::get_buffer( const char* name, uint64_t** buffer_off, uint64_t** buffer_off_size, void** buffer_val, uint64_t** buffer_val_size) const { // Check attribute if (name == constants::coords) { return logger_->status( Status_QueryError("Cannot get buffer; Coordinates are not var-sized")); } if (array_schema_->attribute(name) == nullptr && array_schema_->dimension(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute/dimension name '") + name + "'")); if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is fixed-sized")); // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { *buffer_off = (uint64_t*)it->second.buffer_; *buffer_off_size = it->second.buffer_size_; *buffer_val = it->second.buffer_var_; *buffer_val_size = it->second.buffer_var_size_; return Status::Ok(); } // Named buffer does not exist *buffer_off = nullptr; *buffer_off_size = nullptr; *buffer_val = nullptr; *buffer_val_size = nullptr; return Status::Ok(); } Status Query::get_offsets_buffer( const char* name, uint64_t** buffer_off, uint64_t** buffer_off_size) const { // Check attribute if (name == constants::coords) { return logger_->status( Status_QueryError("Cannot get buffer; Coordinates are not var-sized")); } if (array_schema_->attribute(name) == nullptr && array_schema_->dimension(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute/dimension name '") + name + "'")); if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is fixed-sized")); // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { *buffer_off = (uint64_t*)it->second.buffer_; *buffer_off_size = it->second.buffer_size_; return Status::Ok(); } // Named buffer does not exist *buffer_off = nullptr; *buffer_off_size = nullptr; return Status::Ok(); } Status Query::get_data_buffer( const char* name, void** buffer, uint64_t** buffer_size) const { // Check attribute if (name != constants::coords) { if (array_schema_->attribute(name) == nullptr && array_schema_->dimension(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute/dimension name '") + name + "'")); } // Special zipped coordinates if (type_ == QueryType::WRITE && name == constants::coords) { *buffer = coords_info_.coords_buffer_; *buffer_size = coords_info_.coords_buffer_size_; return Status::Ok(); } // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { if (!array_schema_->var_size(name)) { *buffer = it->second.buffer_; *buffer_size = it->second.buffer_size_; } else { *buffer = it->second.buffer_var_; *buffer_size = it->second.buffer_var_size_; } return Status::Ok(); } // Named buffer does not exist *buffer = nullptr; *buffer_size = nullptr; return Status::Ok(); } Status Query::get_validity_buffer( const char* name, uint8_t** buffer_validity_bytemap, uint64_t** buffer_validity_bytemap_size) const { // Check attribute if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is non-nullable")); // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { auto vv = &it->second.validity_vector_; *buffer_validity_bytemap = vv->bytemap(); *buffer_validity_bytemap_size = vv->bytemap_size(); } return Status::Ok(); } Status Query::get_buffer_vbytemap( const char* name, uint64_t** buffer_off, uint64_t** buffer_off_size, void** buffer_val, uint64_t** buffer_val_size, uint8_t** buffer_validity_bytemap, uint64_t** buffer_validity_bytemap_size) const { const ValidityVector* vv = nullptr; RETURN_NOT_OK(get_buffer( name, buffer_off, buffer_off_size, buffer_val, buffer_val_size, &vv)); if (vv != nullptr) { *buffer_validity_bytemap = vv->bytemap(); *buffer_validity_bytemap_size = vv->bytemap_size(); } return Status::Ok(); } Status Query::get_buffer_vbytemap( const char* name, void** buffer, uint64_t** buffer_size, uint8_t** buffer_validity_bytemap, uint64_t** buffer_validity_bytemap_size) const { const ValidityVector* vv = nullptr; RETURN_NOT_OK(get_buffer(name, buffer, buffer_size, &vv)); if (vv != nullptr) { *buffer_validity_bytemap = vv->bytemap(); *buffer_validity_bytemap_size = vv->bytemap_size(); } return Status::Ok(); } Status Query::get_buffer( const char* name, void** buffer, uint64_t** buffer_size, const ValidityVector** validity_vector) const { // Check nullable attribute if (array_schema_->attribute(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute name '") + name + "'")); if (array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is var-sized")); if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is non-nullable")); // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { *buffer = it->second.buffer_; *buffer_size = it->second.buffer_size_; *validity_vector = &it->second.validity_vector_; return Status::Ok(); } // Named buffer does not exist *buffer = nullptr; *buffer_size = nullptr; *validity_vector = nullptr; return Status::Ok(); } Status Query::get_buffer( const char* name, uint64_t** buffer_off, uint64_t** buffer_off_size, void** buffer_val, uint64_t** buffer_val_size, const ValidityVector** validity_vector) const { // Check attribute if (array_schema_->attribute(name) == nullptr) return logger_->status(Status_QueryError( std::string("Cannot get buffer; Invalid attribute name '") + name + "'")); if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is fixed-sized")); if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot get buffer; '") + name + "' is non-nullable")); // Attribute or dimension auto it = buffers_.find(name); if (it != buffers_.end()) { *buffer_off = (uint64_t*)it->second.buffer_; *buffer_off_size = it->second.buffer_size_; *buffer_val = it->second.buffer_var_; *buffer_val_size = it->second.buffer_var_size_; *validity_vector = &it->second.validity_vector_; return Status::Ok(); } // Named buffer does not exist *buffer_off = nullptr; *buffer_off_size = nullptr; *buffer_val = nullptr; *buffer_val_size = nullptr; *validity_vector = nullptr; return Status::Ok(); } Status Query::get_attr_serialization_state( const std::string& attribute, SerializationState::AttrState** state) { *state = &serialization_state_.attribute_states[attribute]; return Status::Ok(); } bool Query::has_results() const { if (status_ == QueryStatus::UNINITIALIZED || type_ == QueryType::WRITE) return false; for (const auto& it : buffers_) { if (*(it.second.buffer_size_) != 0) return true; } return false; } Status Query::init() { // Only if the query has not been initialized before if (status_ == QueryStatus::UNINITIALIZED) { // Check if the array got closed if (array_ == nullptr || !array_->is_open()) return logger_->status(Status_QueryError( "Cannot init query; The associated array is not open")); // Check if the array got re-opened with a different query type QueryType array_query_type; RETURN_NOT_OK(array_->get_query_type(&array_query_type)); if (array_query_type != type_) { std::stringstream errmsg; errmsg << "Cannot init query; " << "Associated array query type does not match query type: " << "(" << query_type_str(array_query_type) << " != " << query_type_str(type_) << ")"; return logger_->status(Status_QueryError(errmsg.str())); } RETURN_NOT_OK(check_buffer_names()); RETURN_NOT_OK(create_strategy()); RETURN_NOT_OK(strategy_->init()); } status_ = QueryStatus::INPROGRESS; return Status::Ok(); } URI Query::first_fragment_uri() const { if (type_ == QueryType::WRITE || fragment_metadata_.empty()) return URI(); return fragment_metadata_.front()->fragment_uri(); } URI Query::last_fragment_uri() const { if (type_ == QueryType::WRITE || fragment_metadata_.empty()) return URI(); return fragment_metadata_.back()->fragment_uri(); } Layout Query::layout() const { return layout_; } const QueryCondition* Query::condition() const { if (type_ == QueryType::WRITE) return nullptr; return &condition_; } Status Query::cancel() { status_ = QueryStatus::FAILED; return Status::Ok(); } Status Query::process() { if (status_ == QueryStatus::UNINITIALIZED) return logger_->status( Status_QueryError("Cannot process query; Query is not initialized")); status_ = QueryStatus::INPROGRESS; // Process query Status st = strategy_->dowork(); // Handle error if (!st.ok()) { status_ = QueryStatus::FAILED; return st; } if (type_ == QueryType::WRITE && layout_ == Layout::GLOBAL_ORDER) { // reset coord buffer marker at end of global write // this will allow for the user to properly set the next write batch coord_buffer_is_set_ = false; coord_data_buffer_is_set_ = false; coord_offsets_buffer_is_set_ = false; } // Check if the query is complete bool completed = !strategy_->incomplete(); // Handle callback and status if (completed) { if (callback_ != nullptr) callback_(callback_data_); status_ = QueryStatus::COMPLETED; } else { // Incomplete status_ = QueryStatus::INCOMPLETE; } return Status::Ok(); } Status Query::create_strategy() { if (type_ == QueryType::WRITE) { if (layout_ == Layout::COL_MAJOR || layout_ == Layout::ROW_MAJOR) { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( OrderedWriter, stats_->create_child("Writer"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, written_fragment_info_, disable_check_global_order_, coords_info_, fragment_uri_)); } else if (layout_ == Layout::UNORDERED) { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( UnorderedWriter, stats_->create_child("Writer"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, written_fragment_info_, disable_check_global_order_, coords_info_, fragment_uri_)); } else if (layout_ == Layout::GLOBAL_ORDER) { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( GlobalOrderWriter, stats_->create_child("Writer"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, written_fragment_info_, disable_check_global_order_, coords_info_, fragment_uri_)); } else { assert(false); } } else { bool use_default = true; if (use_refactored_sparse_unordered_with_dups_reader() && !array_schema_->dense() && layout_ == Layout::UNORDERED && array_schema_->allows_dups()) { use_default = false; auto&& [st, non_overlapping_ranges]{Query::non_overlapping_ranges()}; RETURN_NOT_OK(st); if (*non_overlapping_ranges || !subarray_.is_set() || subarray_.range_num() == 1) { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( SparseUnorderedWithDupsReader<uint8_t>, stats_->create_child("Reader"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, condition_)); } else { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( SparseUnorderedWithDupsReader<uint64_t>, stats_->create_child("Reader"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, condition_)); } } else if ( use_refactored_sparse_global_order_reader() && !array_schema_->dense() && (layout_ == Layout::GLOBAL_ORDER || (layout_ == Layout::UNORDERED && subarray_.range_num() <= 1))) { // Using the reader for unordered queries to do deduplication. use_default = false; strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( SparseGlobalOrderReader, stats_->create_child("Reader"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, condition_)); } else if (use_refactored_dense_reader() && array_schema_->dense()) { bool all_dense = true; for (auto& frag_md : fragment_metadata_) all_dense &= frag_md->dense(); if (all_dense) { use_default = false; strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( DenseReader, stats_->create_child("Reader"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, condition_)); } } if (use_default) { strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new( Reader, stats_->create_child("Reader"), logger_, storage_manager_, array_, config_, buffers_, subarray_, layout_, condition_)); } } if (strategy_ == nullptr) return logger_->status( Status_QueryError("Cannot create strategy; allocation failed")); return Status::Ok(); } IQueryStrategy* Query::strategy() { if (strategy_ == nullptr) { create_strategy(); } return strategy_.get(); } void Query::clear_strategy() { strategy_ = nullptr; } Status Query::disable_check_global_order() { if (status_ != QueryStatus::UNINITIALIZED) return logger_->status(Status_QueryError( "Cannot disable checking global order after initialization")); if (type_ == QueryType::READ) return logger_->status(Status_QueryError( "Cannot disable checking global order; Applicable only to writes")); disable_check_global_order_ = true; return Status::Ok(); } Status Query::check_buffer_names() { if (type_ == QueryType::WRITE) { // If the array is sparse, the coordinates must be provided if (!array_schema_->dense() && !coords_info_.has_coords_) return logger_->status(Status_WriterError( "Sparse array writes expect the coordinates of the " "cells to be written")); // If the layout is unordered, the coordinates must be provided if (layout_ == Layout::UNORDERED && !coords_info_.has_coords_) return logger_->status( Status_WriterError("Unordered writes expect the coordinates of the " "cells to be written")); // All attributes/dimensions must be provided auto expected_num = array_schema_->attribute_num(); expected_num += (coord_buffer_is_set_ || coord_data_buffer_is_set_ || coord_offsets_buffer_is_set_) ? array_schema_->dim_num() : 0; if (buffers_.size() != expected_num) return logger_->status( Status_WriterError("Writes expect all attributes (and coordinates in " "the sparse/unordered case) to be set")); } return Status::Ok(); } Status Query::check_set_fixed_buffer(const std::string& name) { if (name == constants::coords && !array_schema_->domain()->all_dims_same_type()) return logger_->status(Status_QueryError( "Cannot set buffer; Setting a buffer for zipped coordinates is not " "applicable to heterogeneous domains")); if (name == constants::coords && !array_schema_->domain()->all_dims_fixed()) return logger_->status(Status_QueryError( "Cannot set buffer; Setting a buffer for zipped coordinates is not " "applicable to domains with variable-sized dimensions")); return Status::Ok(); } Status Query::set_config(const Config& config) { config_ = config; // Refresh memory budget configuration. if (strategy_ != nullptr) RETURN_NOT_OK(strategy_->initialize_memory_budget()); // Set subarray's config for backwards compatibility // Users expect the query config to effect the subarray based on existing // behavior before subarray was exposed directly subarray_.set_config(config_); return Status::Ok(); } Status Query::set_coords_buffer(void* buffer, uint64_t* buffer_size) { // Set zipped coordinates buffer coords_info_.coords_buffer_ = buffer; coords_info_.coords_buffer_size_ = buffer_size; coords_info_.has_coords_ = true; return Status::Ok(); } Status Query::set_buffer( const std::string& name, void* const buffer, uint64_t* const buffer_size, const bool check_null_buffers) { RETURN_NOT_OK(check_set_fixed_buffer(name)); // Check buffer if (check_null_buffers && buffer == nullptr) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_size == nullptr) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // For easy reference const bool is_dim = array_schema_->is_dim(name); const bool is_attr = array_schema_->is_attr(name); // Check that attribute/dimension exists if (name != constants::coords && !is_dim && !is_attr) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Invalid attribute/dimension '") + name + "'")); // Must not be nullable if (array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute/dimension '") + name + "' is nullable")); // Check that attribute/dimension is fixed-sized const bool var_size = (name != constants::coords && array_schema_->var_size(name)); if (var_size) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute/dimension '") + name + "' is var-sized")); // Check if zipped coordinates coexist with separate coordinate buffers if ((is_dim && has_zipped_coords_buffer_) || (name == constants::coords && has_coords_buffer_)) return logger_->status(Status_QueryError( std::string("Cannot set separate coordinate buffers and " "a zipped coordinate buffer in the same query"))); // Error if setting a new attribute/dimension after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute/dimension '") + name + "' after initialization")); if (name == constants::coords) { has_zipped_coords_buffer_ = true; // Set special function for zipped coordinates buffer if (type_ == QueryType::WRITE) return set_coords_buffer(buffer, buffer_size); } if (is_dim && type_ == QueryType::WRITE) { // Check number of coordinates uint64_t coords_num = *buffer_size / array_schema_->cell_size(name); if (coord_buffer_is_set_ && coords_num != coords_info_.coords_num_) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input buffer for dimension '") + name + "' has a different number of coordinates than previously " "set coordinate buffers")); coords_info_.coords_num_ = coords_num; coord_buffer_is_set_ = true; coords_info_.has_coords_ = true; } has_coords_buffer_ |= is_dim; // Set attribute buffer buffers_[name].set_data_buffer(buffer, buffer_size); return Status::Ok(); } Status Query::set_data_buffer( const std::string& name, void* const buffer, uint64_t* const buffer_size, const bool check_null_buffers) { RETURN_NOT_OK(check_set_fixed_buffer(name)); // Check buffer if (check_null_buffers && buffer == nullptr) if (type_ != QueryType::WRITE || *buffer_size != 0) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " buffer size is null")); // For easy reference const bool is_dim = array_schema_->is_dim(name); const bool is_attr = array_schema_->is_attr(name); // Check that attribute/dimension exists if (name != constants::coords && !is_dim && !is_attr) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Invalid attribute/dimension '") + name + "'")); if (array_schema_->dense() && type_ == QueryType::WRITE && !is_attr) { return logger_->status(Status_QueryError( std::string("Dense write queries cannot set dimension buffers"))); } // Check if zipped coordinates coexist with separate coordinate buffers if ((is_dim && has_zipped_coords_buffer_) || (name == constants::coords && has_coords_buffer_)) return logger_->status(Status_QueryError( std::string("Cannot set separate coordinate buffers and " "a zipped coordinate buffer in the same query"))); // Error if setting a new attribute/dimension after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute/dimension '") + name + "' after initialization")); if (name == constants::coords) { has_zipped_coords_buffer_ = true; // Set special function for zipped coordinates buffer if (type_ == QueryType::WRITE) return set_coords_buffer(buffer, buffer_size); } if (is_dim && type_ == QueryType::WRITE) { // Check number of coordinates uint64_t coords_num = *buffer_size / array_schema_->cell_size(name); if (coord_data_buffer_is_set_ && coords_num != coords_info_.coords_num_ && name == data_buffer_name_) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input buffer for dimension '") + name + "' has a different number of coordinates than previously " "set coordinate buffers")); coords_info_.coords_num_ = coords_num; coord_data_buffer_is_set_ = true; data_buffer_name_ = name; coords_info_.has_coords_ = true; } has_coords_buffer_ |= is_dim; // Set attribute/dimension buffer on the appropriate buffer if (!array_schema_->var_size(name)) // Fixed size data buffer buffers_[name].set_data_buffer(buffer, buffer_size); else // Var sized data buffer buffers_[name].set_data_var_buffer(buffer, buffer_size); return Status::Ok(); } Status Query::set_offsets_buffer( const std::string& name, uint64_t* const buffer_offsets, uint64_t* const buffer_offsets_size, const bool check_null_buffers) { RETURN_NOT_OK(check_set_fixed_buffer(name)); // Check buffer if (check_null_buffers && buffer_offsets == nullptr) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_offsets_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " buffer size is null")); // For easy reference const bool is_dim = array_schema_->is_dim(name); const bool is_attr = array_schema_->is_attr(name); // Neither a dimension nor an attribute if (!is_dim && !is_attr) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Invalid buffer name '") + name + "' (it should be an attribute or dimension)")); // Error if it is fixed-sized if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute/dimension '") + name + "' is fixed-sized")); // Error if setting a new attribute/dimension after initialization bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute/dimension '") + name + "' after initialization")); if (is_dim && type_ == QueryType::WRITE) { // Check number of coordinates uint64_t coords_num = *buffer_offsets_size / constants::cell_var_offset_size; if (coord_offsets_buffer_is_set_ && coords_num != coords_info_.coords_num_ && name == offsets_buffer_name_) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input buffer for dimension '") + name + "' has a different number of coordinates than previously " "set coordinate buffers")); coords_info_.coords_num_ = coords_num; coord_offsets_buffer_is_set_ = true; coords_info_.has_coords_ = true; offsets_buffer_name_ = name; } has_coords_buffer_ |= is_dim; // Set attribute/dimension buffer buffers_[name].set_offsets_buffer(buffer_offsets, buffer_offsets_size); return Status::Ok(); } Status Query::set_validity_buffer( const std::string& name, uint8_t* const buffer_validity_bytemap, uint64_t* const buffer_validity_bytemap_size, const bool check_null_buffers) { RETURN_NOT_OK(check_set_fixed_buffer(name)); ValidityVector validity_vector; RETURN_NOT_OK(validity_vector.init_bytemap( buffer_validity_bytemap, buffer_validity_bytemap_size)); // Check validity buffer if (check_null_buffers && validity_vector.buffer() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer is null")); // Check validity buffer size if (check_null_buffers && validity_vector.buffer_size() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer size is null")); // Must be an attribute if (!array_schema_->is_attr(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Buffer name '") + name + "' is not an attribute")); // Must be nullable if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute '") + name + "' is not nullable")); // Error if setting a new attribute after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute '") + name + "' after initialization")); // Set attribute/dimension buffer buffers_[name].set_validity_buffer(std::move(validity_vector)); return Status::Ok(); } Status Query::set_buffer( const std::string& name, uint64_t* const buffer_off, uint64_t* const buffer_off_size, void* const buffer_val, uint64_t* const buffer_val_size, const bool check_null_buffers) { // Check buffer if (check_null_buffers && buffer_val == nullptr) if (type_ != QueryType::WRITE || *buffer_val_size != 0) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_val_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " buffer size is null")); // Check offset buffer if (check_null_buffers && buffer_off == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " offset buffer is null")); // Check offset buffer size if (check_null_buffers && buffer_off_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " offset buffer size is null")); // For easy reference const bool is_dim = array_schema_->is_dim(name); const bool is_attr = array_schema_->is_attr(name); // Check that attribute/dimension exists if (!is_dim && !is_attr) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Invalid attribute/dimension '") + name + "'")); // Must not be nullable if (array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute/dimension '") + name + "' is nullable")); // Check that attribute/dimension is var-sized if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute/dimension '") + name + "' is fixed-sized")); // Error if setting a new attribute/dimension after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute/dimension '") + name + "' after initialization")); if (is_dim && type_ == QueryType::WRITE) { // Check number of coordinates uint64_t coords_num = *buffer_off_size / constants::cell_var_offset_size; if (coord_buffer_is_set_ && coords_num != coords_info_.coords_num_) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input buffer for dimension '") + name + "' has a different number of coordinates than previously " "set coordinate buffers")); coords_info_.coords_num_ = coords_num; coord_buffer_is_set_ = true; coords_info_.has_coords_ = true; } // Set attribute/dimension buffer buffers_[name].set_data_var_buffer(buffer_val, buffer_val_size); buffers_[name].set_offsets_buffer(buffer_off, buffer_off_size); return Status::Ok(); } Status Query::set_buffer_vbytemap( const std::string& name, void* const buffer, uint64_t* const buffer_size, uint8_t* const buffer_validity_bytemap, uint64_t* const buffer_validity_bytemap_size, const bool check_null_buffers) { // Convert the bytemap into a ValidityVector. ValidityVector vv; RETURN_NOT_OK( vv.init_bytemap(buffer_validity_bytemap, buffer_validity_bytemap_size)); return set_buffer( name, buffer, buffer_size, std::move(vv), check_null_buffers); } Status Query::set_buffer_vbytemap( const std::string& name, uint64_t* const buffer_off, uint64_t* const buffer_off_size, void* const buffer_val, uint64_t* const buffer_val_size, uint8_t* const buffer_validity_bytemap, uint64_t* const buffer_validity_bytemap_size, const bool check_null_buffers) { // Convert the bytemap into a ValidityVector. ValidityVector vv; RETURN_NOT_OK( vv.init_bytemap(buffer_validity_bytemap, buffer_validity_bytemap_size)); return set_buffer( name, buffer_off, buffer_off_size, buffer_val, buffer_val_size, std::move(vv), check_null_buffers); } Status Query::set_buffer( const std::string& name, void* const buffer, uint64_t* const buffer_size, ValidityVector&& validity_vector, const bool check_null_buffers) { RETURN_NOT_OK(check_set_fixed_buffer(name)); // Check buffer if (check_null_buffers && buffer == nullptr) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " buffer size is null")); // Check validity buffer offset if (check_null_buffers && validity_vector.buffer() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer is null")); // Check validity buffer size if (check_null_buffers && validity_vector.buffer_size() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer size is null")); // Must be an attribute if (!array_schema_->is_attr(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Buffer name '") + name + "' is not an attribute")); // Must be fixed-size if (array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute '") + name + "' is var-sized")); // Must be nullable if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute '") + name + "' is not nullable")); // Error if setting a new attribute/dimension after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute '") + name + "' after initialization")); // Set attribute buffer buffers_[name].set_data_buffer(buffer, buffer_size); buffers_[name].set_validity_buffer(std::move(validity_vector)); return Status::Ok(); } Status Query::set_buffer( const std::string& name, uint64_t* const buffer_off, uint64_t* const buffer_off_size, void* const buffer_val, uint64_t* const buffer_val_size, ValidityVector&& validity_vector, const bool check_null_buffers) { // Check buffer if (check_null_buffers && buffer_val == nullptr) if (type_ != QueryType::WRITE || *buffer_val_size != 0) return logger_->status( Status_QueryError("Cannot set buffer; " + name + " buffer is null")); // Check buffer size if (check_null_buffers && buffer_val_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " buffer size is null")); // Check buffer offset if (check_null_buffers && buffer_off == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " offset buffer is null")); // Check buffer offset size if (check_null_buffers && buffer_off_size == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " offset buffer size is null")); ; // Check validity buffer offset if (check_null_buffers && validity_vector.buffer() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer is null")); // Check validity buffer size if (check_null_buffers && validity_vector.buffer_size() == nullptr) return logger_->status(Status_QueryError( "Cannot set buffer; " + name + " validity buffer size is null")); // Must be an attribute if (!array_schema_->is_attr(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Buffer name '") + name + "' is not an attribute")); // Must be var-size if (!array_schema_->var_size(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute '") + name + "' is fixed-sized")); // Must be nullable if (!array_schema_->is_nullable(name)) return logger_->status(Status_QueryError( std::string("Cannot set buffer; Input attribute '") + name + "' is not nullable")); // Error if setting a new attribute after initialization const bool exists = buffers_.find(name) != buffers_.end(); if (status_ != QueryStatus::UNINITIALIZED && !exists) return logger_->status(Status_QueryError( std::string("Cannot set buffer for new attribute '") + name + "' after initialization")); // Set attribute/dimension buffer buffers_[name].set_data_var_buffer(buffer_val, buffer_val_size); buffers_[name].set_offsets_buffer(buffer_off, buffer_off_size); buffers_[name].set_validity_buffer(std::move(validity_vector)); return Status::Ok(); } Status Query::set_est_result_size( std::unordered_map<std::string, Subarray::ResultSize>& est_result_size, std::unordered_map<std::string, Subarray::MemorySize>& max_mem_size) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot set estimated result size; Operation currently " "unsupported for write queries")); return subarray_.set_est_result_size(est_result_size, max_mem_size); } Status Query::set_layout_unsafe(Layout layout) { layout_ = layout; subarray_.set_layout(layout); return Status::Ok(); } Status Query::set_layout(Layout layout) { if (type_ == QueryType::READ && status_ != QueryStatus::UNINITIALIZED) return logger_->status( Status_QueryError("Cannot set layout after initialization")); if (layout == Layout::HILBERT) return logger_->status(Status_QueryError( "Cannot set layout; Hilbert order is not applicable to queries")); if (type_ == QueryType::WRITE && array_schema_->dense() && layout == Layout::UNORDERED) { return logger_->status(Status_QueryError( "Unordered writes are only possible for sparse arrays")); } layout_ = layout; subarray_.set_layout(layout); return Status::Ok(); } Status Query::set_condition(const QueryCondition& condition) { if (type_ == QueryType::WRITE) return logger_->status(Status_QueryError( "Cannot set query condition; Operation only applicable " "to read queries")); condition_ = condition; return Status::Ok(); } void Query::set_status(QueryStatus status) { status_ = status; } Status Query::set_subarray(const void* subarray) { if (!array_schema_->domain()->all_dims_same_type()) return logger_->status( Status_QueryError("Cannot set subarray; Function not applicable to " "heterogeneous domains")); if (!array_schema_->domain()->all_dims_fixed()) return logger_->status( Status_QueryError("Cannot set subarray; Function not applicable to " "domains with variable-sized dimensions")); // Prepare a subarray object Subarray sub(array_, layout_, stats_, logger_); if (subarray != nullptr) { auto dim_num = array_schema_->dim_num(); auto s_ptr = (const unsigned char*)subarray; uint64_t offset = 0; bool err_on_range_oob = true; if (type_ == QueryType::READ) { // Get read_range_oob config setting bool found = false; std::string read_range_oob_str = config()->get("sm.read_range_oob", &found); assert(found); if (read_range_oob_str != "error" && read_range_oob_str != "warn") return logger_->status(Status_QueryError( "Invalid value " + read_range_oob_str + " for sm.read_range_obb. Acceptable values are 'error' or " "'warn'.")); err_on_range_oob = read_range_oob_str == "error"; } for (unsigned d = 0; d < dim_num; ++d) { auto r_size = 2 * array_schema_->dimension(d)->coord_size(); Range range(&s_ptr[offset], r_size); RETURN_NOT_OK(sub.add_range(d, std::move(range), err_on_range_oob)); offset += r_size; } } if (type_ == QueryType::WRITE) { // Not applicable to sparse arrays if (!array_schema_->dense()) return logger_->status(Status_WriterError( "Setting a subarray is not supported in sparse writes")); // Subarray must be unary for dense writes if (sub.range_num() != 1) return logger_->status( Status_WriterError("Cannot set subarray; Multi-range dense writes " "are not supported")); if (strategy_ != nullptr) strategy_->reset(); } subarray_ = sub; status_ = QueryStatus::UNINITIALIZED; return Status::Ok(); } const Subarray* Query::subarray() const { return &subarray_; } Status Query::set_subarray_unsafe(const Subarray& subarray) { subarray_ = subarray; return Status::Ok(); } Status Query::set_subarray(const tiledb::sm::Subarray& subarray) { auto query_status = status(); if (query_status != tiledb::sm::QueryStatus::UNINITIALIZED && query_status != tiledb::sm::QueryStatus::COMPLETED) { // Can be in this initialized state when query has been de-serialized // server-side and are trying to perform local submit. // Don't change anything and return indication of success. return Status::Ok(); } // Set subarray if (!subarray.is_set()) // Nothing useful to set here, will leave query with its current // settings and consider successful. return Status::Ok(); auto prev_layout = subarray_.layout(); subarray_ = subarray; subarray_.set_layout(prev_layout); status_ = QueryStatus::UNINITIALIZED; return Status::Ok(); } Status Query::set_subarray_unsafe(const NDRange& subarray) { // Prepare a subarray object Subarray sub(array_, layout_, stats_, logger_); if (!subarray.empty()) { auto dim_num = array_schema_->dim_num(); for (unsigned d = 0; d < dim_num; ++d) RETURN_NOT_OK(sub.add_range_unsafe(d, subarray[d])); } assert(layout_ == sub.layout()); subarray_ = sub; status_ = QueryStatus::UNINITIALIZED; return Status::Ok(); } Status Query::check_buffers_correctness() { // Iterate through each attribute for (auto& attr : buffer_names()) { if (array_schema_->var_size(attr)) { // Check for data buffer under buffer_var and offsets buffer under buffer if (type_ == QueryType::READ) { if (buffer(attr).buffer_var_ == nullptr) { return logger_->status(Status_QueryError( std::string("Var-Sized input attribute/dimension '") + attr + "' is not set correctly. \nVar size buffer is not set.")); } } else { if (buffer(attr).buffer_var_ == nullptr && *buffer(attr).buffer_var_size_ != 0) { return logger_->status(Status_QueryError( std::string("Var-Sized input attribute/dimension '") + attr + "' is not set correctly. \nVar size buffer is not set and buffer " "size if not 0.")); } } if (buffer(attr).buffer_ == nullptr) { return logger_->status(Status_QueryError( std::string("Var-Sized input attribute/dimension '") + attr + "' is not set correctly. \nOffsets buffer is not set.")); } } else { // Fixed sized if (buffer(attr).buffer_ == nullptr) { return logger_->status(Status_QueryError( std::string("Fix-Sized input attribute/dimension '") + attr + "' is not set correctly. \nData buffer is not set.")); } } if (array_schema_->is_nullable(attr)) { bool exists_validity = buffer(attr).validity_vector_.buffer() != nullptr; if (!exists_validity) { return logger_->status(Status_QueryError( std::string("Nullable input attribute/dimension '") + attr + "' is not set correctly \nValidity buffer is not set")); } } } return Status::Ok(); } Status Query::submit() { // Do not resubmit completed reads. if (type_ == QueryType::READ && status_ == QueryStatus::COMPLETED) { return Status::Ok(); } // Check attribute/dimensions buffers completeness before query submits RETURN_NOT_OK(check_buffers_correctness()); if (array_->is_remote()) { auto rest_client = storage_manager_->rest_client(); if (rest_client == nullptr) return logger_->status(Status_QueryError( "Error in query submission; remote array with no rest client.")); if (status_ == QueryStatus::UNINITIALIZED) { RETURN_NOT_OK(create_strategy()); RETURN_NOT_OK(strategy_->init()); } return rest_client->submit_query_to_rest(array_->array_uri(), this); } RETURN_NOT_OK(init()); return storage_manager_->query_submit(this); } Status Query::submit_async( std::function<void(void*)> callback, void* callback_data) { // Do not resubmit completed reads. if (type_ == QueryType::READ && status_ == QueryStatus::COMPLETED) { callback(callback_data); return Status::Ok(); } RETURN_NOT_OK(init()); if (array_->is_remote()) return logger_->status( Status_QueryError("Error in async query submission; async queries not " "supported for remote arrays.")); callback_ = callback; callback_data_ = callback_data; return storage_manager_->query_submit_async(this); } QueryStatus Query::status() const { return status_; } QueryStatusDetailsReason Query::status_incomplete_reason() const { if (strategy_ != nullptr) return strategy_->status_incomplete_reason(); return QueryStatusDetailsReason::REASON_NONE; } QueryType Query::type() const { return type_; } const Config* Query::config() const { return &config_; } stats::Stats* Query::stats() const { return stats_; } tdb_shared_ptr<Buffer> Query::rest_scratch() const { return rest_scratch_; } bool Query::use_refactored_dense_reader() { bool use_refactored_readers = false; bool found = false; // First check for legacy option config_.get<bool>( "sm.use_refactored_readers", &use_refactored_readers, &found); // If the legacy/deprecated option is set use it over the new parameters // This facilitates backwards compatibility if (found) { logger_->warn( "sm.use_refactored_readers config option is deprecated.\nPlease use " "'sm.query.dense.reader' with value of 'refactored' or 'legacy'"); return use_refactored_readers; } const std::string& val = config_.get("sm.query.dense.reader", &found); assert(found); return val == "refactored"; } bool Query::use_refactored_sparse_global_order_reader() { bool use_refactored_readers = false; bool found = false; // First check for legacy option config_.get<bool>( "sm.use_refactored_readers", &use_refactored_readers, &found); // If the legacy/deprecated option is set use it over the new parameters // This facilitates backwards compatibility if (found) { logger_->warn( "sm.use_refactored_readers config option is deprecated.\nPlease use " "'sm.query.sparse_global_order.reader' with value of 'refactored' or " "'legacy'"); return use_refactored_readers; } const std::string& val = config_.get("sm.query.sparse_global_order.reader", &found); assert(found); return val == "refactored"; } bool Query::use_refactored_sparse_unordered_with_dups_reader() { bool use_refactored_readers = false; bool found = false; // First check for legacy option config_.get<bool>( "sm.use_refactored_readers", &use_refactored_readers, &found); // If the legacy/deprecated option is set use it over the new parameters // This facilitates backwards compatibility if (found) { logger_->warn( "sm.use_refactored_readers config option is deprecated.\nPlease use " "'sm.query.sparse_unordered_with_dups.reader' with value of " "'refactored' or 'legacy'"); return use_refactored_readers; } const std::string& val = config_.get("sm.query.sparse_unordered_with_dups.reader", &found); assert(found); return val == "refactored"; } tuple<Status, optional<bool>> Query::non_overlapping_ranges() { return subarray_.non_overlapping_ranges(storage_manager_->compute_tp()); } /* ****************************** */ /* PRIVATE METHODS */ /* ****************************** */ } // namespace sm } // namespace tiledb
TileDB-Inc/TileDB
tiledb/sm/query/query.cc
C++
mit
69,785
class CreateProductMaterials < ActiveRecord::Migration[5.0] def change create_table :product_materials do |t| t.belongs_to :product, index: true t.string :name t.string :material t.string :description t.timestamps end end end
Klaital/abandonedforge.com
db/migrate/20160920213323_create_product_materials.rb
Ruby
mit
269
'use strict' var test = require('tap').test var strip = require('./') test('stripFalsy', function(t) { t.plan(5) t.deepEqual(strip(null), {}) t.deepEqual(strip('test'), {}) t.deepEqual(strip(13), {}) t.deepEqual(strip(), {}) var input = { a: false , b: 0 , c: null , d: undefined , e: '' , f: 'biscuits' , g: '0' } var exp = { f: 'biscuits' , g: '0' } t.deepEqual(strip(input), exp) })
helpdotcom/strip-falsy
test.js
JavaScript
mit
433
<?php /** * [WeEngine System] Copyright (c) 2014 WE7.CC * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details. */ defined('IN_IA') or exit('Access Denied'); load()->func('file'); load()->model('article'); load()->model('account'); $dos = array('display', 'post', 'del'); $do = in_array($do, $dos) ? $do : 'display'; permission_check_account_user('platform_site'); $_W['page']['title'] = '文章管理 - 微官网'; $category = pdo_fetchall("SELECT id,parentid,name FROM ".tablename('site_category')." WHERE uniacid = '{$_W['uniacid']}' ORDER BY parentid ASC, displayorder ASC, id ASC ", array(), 'id'); $parent = array(); $children = array(); if (!empty($category)) { foreach ($category as $cid => $cate) { if (!empty($cate['parentid'])) { $children[$cate['parentid']][] = $cate; } else { $parent[$cate['id']] = $cate; } } } if ($do == 'display') { $pindex = max(1, intval($_GPC['page'])); $psize = 20; $condition = ''; $params = array(); if (!empty($_GPC['keyword'])) { $condition .= " AND `title` LIKE :keyword"; $params[':keyword'] = "%{$_GPC['keyword']}%"; } if (!empty($_GPC['category']['childid'])) { $cid = intval($_GPC['category']['childid']); $condition .= " AND ccate = '{$cid}'"; } elseif (!empty($_GPC['category']['parentid'])) { $cid = intval($_GPC['category']['parentid']); $condition .= " AND pcate = '{$cid}'"; } $list = pdo_fetchall("SELECT * FROM ".tablename('site_article')." WHERE uniacid = '{$_W['uniacid']}' $condition ORDER BY displayorder DESC, edittime DESC, id DESC LIMIT ".($pindex - 1) * $psize.','.$psize, $params); $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('site_article') . " WHERE uniacid = '{$_W['uniacid']}'".$condition, $params); $pager = pagination($total, $pindex, $psize); $article_ids = array(); if (!empty($list)) { foreach ($list as $item) { $article_ids[] = $item['id']; } } $article_comment = table('sitearticlecomment')->srticleCommentUnread($article_ids); $setting = uni_setting($_W['uniacid']); template('site/article-display'); } elseif ($do == 'post') { $id = intval($_GPC['id']); $template = uni_templates(); $pcate = intval($_GPC['pcate']); $ccate = intval($_GPC['ccate']); if (!empty($id)) { $item = pdo_fetch("SELECT * FROM ".tablename('site_article')." WHERE id = :id" , array(':id' => $id)); $item['type'] = explode(',', $item['type']); $pcate = $item['pcate']; $ccate = $item['ccate']; if (empty($item)) { itoast('抱歉,文章不存在或是已经删除!', '', 'error'); } $key = pdo_fetchall('SELECT content FROM ' . tablename('rule_keyword') . ' WHERE rid = :rid AND uniacid = :uniacid', array(':rid' => $item['rid'], ':uniacid' => $_W['uniacid'])); if (!empty($key)) { $keywords = array(); foreach ($key as $row) { $keywords[] = $row['content']; } $keywords = implode(',', array_values($keywords)); } $item['credit'] = iunserializer($item['credit']) ? iunserializer($item['credit']) : array(); if (!empty($item['credit']['limit'])) { $credit_num = pdo_fetchcolumn('SELECT SUM(credit_value) FROM ' . tablename('mc_handsel') . ' WHERE uniacid = :uniacid AND module = :module AND sign = :sign', array(':uniacid' => $_W['uniacid'], ':module' => 'article', ':sign' => md5(iserializer(array('id' => $id))))); if (is_null($credit_num)) { $credit_num = 0; } $credit_yu = (($item['credit']['limit'] - $credit_num) < 0) ? 0 : $item['credit']['limit'] - $credit_num; } } else { $item['credit'] = array(); $keywords = ''; } if (checksubmit('submit')) { if (empty($_GPC['title'])) { itoast('标题不能为空,请输入标题!', '', ''); } $sensitive_title = detect_sensitive_word($_GPC['title']); if (!empty($sensitive_title)) { itoast('不能使用敏感词:' . $sensitive_title, '', ''); } $sensitive_content = detect_sensitive_word($_GPC['content']); if (!empty($sensitive_content)) { itoast('不能使用敏感词:' . $sensitive_content, '', ''); } $data = array( 'uniacid' => $_W['uniacid'], 'iscommend' => intval($_GPC['option']['commend']), 'ishot' => intval($_GPC['option']['hot']), 'pcate' => intval($_GPC['category']['parentid']), 'ccate' => intval($_GPC['category']['childid']), 'template' => addslashes($_GPC['template']), 'title' => addslashes($_GPC['title']), 'description' => addslashes($_GPC['description']), 'content' => safe_gpc_html(htmlspecialchars_decode($_GPC['content'], ENT_QUOTES)), 'incontent' => intval($_GPC['incontent']), 'source' => addslashes($_GPC['source']), 'author' => addslashes($_GPC['author']), 'displayorder' => intval($_GPC['displayorder']), 'linkurl' => addslashes($_GPC['linkurl']), 'createtime' => TIMESTAMP, 'edittime' => TIMESTAMP, 'click' => intval($_GPC['click']) ); if (!empty($_GPC['thumb'])) { if (file_is_image($_GPC['thumb'])) { $data['thumb'] = $_GPC['thumb']; } } elseif (!empty($_GPC['autolitpic'])) { $match = array(); preg_match('/&lt;img.*?src=&quot;?(.+\.(jpg|jpeg|gif|bmp|png))&quot;/', $_GPC['content'], $match); if (!empty($match[1])) { $url = $match[1]; $file = file_remote_attach_fetch($url); if (!is_error($file)) { $data['thumb'] = $file; file_remote_upload($file); } } } else { $data['thumb'] = ''; } $keyword = str_replace(',', ',', trim($_GPC['keyword'])); $keyword = explode(',', $keyword); if (!empty($keyword)) { $rule['uniacid'] = $_W['uniacid']; $rule['name'] = '文章:' . $_GPC['title'] . ' 触发规则'; $rule['module'] = 'news'; $rule['status'] = 1; $keywords = array(); foreach ($keyword as $key) { $key = trim($key); if (empty($key)) continue; $keywords[] = array( 'uniacid' => $_W['uniacid'], 'module' => 'news', 'content' => $key, 'status' => 1, 'type' => 1, 'displayorder' => 1, ); } $reply['title'] = $_GPC['title']; $reply['description'] = $_GPC['description']; $reply['thumb'] = $data['thumb']; $reply['url'] = murl('site/site/detail', array('id' => $id)); } if (!empty($_GPC['credit']['status'])) { $credit['status'] = intval($_GPC['credit']['status']); $credit['limit'] = intval($_GPC['credit']['limit']) ? intval($_GPC['credit']['limit']) : itoast('请设置积分上限', '', ''); $credit['share'] = intval($_GPC['credit']['share']) ? intval($_GPC['credit']['share']) : itoast('请设置分享时赠送积分多少', '', ''); $credit['click'] = intval($_GPC['credit']['click']) ? intval($_GPC['credit']['click']) : itoast('请设置阅读时赠送积分多少', '', ''); $data['credit'] = iserializer($credit); } else { $data['credit'] = iserializer(array('status' => 0, 'limit' => 0, 'share' => 0, 'click' => 0)); } if (empty($id)) { unset($data['edittime']); if (!empty($keywords)) { pdo_insert('rule', $rule); $rid = pdo_insertid(); foreach ($keywords as $li) { $li['rid'] = $rid; pdo_insert('rule_keyword', $li); } $reply['rid'] = $rid; pdo_insert('news_reply', $reply); $data['rid'] = $rid; } pdo_insert('site_article', $data); $aid = pdo_insertid(); pdo_update('news_reply', array('url' => murl('site/site/detail', array('id' => $aid))), array('rid' => $rid)); } else { unset($data['createtime']); pdo_delete('rule', array('id' => $item['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('rule_keyword', array('rid' => $item['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('news_reply', array('rid' => $item['rid'])); if (!empty($keywords)) { pdo_insert('rule', $rule); $rid = pdo_insertid(); foreach ($keywords as $li) { $li['rid'] = $rid; pdo_insert('rule_keyword', $li); } $reply['rid'] = $rid; pdo_insert('news_reply', $reply); $data['rid'] = $rid; } else { $data['rid'] = 0; $data['kid'] = 0; } pdo_update('site_article', $data, array('id' => $id)); } itoast('文章更新成功!', url('site/article/display'), 'success'); } else { template('site/article-post'); } } elseif($do == 'del') { if (checksubmit('submit')) { foreach ($_GPC['rid'] as $key => $id) { $id = intval($id); $row = pdo_get('site_article', array('id' => $id, 'uniacid' => $_W['uniacid'])); if (empty($row)) { itoast('抱歉,文章不存在或是已经被删除!', '', ''); } if (!empty($row['rid'])) { pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('news_reply', array('rid' => $row['rid'])); } pdo_delete('site_article', array('id' => $id, 'uniacid'=>$_W['uniacid'])); } itoast('批量删除成功!', referer(), 'success'); } else { $id = intval($_GPC['id']); $row = pdo_fetch("SELECT id,rid,kid,thumb FROM ".tablename('site_article')." WHERE id = :id", array(':id' => $id)); if (empty($row)) { itoast('抱歉,文章不存在或是已经被删除!', '', ''); } if (!empty($row['rid'])) { pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid'])); pdo_delete('news_reply', array('rid' => $row['rid'])); } if (pdo_delete('site_article', array('id' => $id,'uniacid'=>$_W['uniacid']))){ itoast('删除成功!', referer(), 'success'); } else { itoast('删除失败!', referer(), 'error'); } } }
justzheng/test1
web/source/site/article.ctrl.php
PHP
mit
9,565
<?php namespace Kr\OAuthClient\Credentials; class Client extends AbstractCredentials { protected $clientId, $clientSecret, $redirectUri; /** * Client constructor. * @param string $clientId * @param string $clientSecret * @param string $redirectUri */ public function __construct($clientId, $clientSecret, $redirectUri) { $this->clientId = $clientId; $this->clientSecret = $clientSecret; $this->redirectUri = $redirectUri; } /** * @inheritdoc */ public function getCredentials() { return [ "client_id" => $this->getClientId(), "client_secret" => $this->getClientSecret(), "redirect_uri" => $this->getRedirectUri(), ]; } /** * @return mixed */ public function getClientId() { return $this->clientId; } /** * @return mixed */ public function getClientSecret() { return $this->clientSecret; } /** * @return mixed */ public function getRedirectUri() { return $this->redirectUri; } /** * @inheritdoc */ public static function getType() { return "client_credentials"; } }
koenreiniers/oauth-client
src/Credentials/Client.php
PHP
mit
1,264
$(function () { $('.imageUploadMultiple').each(function (index, item) { var $item = $(item); var $group = $item.closest('.form-group'); var $innerGroup = $item.find('.form-group'); var $errors = $item.find('.errors'); var $input = $item.find('.imageValue'); var flow = new Flow({ target: $item.data('target'), testChunks: false, chunkSize: 1024 * 1024 * 1024, query: { _token: $item.data('token') } }); var updateValue = function () { var values = []; $item.find('img[data-value]').each(function () { values.push($(this).data('value')); }); $input.val(values.join(',')); }; flow.assignBrowse($item.find('.imageBrowse')); flow.on('filesSubmitted', function (file) { flow.upload(); }); flow.on('fileSuccess', function (file, message) { flow.removeFile(file); $errors.html(''); $group.removeClass('has-error'); var result = $.parseJSON(message); $innerGroup.append('<div class="col-xs-6 col-md-3 imageThumbnail"><div class="thumbnail">' + '<img data-value="' + result.value + '" src="' + result.url + '" />' + '<a href="#" class="imageRemove">Remove</a></div></div>'); updateValue(); }); flow.on('fileError', function (file, message) { flow.removeFile(file); var response = $.parseJSON(message); var errors = ''; $.each(response, function (index, error) { errors += '<p class="help-block">' + error + '</p>' }); $errors.html(errors); $group.addClass('has-error'); }); $item.on('click', '.imageRemove', function (e) { e.preventDefault(); $(this).closest('.imageThumbnail').remove(); updateValue(); }); $innerGroup.sortable({ onUpdate: function () { updateValue(); } }); }); });
Asvae/SleepingOwlAdmin
resources/assets/js/form/image/initMultiple.js
JavaScript
mit
2,178
vk_wiki_manager ===============
toydestroyer/vk_wiki_manager
README.md
Markdown
mit
32
#!/bin/bash f="$1" d="$2" CURRENT_DIR=$( pushd $(dirname $0) >/dev/null; pwd; popd >/dev/null ) if [ ! -d $d ]; then echo "$d is not found" exit 2 fi F="$d/$f" if [ -f "$F" ]; then s1=`wc -c "$f" | cut -d ' ' -f 1` s2=`wc -c "$F" | cut -d ' ' -f 1` if [ $s1 -eq $s2 ]; then cksum1=`md5sum -b "$f" | cut -d ' ' -f 1` cksum2=`md5sum -b "$F" | cut -d ' ' -f 1` if [ "$cksum1" == "$cksum2" ]; then rm -v "$f" else echo "\"$F\" exists, has the same size, but different md5sum than \"$f\"" fi else echo "\"$F\" exists and has differrent size than \"$f\"" echo "\"$F\" - $s2" echo "\"$f\" - $s1" fi else echo "\"$F\" does not exist" fi
pavel-voinov/ghost-tools
check_file.sh
Shell
mit
693
module Schema include Virtus.module(:constructor => false, :mass_assignment => false) def initialize set_default_attributes end def attributes attribute_set.get(self) end def to_h attributes end end
obsidian-btc/schema
lib/schema/schema.rb
Ruby
mit
228
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for DSA-3663-1 # # Security announcement date: 2016-09-09 00:00:00 UTC # Script generation date: 2017-01-01 21:08:13 UTC # # Operating System: Debian 8 (Jessie) # Architecture: i386 # # Vulnerable packages fix on version: # - xen:4.4.1-9+deb8u7 # - libxen-4.4:4.4.1-9+deb8u7 # - libxenstore3.0:4.4.1-9+deb8u7 # - libxen-dev:4.4.1-9+deb8u7 # - xenstore-utils:4.4.1-9+deb8u7 # - xen-utils-common:4.4.1-9+deb8u7 # - xen-utils-4.4:4.4.1-9+deb8u7 # - xen-hypervisor-4.4-amd64:4.4.1-9+deb8u7 # - xen-system-amd64:4.4.1-9+deb8u7 # # Last versions recommanded by security team: # - xen:4.4.1-9+deb8u7 # - libxen-4.4:4.4.1-9+deb8u7 # - libxenstore3.0:4.4.1-9+deb8u7 # - libxen-dev:4.4.1-9+deb8u7 # - xenstore-utils:4.4.1-9+deb8u7 # - xen-utils-common:4.4.1-9+deb8u7 # - xen-utils-4.4:4.4.1-9+deb8u7 # - xen-hypervisor-4.4-amd64:4.4.1-9+deb8u7 # - xen-system-amd64:4.4.1-9+deb8u7 # # CVE List: # - CVE-2016-7092 # - CVE-2016-7094 # - CVE-2016-7154 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo apt-get install --only-upgrade xen=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade libxen-4.4=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade libxenstore3.0=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade libxen-dev=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade xenstore-utils=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade xen-utils-common=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade xen-utils-4.4=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade xen-hypervisor-4.4-amd64=4.4.1-9+deb8u7 -y sudo apt-get install --only-upgrade xen-system-amd64=4.4.1-9+deb8u7 -y
Cyberwatch/cbw-security-fixes
Debian_8_(Jessie)/i386/2016/DSA-3663-1.sh
Shell
mit
1,783
/** * k-d Tree JavaScript - V 1.01 * * https://github.com/ubilabs/kd-tree-javascript * * @author Mircea Pricop <[email protected]>, 2012 * @author Martin Kleppe <[email protected]>, 2012 * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License <http://www.opensource.org/licenses/mit-license.php> */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports === 'object') { factory(exports); } else { factory((root.commonJsStrict = {})); } }(this, function (exports) { function Node(obj, dimension, parent) { this.obj = obj; this.left = null; this.right = null; this.parent = parent; this.dimension = dimension; } function kdTree(points, metric, dimensions) { var self = this; function buildTree(points, depth, parent) { var dim = depth % dimensions.length, median, node; if (points.length === 0) { return null; } if (points.length === 1) { return new Node(points[0], dim, parent); } points.sort(function (a, b) { return a[dimensions[dim]] - b[dimensions[dim]]; }); median = Math.floor(points.length / 2); node = new Node(points[median], dim, parent); node.left = buildTree(points.slice(0, median), depth + 1, node); node.right = buildTree(points.slice(median + 1), depth + 1, node); return node; } // Reloads a serialied tree function loadTree (data) { // Just need to restore the `parent` parameter self.root = data; function restoreParent (root) { if (root.left) { root.left.parent = root; restoreParent(root.left); } if (root.right) { root.right.parent = root; restoreParent(root.right); } } restoreParent(self.root); } // If points is not an array, assume we're loading a pre-built tree if (!Array.isArray(points)) loadTree(points, metric, dimensions); else this.root = buildTree(points, 0, null); // Convert to a JSON serializable structure; this just requires removing // the `parent` property this.toJSON = function (src) { if (!src) src = this.root; var dest = new Node(src.obj, src.dimension, null); if (src.left) dest.left = self.toJSON(src.left); if (src.right) dest.right = self.toJSON(src.right); return dest; }; this.insert = function (point) { function innerSearch(node, parent) { if (node === null) { return parent; } var dimension = dimensions[node.dimension]; if (point[dimension] < node.obj[dimension]) { return innerSearch(node.left, node); } else { return innerSearch(node.right, node); } } var insertPosition = innerSearch(this.root, null), newNode, dimension; if (insertPosition === null) { this.root = new Node(point, 0, null); return; } newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); dimension = dimensions[insertPosition.dimension]; if (point[dimension] < insertPosition.obj[dimension]) { insertPosition.left = newNode; } else { insertPosition.right = newNode; } }; this.remove = function (point) { var node; function nodeSearch(node) { if (node === null) { return null; } if (node.obj === point) { return node; } var dimension = dimensions[node.dimension]; if (point[dimension] < node.obj[dimension]) { return nodeSearch(node.left, node); } else { return nodeSearch(node.right, node); } } function removeNode(node) { var nextNode, nextObj, pDimension; function findMin(node, dim) { var dimension, own, left, right, min; if (node === null) { return null; } dimension = dimensions[dim]; if (node.dimension === dim) { if (node.left !== null) { return findMin(node.left, dim); } return node; } own = node.obj[dimension]; left = findMin(node.left, dim); right = findMin(node.right, dim); min = node; if (left !== null && left.obj[dimension] < own) { min = left; } if (right !== null && right.obj[dimension] < min.obj[dimension]) { min = right; } return min; } if (node.left === null && node.right === null) { if (node.parent === null) { self.root = null; return; } pDimension = dimensions[node.parent.dimension]; if (node.obj[pDimension] < node.parent.obj[pDimension]) { node.parent.left = null; } else { node.parent.right = null; } return; } // If the right subtree is not empty, swap with the minimum element on the // node's dimension. If it is empty, we swap the left and right subtrees and // do the same. if (node.right !== null) { nextNode = findMin(node.right, node.dimension); nextObj = nextNode.obj; removeNode(nextNode); node.obj = nextObj; } else { nextNode = findMin(node.left, node.dimension); nextObj = nextNode.obj; removeNode(nextNode); node.right = node.left; node.left = null; node.obj = nextObj; } } node = nodeSearch(self.root); if (node === null) { return; } removeNode(node); }; this.nearest = function (point, maxNodes, maxDistance) { var i, result, bestNodes; bestNodes = new BinaryHeap( function (e) { return -e[1]; } ); function nearestSearch(node) { var bestChild, dimension = dimensions[node.dimension], ownDistance = metric(point, node.obj), linearPoint = {}, linearDistance, otherChild, i; function saveNode(node, distance) { bestNodes.push([node, distance]); if (bestNodes.size() > maxNodes) { bestNodes.pop(); } } for (i = 0; i < dimensions.length; i += 1) { if (i === node.dimension) { linearPoint[dimensions[i]] = point[dimensions[i]]; } else { linearPoint[dimensions[i]] = node.obj[dimensions[i]]; } } linearDistance = metric(linearPoint, node.obj); if (node.right === null && node.left === null) { if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { saveNode(node, ownDistance); } return; } if (node.right === null) { bestChild = node.left; } else if (node.left === null) { bestChild = node.right; } else { if (point[dimension] < node.obj[dimension]) { bestChild = node.left; } else { bestChild = node.right; } } nearestSearch(bestChild); if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { saveNode(node, ownDistance); } if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) { if (bestChild === node.left) { otherChild = node.right; } else { otherChild = node.left; } if (otherChild !== null) { nearestSearch(otherChild); } } } if (maxDistance) { for (i = 0; i < maxNodes; i += 1) { bestNodes.push([null, maxDistance]); } } if(self.root) nearestSearch(self.root); result = []; for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) { if (bestNodes.content[i][0]) { result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]); } } return result; }; this.balanceFactor = function () { function height(node) { if (node === null) { return 0; } return Math.max(height(node.left), height(node.right)) + 1; } function count(node) { if (node === null) { return 0; } return count(node.left) + count(node.right) + 1; } return height(self.root) / (Math.log(count(self.root)) / Math.log(2)); }; } // Binary heap implementation from: // http://eloquentjavascript.net/appendix2.html function BinaryHeap(scoreFunction){ this.content = []; this.scoreFunction = scoreFunction; } BinaryHeap.prototype = { push: function(element) { // Add the new element to the end of the array. this.content.push(element); // Allow it to bubble up. this.bubbleUp(this.content.length - 1); }, pop: function() { // Store the first element so we can return it later. var result = this.content[0]; // Get the element at the end of the array. var end = this.content.pop(); // If there are any elements left, put the end element at the // start, and let it sink down. if (this.content.length > 0) { this.content[0] = end; this.sinkDown(0); } return result; }, peek: function() { return this.content[0]; }, remove: function(node) { var len = this.content.length; // To remove a value, we must search through the array to find // it. for (var i = 0; i < len; i++) { if (this.content[i] == node) { // When it is found, the process seen in 'pop' is repeated // to fill up the hole. var end = this.content.pop(); if (i != len - 1) { this.content[i] = end; if (this.scoreFunction(end) < this.scoreFunction(node)) this.bubbleUp(i); else this.sinkDown(i); } return; } } throw new Error("Node not found."); }, size: function() { return this.content.length; }, bubbleUp: function(n) { // Fetch the element that has to be moved. var element = this.content[n]; // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1, parent = this.content[parentN]; // Swap the elements if the parent is greater. if (this.scoreFunction(element) < this.scoreFunction(parent)) { this.content[parentN] = element; this.content[n] = parent; // Update 'n' to continue at the new position. n = parentN; } // Found a parent that is less, no need to move it further. else { break; } } }, sinkDown: function(n) { // Look up the target element and its score. var length = this.content.length, element = this.content[n], elemScore = this.scoreFunction(element); while(true) { // Compute the indices of the child elements. var child2N = (n + 1) * 2, child1N = child2N - 1; // This is used to store the new position of the element, // if any. var swap = null; // If the first child exists (is inside the array)... if (child1N < length) { // Look it up and compute its score. var child1 = this.content[child1N], child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap. if (child1Score < elemScore) swap = child1N; } // Do the same checks for the other child. if (child2N < length) { var child2 = this.content[child2N], child2Score = this.scoreFunction(child2); if (child2Score < (swap == null ? elemScore : child1Score)){ swap = child2N; } } // If the element needs to be moved, swap it, and continue. if (swap != null) { this.content[n] = this.content[swap]; this.content[swap] = element; n = swap; } // Otherwise, we are done. else { break; } } } }; this.kdTree = kdTree; exports.kdTree = kdTree; exports.BinaryHeap = BinaryHeap; }));
tsurantino/roadtrip
lib/kdTree.js
JavaScript
mit
13,331
// function that finds the sum of two parameters function findSum(firstnr, secondnr){ return firstnr + secondnr; } //function that finds the product of two parameters function findProduct(firstnr, secondnr){ return firstnr * secondnr; } /* threeOperation calls the operation parameter as a function so it's able to run and "do" different things depending on the global function it takes as a parameter when calling it*/ function threeOperation (x, operation){ /*put console.log here so it doesn't only returns the result but also prints it in the console first: to check if it gives the right answer when it's called*/ console.log(operation(3, x)); return operation(3, x); } //Call "threeOperation" with the values of "4" and "findSum" threeOperation(4, findSum); //Call "threeOperation" with the values of "5" and "findSum" threeOperation(5, findSum); //Call "threeOperation" with the values of "4" and "findProduct" threeOperation(4, findProduct); //Call "threeOperation" with the values of "5" and "findProduct" threeOperation(5, findProduct);
InekeScheffers/NYCDA-individual-assignments
09-29-2016-Anonymous-Functions-Practice/Anonymous Functions Practice.js
JavaScript
mit
1,060
// // LJRouterPath.h // LJControllerRouterExample // // Created by Jinxing Liao on 12/14/15. // Copyright © 2015 Jinxing Liao. All rights reserved. // #import <Foundation/Foundation.h> @interface LJRouterPath : NSObject @property (nonatomic, strong) NSString *schema; @property (nonatomic, strong) NSArray *components; @property (nonatomic, strong) NSDictionary *params; - (instancetype)initWithRouterURL:(NSString *)URL; @end
liaojinxing/LJURLRouter
LJURLRouter/LJRouterPath.h
C
mit
439
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Everyplay.XCodeEditor { public class XCConfigurationList : PBXObject { public XCConfigurationList(string guid, PBXDictionary dictionary) : base(guid, dictionary) { internalNewlines = true; } } }
uareurapid/balloonquest
Assets/Editor/Everyplay/XCodeEditor/XCConfigurationList.cs
C#
mit
305
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** * Public-Key Encrypted Session Key Packets (Tag 1)<br/> * <br/> * {@link http://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key * used to encrypt a message. Zero or more Public-Key Encrypted Session Key * packets and/or Symmetric-Key Encrypted Session Key packets may precede a * Symmetrically Encrypted Data Packet, which holds an encrypted message. The * message is encrypted with the session key, and the session key is itself * encrypted and stored in the Encrypted Session Key packet(s). The * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted * Session Key packet for each OpenPGP key to which the message is encrypted. * The recipient of the message finds a session key that is encrypted to their * public key, decrypts the session key, and then uses the session key to * decrypt the message. * @requires crypto * @requires enums * @requires type/s2k * @module packet/sym_encrypted_session_key */ var type_s2k = require('../type/s2k.js'), enums = require('../enums.js'), crypto = require('../crypto'); module.exports = SymEncryptedSessionKey; /** * @constructor */ function SymEncryptedSessionKey() { this.tag = enums.packet.symEncryptedSessionKey; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; this.encrypted = null; this.s2k = new type_s2k(); } /** * Parsing function for a symmetric encrypted session key packet (tag 3). * * @param {String} input Payload of a tag 1 packet * @param {Integer} position Position to start reading from the input string * @param {Integer} len * Length of the packet or the remaining length of * input at position * @return {module:packet/sym_encrypted_session_key} Object representation */ SymEncryptedSessionKey.prototype.read = function(bytes) { // A one-octet version number. The only currently defined version is 4. this.version = bytes.charCodeAt(0); // A one-octet number describing the symmetric algorithm used. var algo = enums.read(enums.symmetric, bytes.charCodeAt(1)); // A string-to-key (S2K) specifier, length as defined above. var s2klength = this.s2k.read(bytes.substr(2)); // Optionally, the encrypted session key itself, which is decrypted // with the string-to-key object. var done = s2klength + 2; if (done < bytes.length) { this.encrypted = bytes.substr(done); this.sessionKeyEncryptionAlgorithm = algo; } else this.sessionKeyAlgorithm = algo; }; SymEncryptedSessionKey.prototype.write = function() { var algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm; var bytes = String.fromCharCode(this.version) + String.fromCharCode(enums.write(enums.symmetric, algo)) + this.s2k.write(); if (this.encrypted !== null) bytes += this.encrypted; return bytes; }; /** * Decrypts the session key (only for public key encrypted session key * packets (tag 1) * * @return {String} The unencrypted session key */ SymEncryptedSessionKey.prototype.decrypt = function(passphrase) { var algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; var length = crypto.cipher[algo].keySize; var key = this.s2k.produce_key(passphrase, length); if (this.encrypted === null) { this.sessionKey = key; } else { var decrypted = crypto.cfb.decrypt( this.sessionKeyEncryptionAlgorithm, key, this.encrypted, true); this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0].keyCodeAt()); this.sessionKey = decrypted.substr(1); } }; SymEncryptedSessionKey.prototype.encrypt = function(passphrase) { var length = crypto.getKeyLength(this.sessionKeyEncryptionAlgorithm); var key = this.s2k.produce_key(passphrase, length); var private_key = String.fromCharCode( enums.write(enums.symmetric, this.sessionKeyAlgorithm)) + crypto.getRandomBytes( crypto.getKeyLength(this.sessionKeyAlgorithm)); this.encrypted = crypto.cfb.encrypt( crypto.getPrefixRandom(this.sessionKeyEncryptionAlgorithm), this.sessionKeyEncryptionAlgorithm, key, private_key, true); }; /** * Fix custom types after cloning */ SymEncryptedSessionKey.prototype.postCloneTypeFix = function() { this.s2k = type_s2k.fromClone(this.s2k); };
openilabs/crypto
node_modules/openpgp/src/packet/sym_encrypted_session_key.js
JavaScript
mit
5,248
""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': main()
eifuentes/kaggle_whats_cooking
train_word2vec_rf.py
Python
mit
1,909
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Configuration options for Invenio-Search. The documentation for the configuration is in docs/configuration.rst. """ # # ELASTIC configuration # SEARCH_CLIENT_CONFIG = None """Dictionary of options for the Elasticsearch client. The value of this variable is passed to :py:class:`elasticsearch.Elasticsearch` as keyword arguments and is used to configure the client. See the available keyword arguments in the two following classes: - :py:class:`elasticsearch.Elasticsearch` - :py:class:`elasticsearch.Transport` If you specify the key ``hosts`` in this dictionary, the configuration variable :py:class:`~invenio_search.config.SEARCH_ELASTIC_HOSTS` will have no effect. """ SEARCH_ELASTIC_HOSTS = None # default localhost """Elasticsearch hosts. By default, Invenio connects to ``localhost:9200``. The value of this variable is a list of dictionaries, where each dictionary represents a host. The available keys in each dictionary is determined by the connection class: - :py:class:`elasticsearch.connection.Urllib3HttpConnection` (default) - :py:class:`elasticsearch.connection.RequestsHttpConnection` You can change the connection class via the :py:class:`~invenio_search.config.SEARCH_CLIENT_CONFIG`. If you specified the ``hosts`` key in :py:class:`~invenio_search.config.SEARCH_CLIENT_CONFIG` then this configuration variable will have no effect. """ SEARCH_MAPPINGS = None # loads all mappings and creates aliases for them """List of aliases for which, their search mappings should be created. - If `None` all aliases (and their search mappings) defined through the ``invenio_search.mappings`` entry point in setup.py will be created. - Provide an empty list ``[]`` if no aliases (or their search mappings) should be created. For example if you don't want to create aliases and their mappings for `authors`: .. code-block:: python # in your `setup.py` you would specify: entry_points={ 'invenio_search.mappings': [ 'records = invenio_foo_bar.mappings', 'authors = invenio_foo_bar.mappings', ], } # and in your config.py SEARCH_MAPPINGS = ['records'] """ SEARCH_RESULTS_MIN_SCORE = None """If set, the `min_score` parameter is added to each search request body. The `min_score` parameter excludes results which have a `_score` less than the minimum specified in `min_score`. Note that the `max_score` varies depending on the number of results for a given search query and it is not absolute value. Therefore, setting `min_score` too high can lead to 0 results because it can be higher than any result's `_score`. Please refer to `Elasticsearch min_score documentation <https://www.elastic.co/guide/en/elasticsearch/reference/current/ search-request-min-score.html>`_ for more information. """ SEARCH_INDEX_PREFIX = '' """Any index, alias and templates will be prefixed with this string. Useful to host multiple instances of the app on the same Elasticsearch cluster, for example on one app you can set it to `dev-` and on the other to `prod-`, and each will create non-colliding indices prefixed with the corresponding string. Usage example: .. code-block:: python # in your config.py SEARCH_INDEX_PREFIX = 'prod-' For templates, ensure that the prefix `__SEARCH_INDEX_PREFIX__` is added to your index names. This pattern will be replaced by the prefix config value. Usage example in your template.json: .. code-block:: json { "index_patterns": ["__SEARCH_INDEX_PREFIX__myindex-name-*"] } """
inveniosoftware/invenio-search
invenio_search/config.py
Python
mit
3,755
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class SettingController * * @author The scaffold-interface created at 2016-08-25 01:07:35am * @link https://github.com/amranidev/scaffold-interface */ class Setting extends Model { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'avatars'; }
UnrulyNatives/helpers-for-laravel-projects
src/unstarter_models/Avatar.php
PHP
mit
408
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>DSJCL</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/modern-business.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="index.html">Home</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="about.html">Comments</a> </li> <li class="nav-item"> <a class="nav-link" href="services.html">Constitution</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.html">State and Nationals</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> More </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownPortfolio"> <a class="dropdown-item" href="portfolio-1-col.html">Announcements</a> <a class="dropdown-item" href="portfolio-2-col.html">Event Schedule</a> <a class="dropdown-item" href="portfolio-3-col.html">Officers</a> <a class="dropdown-item" href="portfolio-4-col.html">About JCL</a> <a class="dropdown-item" href="portfolio-item.html">Important Documents</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownBlog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> The Torch </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownBlog"> <a class="dropdown-item" href="blog-home-1.html">Edition 1</a> <a class="dropdown-item" href="blog-home-2.html">Edtion 2</a> <a class="dropdown-item" href="blog-post.html">Edition 3</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownBlog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dev </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownBlog"> <a class="dropdown-item" href="full-width.html">Full Width Page</a> <a class="dropdown-item" href="sidebar.html">Sidebar Page</a> <a class="dropdown-item" href="faq.html">FAQ</a> <a class="dropdown-item" href="404.html">404</a> </div> </li> </ul> </div> </div> </nav> <!-- Page Content --> <div class="container"> <!-- Page Heading/Breadcrumbs --> <h1 class="mt-4 mb-3">State and Nationals <small></small> </h1> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="index.html">Home</a> </li> <li class="breadcrumb-item active">State and Nationals</li> </ol> <!-- Image Header --> <img class="img-fluid rounded mb-4" src="http://placehold.it/1200x300" alt=""> <!-- Marketing Icons Section --> <div class="row"> <div class="col-lg-4 mb-4"> <div class="card h-100"> <h4 class="card-header">Card Title</h4> <div class="card-body"> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente esse necessitatibus neque.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Learn More</a> </div> </div> </div> <div class="col-lg-4 mb-4"> <div class="card h-100"> <h4 class="card-header">Card Title</h4> <div class="card-body"> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis ipsam eos, nam perspiciatis natus commodi similique totam consectetur praesentium molestiae atque exercitationem ut consequuntur, sed eveniet, magni nostrum sint fuga.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Learn More</a> </div> </div> </div> <div class="col-lg-4 mb-4"> <div class="card h-100"> <h4 class="card-header">Card Title</h4> <div class="card-body"> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente esse necessitatibus neque.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Learn More</a> </div> </div> </div> </div> <!-- /.row --> </div> <!-- /.container --> <!-- Footer --> <footer class="py-5 bg-dark"> <div class="container"> <p class="m-0 text-center text-white">Copyright &copy; All rights reserved Whitergirl279 2017</p> </div> <!-- /.container --> </footer> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/popper/popper.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> </body> </html>
DaviesSouthJCL/DaviesSouthJCL.github.io
contact.html
HTML
mit
6,256
package net.robobalasko.dfa.gui; import net.robobalasko.dfa.core.Automaton; import net.robobalasko.dfa.core.exceptions.NodeConnectionMissingException; import net.robobalasko.dfa.core.exceptions.StartNodeMissingException; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MainFrame extends JFrame { private final Automaton automaton; private JButton checkButton; public MainFrame(final Automaton automaton) throws HeadlessException { super("DFA Simulator"); this.automaton = automaton; setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JPanel containerPanel = new JPanel(); containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS)); containerPanel.setBorder(new EmptyBorder(20, 20, 20, 20)); setContentPane(containerPanel); CanvasPanel canvasPanel = new CanvasPanel(this, automaton); containerPanel.add(canvasPanel); JPanel checkInputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); containerPanel.add(checkInputPanel); final JTextField inputText = new JTextField(40); Document document = inputText.getDocument(); document.addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } @Override public void removeUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } @Override public void changedUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } }); checkInputPanel.add(inputText); checkButton = new JButton("Check"); checkButton.setEnabled(false); checkButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { JOptionPane.showMessageDialog(MainFrame.this, automaton.acceptsString(inputText.getText()) ? "Input accepted." : "Input rejected."); } catch (StartNodeMissingException ex) { JOptionPane.showMessageDialog(MainFrame.this, "Missing start node."); } catch (NodeConnectionMissingException ex) { JOptionPane.showMessageDialog(MainFrame.this, "Not a good string. Automat doesn't accept it."); } } }); checkInputPanel.add(checkButton); setResizable(false); setVisible(true); pack(); } }
robobalasko/DFA-Simulator
src/main/java/net/robobalasko/dfa/gui/MainFrame.java
Java
mit
3,007
--- types: - utility id: d5ee1b1e-0ffa-45cd-b3aa-bfecb9a93325 --- Converts all tabs in a string to a given number of spaces, `4` by default. This is a boring modifier to output examples of. Here's just a few examples on how the syntax looks. ``` {{ string | to_spaces }} {{ string | to_spaces:2 }} ```
JesseLeite/docs
content/collections/modifiers/to_spaces.md
Markdown
mit
305
from __future__ import unicode_literals from django.apps import AppConfig class RfhistoryConfig(AppConfig): name = 'RFHistory'
Omenia/RFHistory
ServerApp/apps.py
Python
mit
134
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64 minTime = pb0->GetBlockTime(); int64 maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64 time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64 timeDiff = maxTime - minTime; return (boost::int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); if (!pMiningKey) return false; return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); assert(pwalletMain != NULL); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
frontibit/riestercoin
src/rpcmining.cpp
C++
mit
21,117
<!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8"> <title>Interlude</title> </head> <link href="css/interlude.css" media="screen" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script> <script src="lib/interlude.js"></script> <script src="lib/CV_particles.js"></script> <style> #sample { position: absolute; left: 10%; top: 10%; width: 80%; height: 80%; background: yellow; } </style> <script> function start() { var o = {}; o.div = "sample"; o.centered = true; // var a = new Interlude.Loading(o); // var x = new Interlude.Forms(o); var p = {}; p.div = "sample"; var z = new Particles(p); }; $( document ).ready(function() { $("#sample").click(function(){ start(); }); }); </script> <body> <!-- Invisible comment --> <div id = "sample"></div> </body> </html>
Phalanstere/interlude
index.html
HTML
mit
1,138
#ifndef _PARSER_HPP #define _PARSER_HPP #include <cassert> #include <iostream> #include <vector> #include <string> #include <cstdlib> #include "toyobj.hpp" #include "lexer.hpp" #include "toy.hpp" #include "ast.hpp" class ParserContext { public: explicit ParserContext(LexerContext &lexer) : lexer_(lexer) { lexer_.fetchtok(); } AST *parse_ast(bool); private: Statement *parse_statement(); Statement *parse_while(); Statement *parse_if(); Statement *parse_return(); Statement *parse_def(); Expression *parse_expression(); Expression *parse_primary(); Expression *parse_binary_op_expression(Expression*, int); Expression *parse_paren_expression(); Expression *parse_number(); Expression *parse_string(); Expression *parse_word_expression(); AST *parse_block(); int get_prec(TokenType) const; inline const Token *curtok() { return lexer_.curtok(); } inline void eat_token(TokenType type) { if (type != curtok()->type()) { std::cout << "I was expecting " << Token::token_type_name(type) << " but got " << curtok()->name() << std::endl; exit(1); } lexer_.fetchtok(); } LexerContext &lexer_; DISALLOW_COPY_AND_ASSIGN(ParserContext); }; #endif
helgefmi/Toy
src/parser.hpp
C++
mit
1,288
require 'aws-sdk' require 'awspec/resource_reader' require 'awspec/helper/finder' module Awspec::Type class Base include Awspec::Helper::Finder include Awspec::BlackListForwardable attr_accessor :account def resource_via_client raise 'this method must be override!' end def to_s type = self.class.name.demodulize.underscore "#{type} '#{@display_name}'" end def inspect to_s end def self.tags_allowed define_method :has_tag? do |key, value| begin tags = resource_via_client.tags rescue NoMethodError tags = resource_via_client.tag_set end return false unless tags tags.any? { |t| t['key'] == key && t['value'] == value } end end def method_missing(name) name_str = name.to_s if name.class == Symbol describe = name_str.tr('-', '_').to_sym if !resource_via_client.nil? && resource_via_client.members.include?(describe) resource_via_client[describe] else super unless self.respond_to?(:resource) method_missing_via_black_list(name, delegate_to: resource) end end end end
AgarFu/awspec
lib/awspec/type/base.rb
Ruby
mit
1,180
## Next * Improved Spotlight support for favorites. - alloy ## 2.3.0 (2015.09.18) * Add support for Universal Links on iOS 9. - alloy * Add support for Web-to-Native Handoff. - alloy * Make CircleCI work again by adding the `build` action to the `test` task to ensure the simulator is running. - alloy * Remove `?foo=bar` parameter from Martsy calls - jorystiefel * Convert all web views to use WKWebView - orta * Re-installed all pods with current CocoaPods version, ensuring they’re installed from the new ‘externals’ cache. If running `pod install` changes checksums in `Podfile.lock` for you, then delete your `Pods` checkout and run `pod install` again. - alloy * NSUserActivity object creation to support Spotlight Search and Handoff - jorystiefel * Add Spotlight support for favorite artworks, artists, and genes. - alloy
Havi4/eigen
docs/BETA_CHANGELOG.md
Markdown
mit
838
// // EPTTimer.h // PodcastTimer // // Created by Eric Jones on 6/7/14. // Copyright (c) 2014 Effective Programming. All rights reserved. // #import <Foundation/Foundation.h> @protocol EPTTimerDelegate <NSObject> - (void)timerFired; @end @interface EPTTimer : NSObject @property (nonatomic) id<EPTTimerDelegate> delegate; - (void)scheduleTimer; - (void)stopTimer; @end
EffectiveProgramming/PodcastTimer-iPad
PodcastTimer/PodcastTimer/EPTTimer.h
C
mit
382
--- layout: page title: Floyd Aerospace Seminar date: 2016-05-24 author: Jonathan Jarvis tags: weekly links, java status: published summary: Etiam dictum facilisis massa, iaculis varius. banner: images/banner/wedding.jpg booking: startDate: 09/21/2019 endDate: 09/24/2019 ctyhocn: BTVMVHX groupCode: FAS published: true --- Mauris non sodales arcu. In sit amet eleifend diam. Donec pretium arcu eget nisi feugiat, eu auctor mauris rutrum. Ut aliquet ante a tellus placerat elementum tincidunt sed orci. Donec sollicitudin, nisi quis tempor vestibulum, lectus sapien sollicitudin elit, vulputate placerat mi nisi sed nisl. Phasellus feugiat libero et laoreet venenatis. Pellentesque id lacus a tortor malesuada consectetur. Integer eget risus magna. Nullam rhoncus sem sit amet elementum tristique. Nunc vitae ipsum elementum, vehicula dolor id, volutpat sem. Suspendisse odio lectus, sagittis sit amet nisi vel, condimentum pretium mi. Curabitur auctor sed lorem at eleifend. Nunc at nunc rhoncus ipsum tempus tempor. Fusce et posuere libero. 1 Duis condimentum ligula nec metus laoreet, sit amet porta arcu fermentum. Duis mollis, mauris in porta dictum, justo neque interdum ipsum, eget placerat nulla urna vel dui. Mauris vel pellentesque turpis. Aenean nibh magna, eleifend at sem id, vestibulum auctor lorem. Quisque at ipsum efficitur, viverra magna vitae, ultrices dolor. Aenean dignissim faucibus ex, ac ornare mauris gravida a. Aenean magna neque, eleifend sit amet aliquam vel, sodales id orci. Nam viverra lacus sit amet nibh tincidunt pretium. Morbi pellentesque metus quis nulla ultricies tristique id euismod tellus.
KlishGroup/prose-pogs
pogs/B/BTVMVHX/FAS/index.md
Markdown
mit
1,641
package core import ( . "github.com/smartystreets/goconvey/convey" "strings" "testing" ) func TestValidateSymbol(t *testing.T) { Convey("Given a node name validation function", t, func() { cases := []struct { title string name string success bool }{ {"an empty string", "", false}, {"one alphabet name", "a", true}, {"one digit name", "0", false}, {"one underscore name", "_", false}, {"a name starting from a digit", "0test", false}, {"a name starting from an underscore", "_test", false}, {"a name only containing alphabet", "test", true}, {"a name containing alphabet-digit", "t1e2s3t4", true}, {"a name containing alphabet-digit-underscore", "t1e2_s3t4", true}, {"a name containing an invalid letter", "da-me", false}, {"a name has maximum length", strings.Repeat("a", 127), true}, {"a name longer than the maximum length", strings.Repeat("a", 128), false}, {"a reserved word", "UNTIL", false}, {"a reserved word with different capitalization", "vaLIdaTE", false}, } for _, c := range cases { c := c Convey("When validating "+c.title, func() { if c.success { Convey("Then it should succeed", func() { So(ValidateSymbol(c.name), ShouldBeNil) }) } else { Convey("Then it should fail", func() { So(ValidateSymbol(c.name), ShouldNotBeNil) }) } }) } }) } func TestValidateCapacity(t *testing.T) { Convey("Given validateCapacity function", t, func() { Convey("When passing a valid value to it", func() { Convey("Then it should accept 0", func() { So(validateCapacity(0), ShouldBeNil) }) Convey("Then it should accept a maximum value", func() { So(validateCapacity(MaxCapacity), ShouldBeNil) }) }) Convey("When passing a too large value", func() { Convey("Then it should fail", func() { So(validateCapacity(MaxCapacity+1), ShouldNotBeNil) }) }) Convey("When passing a negative value", func() { Convey("Then it should fail", func() { So(validateCapacity(-1), ShouldNotBeNil) }) }) }) }
sensorbee/sensorbee
core/node_test.go
GO
mit
2,068
require './lib/graph' require './lib/path_measurer' require './lib/path_searcher' require './lib/path_explorer' require './lib/exact_path_length_checker' require './lib/max_path_distance_checker' require './lib/max_path_length_checker' edges = [] $stdin.each_line do | line | line.strip! edges.concat line.split(/\s|,\s|,/) end graph = Graph.new path_measurer = PathMeasurer.new(graph) path_searcher = PathSearcher.new(graph) exact_path_length_checker = ExactPathLengthChecker.new(graph, 4) max_path_length_checker = MaxPathLengthChecker.new(graph, 3) max_path_distance_checker = MaxPathDistanceChecker.new(graph, 30) exact_path_length_path_explorer = PathExplorer.new(graph, exact_path_length_checker) max_path_length_path_explorer = PathExplorer.new(graph, max_path_length_checker) max_path_distance_path_explorer = PathExplorer.new(graph, max_path_distance_checker) edges.each do | edge | graph.add_edge(edge[0], edge[1], edge[2..-1].to_i) end # 1. The distance of the route A-B-C. puts 'Output #1: ' + path_measurer.distance(['A', 'B', 'C']).to_s # 2. The distance of the route A-D. puts 'Output #2: ' + path_measurer.distance(['A', 'D']).to_s # 3. The distance of the route A-D-C. puts 'Output #3: ' + path_measurer.distance(['A', 'D', 'C']).to_s # 4. The distance of the route A-E-B-C-D. puts 'Output #4: ' + path_measurer.distance(['A', 'E', 'B', 'C', 'D']).to_s # 5. The distance of the route A-E-D. puts 'Output #5: ' + path_measurer.distance(['A', 'E', 'D']).to_s # # 6. The number of trips starting at C and ending at # C with a maximum of 3 stops. puts 'Output #6: ' + max_path_length_path_explorer.explore('C', 'C').count.to_s # 7. The number of trips starting at A and ending at # C with exactly 4 stops. puts 'Output #7: ' + exact_path_length_path_explorer.explore('A', 'C').count.to_s # 8. The length of the shortest route (in terms of # distance to travel) from A to C. puts 'Output #8: ' + path_searcher.shortest_path('A', 'C').to_s # 9. The length of the shortest route (in terms of # distance to travel) from B to B. puts 'Output #9: ' + path_searcher.shortest_path('B', 'B').to_s # 10. The number of different routes from C to C with # a distance of less than 30. puts 'Output #10: ' + max_path_distance_path_explorer.explore('C', 'C').count.to_s
heldtogether/train-scheduler
main.rb
Ruby
mit
2,290
export default { FETCH_TAGS_PENDING: Symbol("FETCH_TAGS_PENDING"), FETCH_TAGS_SUCCESS: Symbol("FETCH_TAGS_SUCCESS"), FETCH_TAGS_FAILURE: Symbol("FETCH_TAGS_FAILURE"), FILTER_TAGS: Symbol("FILTER_TAGS"), ORDER_TAGS: Symbol("ORDER_TAGS") };
danjac/photoshare
ui/actionTypes/tags.js
JavaScript
mit
251
<?php /** * summary */ class Product extends MY_Controller { public function __construct() { parent::__construct(); $this->load->model('product_model'); } function index(){ $total = $this->product_model->get_total(); $this->data['total'] = $total; //load thu vien phan trang $this->load->library('pagination'); $config = array(); $config['base_url'] = admin_url('product/index'); $config['total_rows'] = $total; $config['per_page'] = 5; $config['uri_segment'] = 4; $config['next_link'] = "Trang ke tiep"; $config['prev_link'] = "Trang truoc"; $this->pagination->initialize($config); /*end phan trang*/ /*load trang*/ $segment = $this->uri->segment(4); $segment = intval($segment); $input = array(); $input['limit'] = array($config['per_page'],$segment); /*loc theo id*/ $id = $this->input->get('id'); $id = intval($id); $input['where'] = array(); if ($id > 0) { $input['where']['id'] = $id; } /*loc theo ten*/ $name = $this->input->get('name'); if ($name) { $input['like'] = array('name',$name); } /*loc theo danh muc*/ $catalog_id = $this->input->get('catalog'); $catalog_id = intval($catalog_id); if ($catalog_id > 0) { $input['where']['catalog_id'] = $catalog_id; } $list = $this->product_model->get_list($input); $this->data['list'] = $list; /* end loc */ /* end load phan trang*/ /*lay danh muc san pham*/ $this->load->model('catalog_model'); $input = array(); $input['where'] = array('parent_id'=> 0); $catalogs = $this->catalog_model->get_list($input); foreach ($catalogs as $row) { $input['where'] = array('parent_id'=> $row->id); $subs = $this->catalog_model->get_list($input); $row->subs = $subs; } $this->data['catalogs'] = $catalogs; /*end lay danh muc*/ $message = $this->session->flashdata('message'); $this->data['message'] = $message; $this->data['temp'] = 'admin/product/index'; $this->load->view('admin/main', $this->data); } function add(){ /*lay danh muc san pham*/ $this->load->model('catalog_model'); $input = array(); $input['where'] = array('parent_id'=> 0); $catalogs = $this->catalog_model->get_list($input); foreach ($catalogs as $row) { $input['where'] = array('parent_id'=> $row->id); $subs = $this->catalog_model->get_list($input); $row->subs = $subs; } $this->data['catalogs'] = $catalogs; /*end lay danh muc*/ $message = $this->session->flashdata('message'); $this->data['message'] = $message; $this->load->library('form_validation'); $this->load->helper('form'); //neu ma co du lieu post len thi kiem tra if($this->input->post()) { $this->form_validation->set_rules('name', 'Tên', 'required'); $this->form_validation->set_rules('price', 'Gia', 'required'); $this->form_validation->set_rules('catalog', 'Thể loại', 'required'); //nhập liệu chính xác if($this->form_validation->run()) { //them vao csdl $name = $this->input->post('name'); $price = $this->input->post('price'); $price = str_replace(',', '', $price); $discount = $this->input->post('discount'); $discount = str_replace(',', '', $discount); /*up hinh anh dai dien*/ $this->load->library('upload_library'); $upload_path = './upload/product'; $upload_data = $this->upload_library->upload($upload_path,'image' ); $image_link = ''; if (isset($upload_data['file_name'])) { $image_link = $upload_data['file_name']; } /*Upload hinh anh kem theo*/ $image_list = array(); $image_list = $this->upload_library->upload_file($upload_path, 'image_list'); $image_list_json = json_encode($image_list); $data = array( 'name' => $name, 'price' => $price, 'discount' => $discount, 'warranty' => $this->input->post('warranty'), 'gifts' => $this->input->post('gitfs'), 'meta_desc' => $this->input->post('meta_desc'), 'meta_key' => $this->input->post('meta_key'), 'site_title' => $this->input->post('site_title'), 'content' => $this->input->post('content'), 'catalog_id' => $this->input->post('catalog') ); if($image_link != '') { $data['image_link'] = $image_link; } if(!empty($image_list)) { $data['image_list'] = $image_list_json; } if($this->product_model->create($data)) { //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'Thêm mới san pham thành công'); }else{ $this->session->set_flashdata('message', 'Không thêm được'); } //chuyen tới trang danh sách san pham redirect(admin_url('product')); } } $this->data['temp'] = 'admin/product/add'; $this->load->view('admin/main', $this->data); } function edit() { $id = $this->uri->rsegment('3'); $product = $this->product_model->get_info($id); if(!$product) { //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'Không tồn tại sản phẩm này'); redirect(admin_url('product')); } $this->data['product'] = $product; //lay danh sach danh muc san pham $this->load->model('catalog_model'); $input = array(); $input['where'] = array('parent_id' => 0); $catalogs = $this->catalog_model->get_list($input); foreach ($catalogs as $row) { $input['where'] = array('parent_id' => $row->id); $subs = $this->catalog_model->get_list($input); $row->subs = $subs; } $this->data['catalogs'] = $catalogs; //load thư viện validate dữ liệu $this->load->library('form_validation'); $this->load->helper('form'); //neu ma co du lieu post len thi kiem tra if($this->input->post()) { $this->form_validation->set_rules('name', 'Tên', 'required'); $this->form_validation->set_rules('catalog', 'Thể loại', 'required'); $this->form_validation->set_rules('price', 'Giá', 'required'); //nhập liệu chính xác if($this->form_validation->run()) { //them vao csdl $name = $this->input->post('name'); $catalog_id = $this->input->post('catalog'); $price = $this->input->post('price'); $price = str_replace(',', '', $price); $discount = $this->input->post('discount'); $discount = str_replace(',', '', $discount); //lay ten file anh minh hoa duoc update len $this->load->library('upload_library'); $upload_path = './upload/product'; $upload_data = $this->upload_library->upload($upload_path, 'image'); $image_link = ''; if(isset($upload_data['file_name'])) { $image_link = $upload_data['file_name']; } //upload cac anh kem theo $image_list = array(); $image_list = $this->upload_library->upload_file($upload_path, 'image_list'); $image_list_json = json_encode($image_list); //luu du lieu can them $data = array( 'name' => $name, 'catalog_id' => $catalog_id, 'price' => $price, 'discount' => $discount, 'warranty' => $this->input->post('warranty'), 'gifts' => $this->input->post('gifts'), 'site_title' => $this->input->post('site_title'), 'meta_desc' => $this->input->post('meta_desc'), 'meta_key' => $this->input->post('meta_key'), 'content' => $this->input->post('content'), ); if($image_link != '') { $data['image_link'] = $image_link; } if(!empty($image_list)) { $data['image_list'] = $image_list_json; } //them moi vao csdl if($this->product_model->update($product->id, $data)) { //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'Cập nhật dữ liệu thành công'); }else{ $this->session->set_flashdata('message', 'Không cập nhật được'); } //chuyen tới trang danh sách redirect(admin_url('product')); } } //load view $this->data['temp'] = 'admin/product/edit'; $this->load->view('admin/main', $this->data); } function del(){ $id = $this->uri->rsegment('3'); $this->_del($id); $this->session->set_flashdata('message', 'Xoa thanh cong '); redirect(admin_url('product')); } function delete_all(){ $ids = $this->input->post('ids'); foreach ($ids as $id) { $this->_del($id); } $this->session->set_flashdata('message', 'Xoa thanh cong cac san pham '); redirect(admin_url('product')); } private function _del($id){ $product = $this->product_model->get_info($id); if(!$product) { //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'Không tồn tại sản phẩm này'); redirect(admin_url('product')); } $this->data['product'] = $product; $this->product_model->delete($id); $image_link = './upload/product'.$product->image_link; if (file_exists($image_link)) { unlink($image_link); } $image_list = json_decode($product->image_list); foreach ($image_list as $img) { $image_link = '.upload/product'.$img; if (file_exists($image_link)) { unlink($image_link); } } } } ?>
mrthanhtan22/vemaybay
application/controllers/admin/Product.php
PHP
mit
11,577
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; import {Http, Headers} from '@angular/http'; import {Router } from '@angular/router'; import 'rxjs/add/operator/map'; @Injectable() export class AuthService { submission: FirebaseListObservable<any>; constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private router: Router){ console.log("Authentication service started"); console.log(firebase.auth()); } login(email, pass){ this.afAuth.auth.signInWithEmailAndPassword(email, pass) .then(res => { console.log('Nice, logging you in!!!'); this.router.navigate(['/admin']); }); } checkAuth(){ this.afAuth.authState.subscribe(res => { if (res && res.uid) { console.log('user is logged in'); return true; } else { console.log('user not logged in...redirecting to welcome..'); this.router.navigate(['/login']); return false; } }); } logout() { this.afAuth.auth.signOut(); this.router.navigate(['/']); } }
alimcharaniya/uniformlab-v3
src/services/auth.service.ts
TypeScript
mit
1,321
/** * * @function * @param {Array|arraylike} value * @param {Function} cmd * @param {any} context * @returns {?} */ export default function eachValue(value, cmd, context, keepReverse) { if (value === undefined || value === null) return undefined; const size = (0 | value.length) - 1; for (let index = size; index > -1; index -= 1) { const i = keepReverse ? index : size - index; const item = value[i]; const resolve = cmd.call(context || item, item, i, value, i); if (resolve === undefined === false) { return resolve; } } return undefined; }
adriancmiranda/describe-type
internal/eachValue.next.js
JavaScript
mit
568
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author John Miller * @version 1.2 * @date Sat Jan 31 20:59:02 EST 2015 * @see LICENSE (MIT style license file). */ package scalation.analytics import scalation.linalgebra.{MatriD, MatrixD, VectorD} //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `Centering` object is used to center the input matrix 'x'. This is done by * subtracting the column means from each value. */ object Centering { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Center the input matrix 'x' to zero mean, columnwise, by subtracting the mean. * @param x the input matrix to center * @param mu_x the vector of column means of matrix x */ def center (x: MatriD, mu_x: VectorD): MatrixD = { val x_c = new MatrixD (x.dim1, x.dim2) for (j <- 0 until x.dim2) { x_c.setCol (j, x.col(j) - mu_x(j)) // subtract column means } // for x_c } // center } // Centering object
mvnural/scalation
src/main/scala/scalation/analytics/Centering.scala
Scala
mit
1,112
const should = require('should'), sinon = require('sinon'), _ = require('lodash'), settingsCache = require('../../../../server/services/settings/cache'), common = require('../../../../server/lib/common'), controllers = require('../../../../server/services/routing/controllers'), TaxonomyRouter = require('../../../../server/services/routing/TaxonomyRouter'), RESOURCE_CONFIG = require('../../../../server/services/routing/assets/resource-config'), sandbox = sinon.sandbox.create(); describe('UNIT - services/routing/TaxonomyRouter', function () { let req, res, next; beforeEach(function () { sandbox.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/'); sandbox.stub(common.events, 'emit'); sandbox.stub(common.events, 'on'); sandbox.spy(TaxonomyRouter.prototype, 'mountRoute'); sandbox.spy(TaxonomyRouter.prototype, 'mountRouter'); req = sandbox.stub(); res = sandbox.stub(); next = sandbox.stub(); res.locals = {}; }); afterEach(function () { sandbox.restore(); }); it('instantiate', function () { const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/'); should.exist(taxonomyRouter.router); should.exist(taxonomyRouter.rssRouter); taxonomyRouter.taxonomyKey.should.eql('tag'); taxonomyRouter.getPermalinks().getValue().should.eql('/tag/:slug/'); common.events.emit.calledOnce.should.be.true(); common.events.emit.calledWith('router.created', taxonomyRouter).should.be.true(); taxonomyRouter.mountRouter.callCount.should.eql(1); taxonomyRouter.mountRouter.args[0][0].should.eql('/tag/:slug/'); taxonomyRouter.mountRouter.args[0][1].should.eql(taxonomyRouter.rssRouter.router()); taxonomyRouter.mountRoute.callCount.should.eql(3); // permalink route taxonomyRouter.mountRoute.args[0][0].should.eql('/tag/:slug/'); taxonomyRouter.mountRoute.args[0][1].should.eql(controllers.channel); // pagination feature taxonomyRouter.mountRoute.args[1][0].should.eql('/tag/:slug/page/:page(\\d+)'); taxonomyRouter.mountRoute.args[1][1].should.eql(controllers.channel); // edit feature taxonomyRouter.mountRoute.args[2][0].should.eql('/tag/:slug/edit'); taxonomyRouter.mountRoute.args[2][1].should.eql(taxonomyRouter._redirectEditOption.bind(taxonomyRouter)); }); it('fn: _prepareContext', function () { const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/'); taxonomyRouter._prepareContext(req, res, next); next.calledOnce.should.eql(true); res.locals.routerOptions.should.eql({ name: 'tag', permalinks: '/tag/:slug/', type: RESOURCE_CONFIG.QUERY.tag.resource, data: {tag: _.omit(RESOURCE_CONFIG.QUERY.tag, 'alias')}, filter: RESOURCE_CONFIG.TAXONOMIES.tag.filter, context: ['tag'], slugTemplate: true, identifier: taxonomyRouter.identifier }); res._route.type.should.eql('channel'); }); });
dbalders/Ghost
core/test/unit/services/routing/TaxonomyRouter_spec.js
JavaScript
mit
3,184
<?php use Snscripts\HtmlHelper\Html; use Snscripts\HtmlHelper\Services; use Snscripts\HtmlHelper\Helpers; class HtmlTest extends \PHPUnit_Framework_TestCase { public function testCanCreateInstance() { $this->assertInstanceOf( 'Snscripts\HtmlHelper\Html', new Html( new Helpers\Form( new Services\Basic\Data ), new Services\Basic\Router, new Services\Basic\Assets ) ); } /** * return an instance of the Html Helper * with constructor */ protected function getHtml() { return new Html( new Helpers\Form( new Services\Basic\Data ), new Services\Basic\Router, new Services\Basic\Assets ); } /** * return an instance of the Html Helper * with constructor dissabled so we can test the constructor setters */ protected function getHtmlNoConstructor() { return $this->getMockBuilder('\Snscripts\HtmlHelper\Html') ->setMethods(array('__construct')) ->setConstructorArgs(array(false, false)) ->disableOriginalConstructor() ->getMock(); } public function testSettingValidFormObject() { $Html = $this->getHtmlNoConstructor(); $this->assertTrue( $Html->setForm( new Helpers\Form( new Services\Basic\Data ) ) ); } public function testSettingInvalidFormObjectThrowsException() { $this->setExpectedException('InvalidArgumentException'); $Html = $this->getHtmlNoConstructor(); $Html->setForm( new \stdClass ); } public function testSettingValidAbstractRouter() { $Html = $this->getHtmlNoConstructor(); $this->assertTrue( $Html->setRouter( new Services\Basic\Router ) ); } public function testSettingInvalidAbstractRouterThrowsException() { $this->setExpectedException('InvalidArgumentException'); $Html = $this->getHtmlNoConstructor(); $Html->setRouter( new \stdClass ); } public function testSettingValidAbstractAssets() { $Html = $this->getHtmlNoConstructor(); $this->assertTrue( $Html->setAssets( new Services\Basic\Assets ) ); } public function testSettingInvalidAbstractAssetsThrowsException() { $this->setExpectedException('InvalidArgumentException'); $Html = $this->getHtmlNoConstructor(); $Html->setAssets( new \stdClass ); } public function testTagReturnsValidDivTagWithAttributes() { $Html = $this->getHtml(); $this->assertSame( '<div class="myClass" id="content">Div Contents</div>', $Html->tag( 'div', array( 'class' => 'myClass', 'id' => 'content' ), 'Div Contents', true ) ); } public function testDivReturnsValidDivElement() { $Html = $this->getHtml(); $this->assertSame( '<div class="myClass" id="content">Div Contents</div>', $Html->div( 'Div Contents', array( 'class' => 'myClass', 'id' => 'content' ) ) ); } public function testPReturnsValidPElement() { $Html = $this->getHtml(); $this->assertSame( '<p class="intro">Paragraph Contents</p>', $Html->p( 'Paragraph Contents', array( 'class' => 'intro' ) ) ); } public function testUlReturnsValidUlElement() { $Html = $this->getHtml(); $this->assertSame( '<ul id="main ul"><li>this is a list item</li><li>this is a list item 2</li><li>sub-item<ul><li>will they work?</li><li>or won\'t they, who knows?</li></ul></li><li id="listID">subitem attr!<ul id="sub-list"><li>this is a sub item</li><li>this list should have attributes</li></ul></li></ul>', $Html->ul( array( 'this is a list item', 'this is a list item 2', 'sub-item' => array( 'will they work?', 'or won\'t they, who knows?' ), 'subitem attr!' => array( 'attr' => array( 'id' => 'listID' ), 'listAttr' => array( 'id' => 'sub-list' ), 'list' => array( 'this is a sub item', 'this list should have attributes' ) ) ), array( 'id' => 'main ul' ) ) ); } public function testOlReturnsValidOlElement() { $Html = $this->getHtml(); $this->assertSame( '<ol id="main ol"><li>this is a list item</li><li>this is a list item 2</li><li>sub-item<ol><li>will they work?</li><li>or won\'t they, who knows?</li></ol></li><li id="listID">subitem attr!<ol id="sub-list"><li>this is a sub item</li><li>this list should have attributes</li></ol></li></ol>', $Html->ol( array( 'this is a list item', 'this is a list item 2', 'sub-item' => array( 'will they work?', 'or won\'t they, who knows?' ), 'subitem attr!' => array( 'attr' => array( 'id' => 'listID' ), 'listAttr' => array( 'id' => 'sub-list' ), 'list' => array( 'this is a sub item', 'this list should have attributes' ) ) ), array( 'id' => 'main ol' ) ) ); } public function testListReturnsValidElements() { $Html = $this->getHtml(); $this->assertSame( '<li>this is a list item</li><li>this is a list item 2</li><li>sub-item<ul><li>will they work?</li><li>or won\'t they, who knows?</li></ul></li><li id="listID">subitem attr!<ul id="sub-list"><li>this is a sub item</li><li>this list should have attributes</li></ul></li>', $Html->processList( array( 'this is a list item', 'this is a list item 2', 'sub-item' => array( 'will they work?', 'or won\'t they, who knows?' ), 'subitem attr!' => array( 'attr' => array( 'id' => 'listID' ), 'listAttr' => array( 'id' => 'sub-list' ), 'list' => array( 'this is a sub item', 'this list should have attributes' ) ) ) ) ); } public function testLinkReturnsValidElements() { $Html = $this->getHtml(); $this->assertSame( '<a target="_blank" class="myClass" href="http://google.com">Google</a>', $Html->link( 'Google', 'http://google.com', array( 'target' => '_blank', 'class' => 'myClass' ) ) ); } public function testImageReturnsValidElement() { $Html = $this->getHtml(); $this->assertSame( '<img alt="This is alt text" title="This is the title" class="logo" src="/assets/img/logo.png">', $Html->image( '/assets/img/logo.png', array( 'alt' => 'This is alt text', 'title' => 'This is the title', 'class' => 'logo' ) ) ); } public function testStyleReturnsValidElement() { $Html = $this->getHtml(); $this->assertSame( '<link media="print" rel="stylesheet" type="text/css" href="/assets/css/print.css">', $Html->style( '/assets/css/print.css', array( 'media' => 'print' ) ) ); } public function testScriptReturnsValidElement() { $Html = $this->getHtml(); $this->assertSame( '<script src="/assets/js/site.js"></script>', $Html->script( '/assets/js/site.js' ) ); } }
snscripts/html-helper
Tests/HtmlTest.php
PHP
mit
9,524
<?php /*============================================================================== * (C) Copyright 2016,2020 John J Kauflin, All rights reserved. *---------------------------------------------------------------------------- * DESCRIPTION: Functions to validate Admin operations (i.e. check permissions * parameters, timing, etc.) *---------------------------------------------------------------------------- * Modification History * 2016-04-05 JJK Added check for AddAssessments * 2020-08-01 JJK Re-factored to use jjklogin for authentication * 2020-12-21 JJK Re-factored to use jjklogin package *============================================================================*/ // Define a super global constant for the log file (this will be in scope for all functions) define("LOG_FILE", "./php.log"); require_once 'vendor/autoload.php'; // Figure out how many levels up to get to the "public_html" root folder $webRootDirOffset = substr_count(strstr(dirname(__FILE__),"public_html"),DIRECTORY_SEPARATOR) + 1; // Get settings and credentials from a file in a directory outside of public_html // (assume a settings file in the "external_includes" folder one level up from "public_html") $extIncludePath = dirname(__FILE__, $webRootDirOffset+1).DIRECTORY_SEPARATOR.'external_includes'.DIRECTORY_SEPARATOR; require_once $extIncludePath.'hoadbSecrets.php'; require_once $extIncludePath.'jjkloginSettings.php'; // Common functions require_once 'php_secure/commonUtil.php'; // Common database functions and table record classes require_once 'php_secure/hoaDbCommon.php'; use \jkauflin\jjklogin\LoginAuth; $adminRec = new AdminRec(); try { $userRec = LoginAuth::getUserRec($cookieNameJJKLogin,$cookiePathJJKLogin,$serverKeyJJKLogin); if ($userRec->userName == null || $userRec->userName == '') { throw new Exception('User is NOT logged in', 500); } if ($userRec->userLevel < 1) { throw new Exception('User is NOT authorized (contact Administrator)', 500); } $currTimestampStr = date("Y-m-d H:i:s"); //JJK test, date = 2015-04-22 19:45:09 $adminRec->result = "Not Valid"; $adminRec->message = ""; $adminRec->userName = $userRec->userName; $adminRec->userLevel = $userRec->userLevel; $adminLevel = $userRec->userLevel; $action = getParamVal("action"); $fy = getParamVal("fy"); $duesAmt = strToUSD(getParamVal("duesAmt")); if ($adminLevel < 2) { $adminRec->message = "You do not have permissions for this function"; $adminRec->result = "Not Valid"; } else { $adminRec->result = "Valid"; $adminRec->message = "Continue with " . $action . "?"; if ($action == "AddAssessments") { if (empty($duesAmt) || empty($fy)) { $adminRec->message = "You must enter Dues Amount and Fiscal Year."; $adminRec->result = "Not Valid"; } else { $adminRec->message = "Are you sure you want to add assessment for Fiscal Year " . $fy . ' with Dues Amount of $' . $duesAmt .'?'; } } else if ($action == "MarkMailed") { $adminRec->message = "Continue to record Communication to mark paper notices as mailed?"; } else if ($action == "DuesEmailsTest") { $adminRec->message = "Continue with TEST email of Dues Notices to show the list and send the first one to the test address?"; } else if ($action == "DuesEmails") { $adminRec->message = "Continue with email of Dues Notices? This will create a Communication record for each email to send"; } } echo json_encode($adminRec); } catch(Exception $e) { //error_log(date('[Y-m-d H:i] '). "in " . basename(__FILE__,".php") . ", Exception = " . $e->getMessage() . PHP_EOL, 3, LOG_FILE); $adminRec->message = $e->getMessage(); $adminRec->result = "Not Valid"; echo json_encode($adminRec); /* echo json_encode( array( 'error' => $e->getMessage(), 'error_code' => $e->getCode() ) ); */ } ?>
jkauflin/hoadb
adminValidate.php
PHP
mit
3,993
<h1>Access Denied</h1> <p>You have logged in correctly, but you have tried to access a page without a high enough level of security clearance.</p>
tonymarklove/wool
views/user/admin_denied.php
PHP
mit
147
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.11"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="all_6.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
yurikoma/PhysicsForGamesAIE_StudentWork
dependencies/glfw/docs/html/search/all_6.html
HTML
mit
1,039