code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
from .cpu import Cpu
Hexadorsimal/pynes
nes/processors/cpu/__init__.py
Python
mit
21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <?php require_once("globals.php"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php $page_title = "Projects"; require_once("meta.php"); ?> </head> <body> <div id="logo"> <?php require_once("header.php"); ?> </div> <!-- end of logo --> <div id="header"> <div id="navigation"> <?php require_once("navigation.php"); ?> </div> <!-- end of navigation --> </div> <!-- end of header --> <div id="wrap"> <div id="wrap-btm"> <div id="main"> <div id="content"> <div class="post"> projects </div> </div> <!-- end of content --> <!-- start sidebar --> <div id="sidepanel"> <?php require_once("leftpanel.php"); ?> </div> <div style="clear: both;">&nbsp;</div> </div> <!-- end of main --> </div> <!-- end of wrap --> </div> <!-- end of wrap-btm --> <div id="footer-wrap"> <div id="footer"> <?php require_once("footer.php"); ?> </div> </div> <!-- end of footer --> </body> </html>
JayWalker512/brandonfoltz.com
projects.php
PHP
mit
1,055
<?php /** * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Tax\Controller\Adminhtml\Rule; use Magento\Framework\Controller\ResultFactory; class Delete extends \Magento\Tax\Controller\Adminhtml\Rule { /** * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $ruleId = (int)$this->getRequest()->getParam('rule'); try { $this->ruleService->deleteById($ruleId); $this->messageManager->addSuccess(__('The tax rule has been deleted.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->messageManager->addError(__('This rule no longer exists.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong deleting this tax rule.')); } return $resultRedirect->setUrl($this->_redirect->getRedirectUrl($this->getUrl('*'))); } }
j-froehlich/magento2_wk
vendor/magento/module-tax/Controller/Adminhtml/Rule/Delete.php
PHP
mit
1,412
/// <reference path="initialization.ts" /> function initializeAppInsights() { try { // only initialize if we are running in a browser that supports JSON serialization (ie7<, node.js, cordova) if (typeof window !== "undefined" && typeof JSON !== "undefined") { // get snippet or initialize to an empty object var aiName = "appInsights"; if (window[aiName] === undefined) { // if no snippet is present, initialize default values Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(); } else { // this is the typical case for browser+snippet var snippet: Microsoft.ApplicationInsights.Snippet = window[aiName] || <any>{}; // overwrite snippet with full appInsights var init = new Microsoft.ApplicationInsights.Initialization(snippet); var appInsightsLocal = init.loadAppInsights(); // apply full appInsights to the global instance that was initialized in the snippet for (var field in appInsightsLocal) { snippet[field] = appInsightsLocal[field]; } init.emptyQueue(); init.pollInteralLogs(appInsightsLocal); init.addHousekeepingBeforeUnload(appInsightsLocal); } } } catch (e) { console.error('Failed to initialize AppInsights JS SDK: ' + e.message); } } initializeAppInsights();
reyno-uk/ApplicationInsights-JS
JavaScript/JavaScriptSDK/Init.ts
TypeScript
mit
1,610
import React from 'react'; import { Link as RouterLink } from 'react-router'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import counterActions from 'actions/counter'; import Radium from 'radium'; import { Scroll, Link, Element, Events } from 'react-scroll'; import { FlatButton, Paper } from 'material-ui/lib'; import { styles } from 'styles/HomeViewStyles'; const mapStateToProps = (state) => ({ counter: state.counter, routerState: state.router }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(counterActions, dispatch) }); @Radium class HomeView extends React.Component { static propTypes = { actions: React.PropTypes.object, counter: React.PropTypes.number } render() { return ( <div className='landing main-body' style={styles.mainBody}> <div style={styles.heroDiv}> <img src={require('styles/assets/splash3.png')} style={styles.heroImg} draggable='false' /> <div style={styles.heroText}> a simple, intuitive, <br/>drag-and-drop resume builder </div> {Radium.getState(this.state, 'callToAction', 'hover')} <RouterLink to='/resume'> <div style={styles.callToAction} key='callToAction'> get started </div> </RouterLink> {Radium.getState(this.state, 'circle', 'hover')} <Link to='Features' spy={true} smooth={true} duration={800}> <div style={styles.circle} key='circle'> <img src={require('styles/assets/downArrow.png')} style={styles.downArrow} /> </div> </Link> <div style={styles.diagonalLine}></div> </div> <div style={styles.grayDivMiddle}> <div style={styles.copy}> <Element name='Features'> <div style={styles.wysiwyg}>what you see is what you get</div> <div style={styles.video}> <iframe src="https://player.vimeo.com/video/149104789?color=ff9f10&title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </Element> <div style={styles.middleCopy}> <div>Import your information from LinkedIn</div> <div>Save your progress to the cloud</div> <div>Easily print or export to PDF when you're done</div> </div> <RouterLink to='/resume'> <div style={styles.getStartedButton}> get started </div> </RouterLink> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView); /* Here lies the counter. It was a good counter; it incremented when clicked. But it was more than just a simple counter. It was a window into another world; a stateful lighthouse to our souls. The counter is dead. Long live the counter! <div style={{ margin: '20px' }}> <div style={{ margin: '5px' }}> For no reason, a counter: {this.props.counter} </div> <RaisedButton label='Increment' onClick={this.props.actions.increment} /> </div> */
dont-fear-the-repo/fear-the-repo
src/views/HomeView.js
JavaScript
mit
3,354
require 'test_helper' class LockableTest < ActiveSupport::TestCase def setup setup_mailer end test "should respect maximum attempts configuration" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end end test "should increment failed_attempts on successfull validation if the user is already locked" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end user.valid_for_authentication?{ true } assert_equal 4, user.reload.failed_attempts end test "should not touch failed_attempts if lock_strategy is none" do user = create_user user.confirm! swap Devise, :lock_strategy => :none, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert !user.access_locked? assert_equal 0, user.failed_attempts end end test 'should be valid for authentication with a unlocked user' do user = create_user user.lock_access! user.unlock_access! assert user.valid_for_authentication?{ true } end test "should verify whether a user is locked or not" do user = create_user assert_not user.access_locked? user.lock_access! assert user.access_locked? end test "active_for_authentication? should be the opposite of locked?" do user = create_user user.confirm! assert user.active_for_authentication? user.lock_access! assert_not user.active_for_authentication? end test "should unlock a user by cleaning locked_at, falied_attempts and unlock_token" do user = create_user user.lock_access! assert_not_nil user.reload.locked_at assert_not_nil user.reload.unlock_token user.unlock_access! assert_nil user.reload.locked_at assert_nil user.reload.unlock_token assert_equal 0, user.reload.failed_attempts end test "new user should not be locked and should have zero failed_attempts" do assert_not new_user.access_locked? assert_equal 0, create_user.failed_attempts end test "should unlock user after unlock_in period" do swap Devise, :unlock_in => 3.hours do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? Devise.unlock_in = 1.hour assert_not user.access_locked? end end test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do swap Devise, :unlock_strategy => :email do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? end end test "should set unlock_token when locking" do user = create_user assert_nil user.unlock_token user.lock_access! assert_not_nil user.unlock_token end test "should never generate the same unlock token for different users" do unlock_tokens = [] 3.times do user = create_user user.lock_access! token = user.unlock_token assert !unlock_tokens.include?(token) unlock_tokens << token end end test "should not generate unlock_token when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user user.lock_access! assert_nil user.unlock_token end end test "should send email with unlock instructions when :email is an unlock strategy" do swap Devise, :unlock_strategy => :email do user = create_user assert_email_sent do user.lock_access! end end end test "should not send email with unlock instructions when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user assert_email_not_sent do user.lock_access! end end end test 'should find and unlock a user automatically' do user = create_user user.lock_access! locked_user = User.unlock_access_by_token(user.unlock_token) assert_equal locked_user, user assert_not user.reload.access_locked? end test 'should return a new record with errors when a invalid token is given' do locked_user = User.unlock_access_by_token('invalid_token') assert_not locked_user.persisted? assert_equal "is invalid", locked_user.errors[:unlock_token].join end test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') assert_not locked_user.persisted? assert_equal "can't be blank", locked_user.errors[:unlock_token].join end test 'should find a user to send unlock instructions' do user = create_user user.lock_access! unlock_user = User.send_unlock_instructions(:email => user.email) assert_equal unlock_user, user end test 'should return a new user if no email was found' do unlock_user = User.send_unlock_instructions(:email => "invalid@example.com") assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do unlock_user = User.send_unlock_instructions(:email => "invalid@example.com") assert_equal 'not found', unlock_user.errors[:email].join end test 'should find a user to send unlock instructions by authentication_keys' do swap Devise, :authentication_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email, :username => user.username) assert_equal unlock_user, user end end test 'should require all unlock_keys' do swap Devise, :unlock_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email) assert_not unlock_user.persisted? assert_equal "can't be blank", unlock_user.errors[:username].join end end test 'should not be able to send instructions if the user is not locked' do user = create_user assert_not user.resend_unlock_token assert_not user.access_locked? assert_equal 'was not locked', user.errors[:email].join end test 'should unlock account if lock has expired and increase attempts on failure' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { false } assert_equal 1, user.failed_attempts end end test 'should unlock account if lock has expired on success' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { true } assert_equal 0, user.failed_attempts assert_nil user.locked_at end end test 'required_fields should contain the all the fields when all the strategies are enabled' do swap Devise, :unlock_strategy => :both do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at, :unlock_token ] end end end test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do swap Devise, :unlock_strategy => :time do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at ] end end end test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do swap Devise, :unlock_strategy => :email do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :unlock_token ] end end end test 'should not return a locked unauthenticated message if in paranoid mode' do swap Devise, :paranoid => :true do user = create_user user.failed_attempts = Devise.maximum_attempts + 1 user.lock_access! assert_equal :invalid, user.unauthenticated_message end end end
piousbox/microsites2-cities
vendor/ruby/1.9.1/gems/devise-2.2.3/test/models/lockable_test.rb
Ruby
mit
8,403
#! /usr/bin/python2 # # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # import argparse import collections import re import subprocess import sys __DESCRIPTION = """ Processes a perf.data sample file and reports the hottest Ignition bytecodes, or write an input file for flamegraph.pl. """ __HELP_EPILOGUE = """ examples: # Get a flamegraph for Ignition bytecode handlers on Octane benchmark, # without considering the time spent compiling JS code, entry trampoline # samples and other non-Ignition samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt run.js $ tools/ignition/linux_perf_report.py --flamegraph -o out.collapsed $ flamegraph.pl --colors js out.collapsed > out.svg # Same as above, but show all samples, including time spent compiling JS code, # entry trampoline samples and other samples. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-all -o out.collapsed $ # ... # Same as above, but show full function signatures in the flamegraph. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-full-signatures -o out.collapsed $ # ... # See the hottest bytecodes on Octane benchmark, by number of samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt octane/run.js $ tools/ignition/linux_perf_report.py """ COMPILER_SYMBOLS_RE = re.compile( r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser") JIT_CODE_SYMBOLS_RE = re.compile( r"(LazyCompile|Compile|Eval|Script):(\*|~)") GC_SYMBOLS_RE = re.compile( r"v8::internal::Heap::CollectGarbage") def strip_function_parameters(symbol): if symbol[-1] != ')': return symbol pos = 1 parenthesis_count = 0 for c in reversed(symbol): if c == ')': parenthesis_count += 1 elif c == '(': parenthesis_count -= 1 if parenthesis_count == 0: break else: pos += 1 return symbol[:-pos] def collapsed_callchains_generator(perf_stream, hide_other=False, hide_compiler=False, hide_jit=False, hide_gc=False, show_full_signatures=False): current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False for line in perf_stream: # Lines starting with a "#" are comments, skip them. if line[0] == "#": continue line = line.strip() # Empty line signals the end of the callchain. if not line: if (not skip_until_end_of_chain and current_chain and not hide_other): current_chain.append("[other]") yield current_chain # Reset parser status. current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False continue if skip_until_end_of_chain: continue # Trim the leading address and the trailing +offset, if present. symbol = line.split(" ", 1)[1].split("+", 1)[0] if not show_full_signatures: symbol = strip_function_parameters(symbol) # Avoid chains of [unknown] if (symbol == "[unknown]" and current_chain and current_chain[-1] == "[unknown]"): continue current_chain.append(symbol) if symbol.startswith("BytecodeHandler:"): current_chain.append("[interpreter]") yield current_chain skip_until_end_of_chain = True elif JIT_CODE_SYMBOLS_RE.match(symbol): if not hide_jit: current_chain.append("[jit]") yield current_chain skip_until_end_of_chain = True elif GC_SYMBOLS_RE.match(symbol): if not hide_gc: current_chain.append("[gc]") yield current_chain skip_until_end_of_chain = True elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain: if not hide_compiler: current_chain.append("[compiler]") yield current_chain skip_until_end_of_chain = True elif COMPILER_SYMBOLS_RE.match(symbol): compiler_symbol_in_chain = True elif symbol == "Builtin:InterpreterEntryTrampoline": if len(current_chain) == 1: yield ["[entry trampoline]"] else: # If we see an InterpreterEntryTrampoline which is not at the top of the # chain and doesn't have a BytecodeHandler above it, then we have # skipped the top BytecodeHandler due to the top-level stub not building # a frame. File the chain in the [misattributed] bucket. current_chain[-1] = "[misattributed]" yield current_chain skip_until_end_of_chain = True def calculate_samples_count_per_callchain(callchains): chain_counters = collections.defaultdict(int) for callchain in callchains: key = ";".join(reversed(callchain)) chain_counters[key] += 1 return chain_counters.items() def calculate_samples_count_per_handler(callchains): def strip_handler_prefix_if_any(handler): return handler if handler[0] == "[" else handler.split(":", 1)[1] handler_counters = collections.defaultdict(int) for callchain in callchains: handler = strip_handler_prefix_if_any(callchain[-1]) handler_counters[handler] += 1 return handler_counters.items() def write_flamegraph_input_file(output_stream, callchains): for callchain, count in calculate_samples_count_per_callchain(callchains): output_stream.write("{}; {}\n".format(callchain, count)) def write_handlers_report(output_stream, callchains): handler_counters = calculate_samples_count_per_handler(callchains) samples_num = sum(counter for _, counter in handler_counters) # Sort by decreasing number of samples handler_counters.sort(key=lambda entry: entry[1], reverse=True) for bytecode_name, count in handler_counters: output_stream.write( "{}\t{}\t{:.3f}%\n".format(bytecode_name, count, 100. * count / samples_num)) def parse_command_line(): command_line_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__DESCRIPTION, epilog=__HELP_EPILOGUE) command_line_parser.add_argument( "perf_filename", help="perf sample file to process (default: perf.data)", nargs="?", default="perf.data", metavar="<perf filename>" ) command_line_parser.add_argument( "--flamegraph", "-f", help="output an input file for flamegraph.pl, not a report", action="store_true", dest="output_flamegraph" ) command_line_parser.add_argument( "--hide-other", help="Hide other samples", action="store_true" ) command_line_parser.add_argument( "--hide-compiler", help="Hide samples during compilation", action="store_true" ) command_line_parser.add_argument( "--hide-jit", help="Hide samples from JIT code execution", action="store_true" ) command_line_parser.add_argument( "--hide-gc", help="Hide samples from garbage collection", action="store_true" ) command_line_parser.add_argument( "--show-full-signatures", "-s", help="show full signatures instead of function names", action="store_true" ) command_line_parser.add_argument( "--output", "-o", help="output file name (stdout if omitted)", type=argparse.FileType('wt'), default=sys.stdout, metavar="<output filename>", dest="output_stream" ) return command_line_parser.parse_args() def main(): program_options = parse_command_line() perf = subprocess.Popen(["perf", "script", "--fields", "ip,sym", "-i", program_options.perf_filename], stdout=subprocess.PIPE) callchains = collapsed_callchains_generator( perf.stdout, program_options.hide_other, program_options.hide_compiler, program_options.hide_jit, program_options.hide_gc, program_options.show_full_signatures) if program_options.output_flamegraph: write_flamegraph_input_file(program_options.output_stream, callchains) else: write_handlers_report(program_options.output_stream, callchains) if __name__ == "__main__": main()
hoho/dosido
nodejs/deps/v8/tools/ignition/linux_perf_report.py
Python
mit
8,176
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nexports.__esModule = true;\nconsole.log('do something');\n// The DEBUG constant will be inlined by webpack's DefinePlugin (see config)\n// The whole if-statement can then be removed by UglifyJS\nif (false) { var debug; }\nconsole.log('do something else');\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
jbrantly/ts-loader
test/comparison-tests/conditionalRequire/expectedOutput-2.8/bundle.js
JavaScript
mit
3,132
<?php namespace ApplicationInsights\Channel\Contracts; /** * Contains utilities for contract classes */ class Utils { /** * Removes NULL and empty collections * @param array $sourceArray * @return array */ public static function removeEmptyValues($sourceArray) { $newArray = array(); foreach ($sourceArray as $key => $value) { if ((is_array($value) && sizeof($value) == 0) || ($value == NULL && is_bool($value) == false)) { continue; } $newArray[$key] = $value; } return $newArray; } /** * Serialization helper. * @param array Items to serialize * @return array JSON serialized items, nested */ public static function getUnderlyingData($dataItems) { $queueToEncode = array(); foreach ($dataItems as $key => $dataItem) { if (method_exists($dataItem, 'jsonSerialize') == true) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem->jsonSerialize()); } else if (is_array($dataItem)) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem); } else { $queueToEncode[$key] = $dataItem; } } return $queueToEncode; } /** * Converts milliseconds to a timespan string as accepted by the backend * @param int $milliseconds * @return string */ public static function convertMillisecondsToTimeSpan($milliseconds) { if ($milliseconds == NULL || $milliseconds < 0) { $milliseconds = 0; } $ms = $milliseconds % 1000; $sec = floor($milliseconds / 1000) % 60; $min = floor($milliseconds / (1000 * 60)) % 60; $hour = floor($milliseconds / (1000 * 60 * 60)) % 24; $ms = strlen($ms) == 1 ? '00' . $ms : (strlen($ms) === 2 ? "0" . $ms : $ms); $sec = strlen($sec) < 2 ? '0' . $sec : $sec; $min = strlen($min) < 2 ? '0' . $min : $min; $hour = strlen($hour) < 2 ? '0' . $hour : $hour; return $hour . ":" . $min . ":" . $sec . "." . $ms; } /** * Returns the proper ISO string for Application Insights service to accept. * @param mixed $time * @return string */ public static function returnISOStringForTime($time = null) { if ($time == NULL) { return gmdate('c') . 'Z'; } else { return gmdate('c', $time) . 'Z'; } } /** * Returns a Guid on all flavors of PHP. Copied from the PHP manual: http://php.net/manual/en/function.com-create-guid.php * @return mixed */ public static function returnGuid() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); } }
fidmor89/appInsights-Concrete
appinsights/vendor/microsoft/application-insights/ApplicationInsights/Channel/Contracts/Utils.php
PHP
mit
3,254
/* */ var cof = require("./_cof"), TAG = require("./_wks")('toStringTag'), ARG = cof(function() { return arguments; }()) == 'Arguments'; module.exports = function(it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof(T = (O = Object(it))[TAG]) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; };
jdanyow/aurelia-plunker
jspm_packages/npm/core-js@2.1.0/modules/_classof.js
JavaScript
mit
427
/* eslint node/no-unsupported-features: ["error", { version: 4 }] */ // this file is not transpiled by Jest when configured in "snapshotSerializers" "use strict"; const _ = require("lodash"); const normalizeNewline = require("normalize-newline"); const constants = require("./constants"); const VERSION_REGEX = new RegExp(`^(?:((?:.*?version )|\\^)|v?)${constants.LERNA_VERSION}`, "gm"); const VERSION_REPLACEMENT = `$1${constants.__TEST_VERSION__}`; // TODO: maybe even less naïve regex? function needsReplacement(str) { return ( str.indexOf(constants.__TEST_VERSION__) === -1 ); } function stableVersion(str) { return str.replace(VERSION_REGEX, VERSION_REPLACEMENT); } const stabilizeString = _.flow([ normalizeNewline, stableVersion, ]); /** A snapshot serializer that replaces all instances of unstable version number with __TEST_VERSION__ when found in snapshotted strings or object properties. @see http://facebook.github.io/jest/docs/expect.html#expectaddsnapshotserializerserializer **/ module.exports = { test(thing) { return _.isString(thing) && needsReplacement(thing) || ( _.isPlainObject(thing) && _.isString(thing.lerna) && needsReplacement(thing.lerna) ); }, print(thing, serialize) { if (_.isString(thing)) { thing = stabilizeString(thing); } else if (_.isPlainObject(thing)) { thing.lerna = stableVersion(thing.lerna); } return serialize(thing); }, };
FaHeymann/lerna
test/helpers/serializePlaceholders.js
JavaScript
mit
1,443
/*! * address.js - address object for decentraland * Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * Copyright (c) 2016-2017, Manuel Araoz (MIT License). * https://github.com/decentraland/decentraland-node */ 'use strict'; var networks = require('../protocol/networks'); var constants = require('../protocol/constants'); var util = require('../utils/util'); var crypto = require('../crypto/crypto'); var assert = require('assert'); var BufferReader = require('../utils/reader'); var StaticWriter = require('../utils/staticwriter'); var base58 = require('../utils/base58'); var scriptTypes = constants.scriptTypes; /** * Represents an address. * @exports Address * @constructor * @param {Object} options * @param {Buffer|Hash} options.hash - Address hash. * @param {AddressType} options.type - Address type * `{witness,}{pubkeyhash,scripthash}`. * @param {Number} [options.version=-1] - Witness program version. * @property {Buffer} hash * @property {AddressType} type * @property {Number} version */ function Address(options) { if (!(this instanceof Address)) return new Address(options); this.hash = constants.ZERO_HASH160; this.type = scriptTypes.PUBKEYHASH; this.version = -1; var Network = require('../protocol/network'); this.network = Network.primary; if (options) this.fromOptions(options); } /** * Address types. * @enum {Number} */ Address.types = scriptTypes; /** * Inject properties from options object. * @private * @param {Object} options */ Address.prototype.fromOptions = function fromOptions(options) { if (typeof options === 'string') return this.fromBase58(options); if (Buffer.isBuffer(options)) return this.fromRaw(options); return this.fromHash( options.hash, options.type, options.version, options.network ); }; /** * Insantiate address from options. * @param {Object} options * @returns {Address} */ Address.fromOptions = function fromOptions(options) { return new Address().fromOptions(options); }; /** * Get the address hash. * @param {String?} enc - Can be `"hex"` or `null`. * @returns {Hash|Buffer} */ Address.prototype.getHash = function getHash(enc) { if (enc === 'hex') return this.hash.toString(enc); return this.hash; }; /** * Get a network address prefix for the address. * @returns {Number} */ Address.prototype.getPrefix = function getPrefix(network) { if (!network) network = this.network; var Network = require('../protocol/network'); network = Network.get(network); return Address.getPrefix(this.type, network); }; /** * Verify an address network (compares prefixes). * @returns {Boolean} */ Address.prototype.verifyNetwork = function verifyNetwork(network) { assert(network); return this.getPrefix() === this.getPrefix(network); }; /** * Get the address type as a string. * @returns {AddressType} */ Address.prototype.getType = function getType() { return constants.scriptTypesByVal[this.type].toLowerCase(); }; /** * Calculate size of serialized address. * @returns {Number} */ Address.prototype.getSize = function getSize() { var size = 5 + this.hash.length; if (this.version !== -1) size += 2; return size; }; /** * Compile the address object to its raw serialization. * @returns {Buffer} * @throws Error on bad hash/prefix. */ Address.prototype.toRaw = function toRaw(network) { var size = this.getSize(); var bw = new StaticWriter(size); var prefix = this.getPrefix(network); assert(prefix !== -1, 'Not a valid address prefix.'); bw.writeU8(prefix); if (this.version !== -1) { bw.writeU8(this.version); bw.writeU8(0); } bw.writeBytes(this.hash); bw.writeChecksum(); return bw.render(); }; /** * Compile the address object to a base58 address. * @returns {Base58Address} * @throws Error on bad hash/prefix. */ Address.prototype.toBase58 = function toBase58(network) { return base58.encode(this.toRaw(network)); }; /** * Convert the Address to a string. * @returns {Base58Address} */ Address.prototype.toString = function toString() { return this.toBase58(); }; /** * Inspect the Address. * @returns {Object} */ Address.prototype.inspect = function inspect() { return '<Address:' + ' type=' + this.getType() + ' version=' + this.version + ' base58=' + this.toBase58() + '>'; }; /** * Inject properties from serialized data. * @private * @param {Buffer} data * @throws Parse error */ Address.prototype.fromRaw = function fromRaw(data) { var br = new BufferReader(data, true); var i, prefix, network, type, version, hash; prefix = br.readU8(); for (i = 0; i < networks.types.length; i++) { network = networks[networks.types[i]]; type = Address.getType(prefix, network); if (type !== -1) break; } assert(i < networks.types.length, 'Unknown address prefix.'); if (data.length > 25) { version = br.readU8(); assert(br.readU8() === 0, 'Address version padding is non-zero.'); } else { version = -1; } hash = br.readBytes(br.left() - 4); br.verifyChecksum(); return this.fromHash(hash, type, version, network.type); }; /** * Create an address object from a serialized address. * @param {Buffer} data * @returns {Address} * @throws Parse error. */ Address.fromRaw = function fromRaw(data) { return new Address().fromRaw(data); }; /** * Inject properties from base58 address. * @private * @param {Base58Address} data * @throws Parse error */ Address.prototype.fromBase58 = function fromBase58(data) { assert(typeof data === 'string'); return this.fromRaw(base58.decode(data)); }; /** * Create an address object from a base58 address. * @param {Base58Address} address * @returns {Address} * @throws Parse error. */ Address.fromBase58 = function fromBase58(address) { return new Address().fromBase58(address); }; /** * Inject properties from output script. * @private * @param {Script} script */ Address.prototype.fromScript = function fromScript(script) { if (script.isPubkey()) { this.hash = crypto.hash160(script.get(0)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isPubkeyhash()) { this.hash = script.get(2); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthash()) { this.hash = script.get(1); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } if (script.isWitnessPubkeyhash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (script.isWitnessScripthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } if (script.isWitnessMasthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 1; return this; } // Put this last: it's the slowest to check. if (script.isMultisig()) { this.hash = script.hash160(); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Inject properties from witness. * @private * @param {Witness} witness */ Address.prototype.fromWitness = function fromWitness(witness) { // We're pretty much screwed here // since we can't get the version. if (witness.isPubkeyhashInput()) { this.hash = crypto.hash160(witness.get(1)); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (witness.isScripthashInput()) { this.hash = crypto.sha256(witness.get(witness.length - 1)); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } }; /** * Inject properties from input script. * @private * @param {Script} script */ Address.prototype.fromInputScript = function fromInputScript(script) { if (script.isPubkeyhashInput()) { this.hash = crypto.hash160(script.get(1)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthashInput()) { this.hash = crypto.hash160(script.get(script.length - 1)); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Create an Address from a witness. * Attempt to extract address * properties from a witness. * @param {Witness} * @returns {Address|null} */ Address.fromWitness = function fromWitness(witness) { return new Address().fromWitness(witness); }; /** * Create an Address from an input script. * Attempt to extract address * properties from an input script. * @param {Script} * @returns {Address|null} */ Address.fromInputScript = function fromInputScript(script) { return new Address().fromInputScript(script); }; /** * Create an Address from an output script. * Parse an output script and extract address * properties. Converts pubkey and multisig * scripts to pubkeyhash and scripthash addresses. * @param {Script} * @returns {Address|null} */ Address.fromScript = function fromScript(script) { return new Address().fromScript(script); }; /** * Inject properties from a hash. * @private * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @throws on bad hash size */ Address.prototype.fromHash = function fromHash(hash, type, version, network) { if (typeof hash === 'string') hash = new Buffer(hash, 'hex'); if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type == null) type = scriptTypes.PUBKEYHASH; if (version == null) version = -1; var Network = require('../protocol/network'); network = Network.get(network); assert(Buffer.isBuffer(hash)); assert(util.isNumber(type)); assert(util.isNumber(version)); assert(Address.getPrefix(type, network) !== -1, 'Not a valid address type.'); if (version === -1) { assert(!Address.isWitness(type), 'Wrong version (witness)'); assert(hash.length === 20, 'Hash is the wrong size.'); } else { assert(Address.isWitness(type), 'Wrong version (non-witness).'); assert(version >= 0 && version <= 16, 'Bad program version.'); if (version === 0 && type === scriptTypes.WITNESSPUBKEYHASH) assert(hash.length === 20, 'Hash is the wrong size.'); else if (version === 0 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); else if (version === 1 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); } this.hash = hash; this.type = type; this.version = version; this.network = network; return this; }; /** * Create a naked address from hash/type/version. * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromHash = function fromHash(hash, type, version, network) { return new Address().fromHash(hash, type, version, network); }; /** * Inject properties from data. * @private * @param {Buffer|Buffer[]} data * @param {AddressType} type * @param {Number} [version=-1] */ Address.prototype.fromData = function fromData(data, type, version, network) { if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type === scriptTypes.WITNESSSCRIPTHASH) { if (version === 0) { assert(Buffer.isBuffer(data)); data = crypto.sha256(data); } else if (version === 1) { assert(Array.isArray(data)); throw new Error('MASTv2 creation not implemented.'); } else { throw new Error('Cannot create from version=' + version); } } else if (type === scriptTypes.WITNESSPUBKEYHASH) { if (version !== 0) throw new Error('Cannot create from version=' + version); assert(Buffer.isBuffer(data)); data = crypto.hash160(data); } else { data = crypto.hash160(data); } return this.fromHash(data, type, version, network); }; /** * Create an Address from data/type/version. * @param {Buffer|Buffer[]} data - Data to be hashed. * Normally a buffer, but can also be an array of * buffers for MAST. * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromData = function fromData(data, type, version, network) { return new Address().fromData(data, type, version, network); }; /** * Validate an address, optionally test against a type. * @param {Base58Address} address * @param {AddressType} * @returns {Boolean} */ Address.validate = function validate(address, type) { if (!address) return false; if (!Buffer.isBuffer(address) && typeof address !== 'string') return false; try { address = Address.fromBase58(address); } catch (e) { return false; } if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type && address.type !== type) return false; return true; }; /** * Get the hex hash of a base58 * address or address object. * @param {Base58Address|Address} data * @returns {Hash|null} */ Address.getHash = function getHash(data, enc) { var hash; if (typeof data === 'string') { if (data.length === 40 || data.length === 64) return enc === 'hex' ? data : new Buffer(data, 'hex'); try { hash = Address.fromBase58(data).hash; } catch (e) { return; } } else if (Buffer.isBuffer(data)) { hash = data; } else if (data instanceof Address) { hash = data.hash; } else { return; } return enc === 'hex' ? hash.toString('hex') : hash; }; /** * Get a network address prefix for a specified address type. * @param {AddressType} type * @returns {Number} */ Address.getPrefix = function getPrefix(type, network) { var prefixes = network.addressPrefix; switch (type) { case scriptTypes.PUBKEYHASH: return prefixes.pubkeyhash; case scriptTypes.SCRIPTHASH: return prefixes.scripthash; case scriptTypes.WITNESSPUBKEYHASH: return prefixes.witnesspubkeyhash; case scriptTypes.WITNESSSCRIPTHASH: return prefixes.witnessscripthash; default: return -1; } }; /** * Get an address type for a specified network address prefix. * @param {Number} prefix * @returns {AddressType} */ Address.getType = function getType(prefix, network) { var prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: return scriptTypes.PUBKEYHASH; case prefixes.scripthash: return scriptTypes.SCRIPTHASH; case prefixes.witnesspubkeyhash: return scriptTypes.WITNESSPUBKEYHASH; case prefixes.witnessscripthash: return scriptTypes.WITNESSSCRIPTHASH; default: return -1; } }; /** * Test whether an address type is a witness program. * @param {AddressType} type * @returns {Boolean} */ Address.isWitness = function isWitness(type) { switch (type) { case scriptTypes.WITNESSPUBKEYHASH: return true; case scriptTypes.WITNESSSCRIPTHASH: return true; default: return false; } }; /* * Expose */ module.exports = Address;
decentraland/bronzeage-node
lib/primitives/address.js
JavaScript
mit
15,225
using Microsoft.EntityFrameworkCore; namespace Sample.RabbitMQ.MySql { public class Person { public int Id { get; set; } public string Name { get; set; } public override string ToString() { return $"Name:{Name}, Id:{Id}"; } } public class AppDbContext : DbContext { public const string ConnectionString = ""; public DbSet<Person> Persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql(ConnectionString, new MariaDbServerVersion(ServerVersion.AutoDetect(ConnectionString))); } } }
dotnetcore/CAP
samples/Sample.RabbitMQ.MySql/AppDbContext.cs
C#
mit
689
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. using AppBrix.Cloning.Impl; using AppBrix.Container; using AppBrix.Lifecycle; using AppBrix.Modules; using System; using System.Collections.Generic; namespace AppBrix.Cloning; /// <summary> /// A module used for registering a default object cloner. /// The object cloner is used for creating deep and shallow copies of objects. /// </summary> public sealed class CloningModule : ModuleBase { #region Properties /// <summary> /// Gets the types of the modules which are direct dependencies for the current module. /// This is used to determine the order in which the modules are loaded. /// </summary> public override IEnumerable<Type> Dependencies => new[] { typeof(ContainerModule) }; #endregion #region Public and overriden methods /// <summary> /// Initializes the module. /// Automatically called by <see cref="ModuleBase.Initialize"/> /// </summary> /// <param name="context">The initialization context.</param> protected override void Initialize(IInitializeContext context) { this.App.Container.Register(this); this.App.Container.Register(this.cloner); } /// <summary> /// Uninitializes the module. /// Automatically called by <see cref="ModuleBase.Uninitialize"/> /// </summary> protected override void Uninitialize() { } #endregion #region Private fields and constants private readonly Cloner cloner = new Cloner(); #endregion }
MarinAtanasov/AppBrix
Modules/AppBrix.Cloning/CloningModule.cs
C#
mit
1,625
// @flow declare module '@reach/portal' { declare export default React$ComponentType<{| children: React$Node, type?: string, |}>; }
flowtype/flow-typed
definitions/npm/@reach/portal_v0.2.x/flow_v0.84.x-/portal_v0.2.x.js
JavaScript
mit
145
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.InteropServices; using System.Globalization; using System.Linq.Expressions; using Mono.Linq.Expressions; namespace V { public enum Keyword : int { _TypesStart, // Types begin Void, Int, UInt, String, Float, Double, _TypesEnd, // Types end _KeywordsStart, // Keywords begin Null, Return, _KeywordsEnd, // Keywords end } public enum Symbol : int { _Null, LParen, RParen, LCurvy, RCurvy, Comma, Semicolon, Assign, } public static class KeywordExtensions { public static bool IsBetween(this Keyword K, Keyword Start, Keyword End) { return (int)K > (int)Start && (int)K < (int)End; } public static bool IsType(this Keyword K) { return K.IsBetween(Keyword._TypesStart, Keyword._TypesEnd); } } public static class TokenExtensions { public static bool IsType(this Token T) { return T.Type == TokenType.Keyword && ((Keyword)T.Id).IsType(); } public static Type ToType(this Token T) { if (!T.IsType()) throw new Exception("Token is not a type token"); Keyword K = (Keyword)T.Id; switch (K) { case Keyword.Void: return typeof(void); case Keyword.Int: return typeof(int); case Keyword.UInt: return typeof(uint); case Keyword.String: return typeof(string); case Keyword.Double: return typeof(double); case Keyword.Float: return typeof(float); default: throw new Exception("Unknown type keyword " + K); } } public static bool IsIdentifier(this Token T) { return T.Type == TokenType.Identifier; } public static bool IsSymbol(this Token T, Symbol S) { return T.Type == TokenType.Symbol && ((Symbol)T.Id) == S; } public static bool IsKeyword(this Token T, Keyword K) { return T.Type == TokenType.Keyword && ((Keyword)T.Id) == K; } } public class Parser { LexerBehavior LB; LexerSettings LS; Token[] Tokens; int Idx; public Parser() { LB = LexerBehavior.SkipComments | LexerBehavior.SkipWhiteSpaces | LexerBehavior.Default; LS = LexerSettings.Default; LS.Options = LexerOptions.StringDoubleQuote | LexerOptions.StringEscaping; LS.Keywords = new Dictionary<string, int>(); string[] KeywordNames = Enum.GetNames(typeof(Keyword)); for (int i = 0; i < KeywordNames.Length; i++) { if (KeywordNames[i].StartsWith("_")) continue; LS.Keywords.Add(KeywordNames[i].ToLower(), (int)(Keyword)Enum.Parse(typeof(Keyword), KeywordNames[i])); } LS.Symbols = new Dictionary<string, int>(); LS.Symbols.Add("(", (int)Symbol.LParen); LS.Symbols.Add(")", (int)Symbol.RParen); LS.Symbols.Add("{", (int)Symbol.LCurvy); LS.Symbols.Add("}", (int)Symbol.RCurvy); LS.Symbols.Add(",", (int)Symbol.Comma); LS.Symbols.Add(";", (int)Symbol.Semicolon); LS.Symbols.Add("=", (int)Symbol.Assign); } Token Peek(int N = 0) { if (Idx + N >= Tokens.Length) return Token.Null; return Tokens[Idx + N]; } Symbol PeekSymbol(int N = 0) { Token T = Peek(N); if (T.Type != TokenType.Symbol) return Symbol._Null; return (Symbol)T.Id; } Token Next() { Token N = Peek(); Console.WriteLine(N); Idx++; return N; } public void Parse(string Src) { Parse(new StringReader(Src)); } public void Parse(TextReader TR) { Lexer L = new Lexer(TR, LB, LS); Tokens = L.ToArray(); Idx = 0; while (Peek() != Token.Null) Next(); /*List<Expression> Program = new List<Expression>(); while (Peek() != Token.Null) Program.Add(ParseAny()); Console.WriteLine(); foreach (var E in Program) Console.WriteLine(E.ToCSharpCode());*/ } } }
cartman300/Vermin
V/Parser.cs
C#
mit
3,763
shared_context 'optoro_zookeeper' do before do Chef::Recipe.any_instance.stub(:query_role).and_return('kitchen_role') Chef::Recipe.any_instance.stub(:query_role_credentials).and_return('{ "Code" : "Success", "LastUpdated" : "2015-03-09T14:48:17Z", "Type" : "AWS-HMAC", "AccessKeyId" : "ACCESSKEY", "SecretAccessKey" : "SECRETKEY", "Token" : "TOKEN", "Expiration" : "2015-03-09T21:14:00Z" }') allow(Chef::EncryptedDataBagItem).to receive(:load).with('aws', 'aws_keys').and_return('id' => 'aws_keys', 'exhibitor_access_key_id' => 'ACCESS', 'exhibitor_secret_access_key' => 'SECRET') end end
smedefind/optoro_zookeeper
spec/helpers.rb
Ruby
mit
606
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class FlashStatus extends AbstractTag { protected $Id = 0; protected $Name = 'FlashStatus'; protected $FullName = 'Pentax::FlashInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Camera'; protected $Type = 'int8u'; protected $Writable = true; protected $Description = 'Flash Status'; protected $flag_Permanent = true; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 'Off', ), 1 => array( 'Id' => 1, 'Label' => 'Off (1)', ), 2 => array( 'Id' => 2, 'Label' => 'External, Did not fire', ), 6 => array( 'Id' => 6, 'Label' => 'External, Fired', ), 8 => array( 'Id' => 8, 'Label' => 'Internal, Did not fire (0x08)', ), 9 => array( 'Id' => 9, 'Label' => 'Internal, Did not fire', ), 13 => array( 'Id' => 13, 'Label' => 'Internal, Fired', ), ); }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/FlashStatus.php
PHP
mit
1,553
package com.merakianalytics.orianna.types.core.searchable; public abstract interface SearchableObject { public boolean contains(final Object item); }
robrua/Orianna
orianna/src/main/java/com/merakianalytics/orianna/types/core/searchable/SearchableObject.java
Java
mit
155
version https://git-lfs.github.com/spec/v1 oid sha256:90773470146a0daefafb65539bea2a9c6537067655a435ffce48433658e3d73a size 943
yogeshsaroya/new-cdnjs
ajax/libs/highlight.js/7.5/languages/actionscript.min.js
JavaScript
mit
128
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Tests * @package Tests_Functional * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ namespace Mage\Catalog\Test\Handler\CatalogAttributeSet; use Magento\Mtf\Handler\HandlerInterface; /** * Interface CatalogCategoryEntityInterface. */ interface CatalogAttributeSetInterface extends HandlerInterface { // }
fabiensebban/magento
dev/tests/functional/tests/app/Mage/Catalog/Test/Handler/CatalogAttributeSet/CatalogAttributeSetInterface.php
PHP
mit
1,196
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerregistry.v2019_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for OS. */ public final class OS extends ExpandableStringEnum<OS> { /** Static value Windows for OS. */ public static final OS WINDOWS = fromString("Windows"); /** Static value Linux for OS. */ public static final OS LINUX = fromString("Linux"); /** * Creates or finds a OS from its string representation. * @param name a name to look for * @return the corresponding OS */ @JsonCreator public static OS fromString(String name) { return fromString(name, OS.class); } /** * @return known OS values */ public static Collection<OS> values() { return values(OS.class); } }
selvasingh/azure-sdk-for-java
sdk/containerregistry/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/containerregistry/v2019_04_01/OS.java
Java
mit
1,118
package com.github.bogdanlivadariu.jenkins.reporting.testng; import hudson.model.AbstractProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Publisher; public class TestNGTestReportBuildStepDescriptor extends BuildStepDescriptor<Publisher> { @Override public String getDisplayName() { return "Publish TestNG reports generated with handlebars"; } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } }
BogdanLivadariu/bootstraped-multi-test-results-report
bootstraped-multi-test-results-report/src/main/java/com/github/bogdanlivadariu/jenkins/reporting/testng/TestNGTestReportBuildStepDescriptor.java
Java
mit
507
using System; using System.Diagnostics; using Aspose.Email.Mail; namespace Aspose.Email.Examples.CSharp.Email.SMTP { class SendingEMLFilesWithSMTP { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_SMTP(); string dstEmail = dataDir + "Message.eml"; // Create an instance of the MailMessage class MailMessage message = new MailMessage(); // Import from EML format message = MailMessage.Load(dstEmail, new EmlLoadOptions()); // Create an instance of SmtpClient class SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "your.email@gmail.com", "your.password"); client.SecurityOptions = SecurityOptions.Auto; try { // Client.Send will send this message client.Send(message); Console.WriteLine("Message sent"); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Email sent using EML file successfully. " + dstEmail); } } }
jawadaspose/Aspose.Email-for-.NET
Examples/CSharp/SMTP/SendingEMLFilesWithSMTP.cs
C#
mit
1,239
<?php namespace Mongrate\Tests\Command; use Mongrate\Command\TestMigrationCommand; use Mongrate\Enum\DirectionEnum; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; class TestMigrationCommandTest extends BaseCommandTest { public function testExecute_upAndDown() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute(['command' => $command->getName(), 'name' => 'UpdateAddressStructure']); $this->assertEquals( "Testing UpdateAddressStructure going up.\n" . "Test passed.\n" . "Testing UpdateAddressStructure going down.\n" . "Test passed.\n", $commandTester->getDisplay() ); } public function testExecute_up() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'UpdateAddressStructure', 'direction' => DirectionEnum::UP]); $this->assertEquals( "Testing UpdateAddressStructure going up.\n" . "Test passed.\n", $commandTester->getDisplay() ); } public function testExecute_down() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'UpdateAddressStructure', 'direction' => DirectionEnum::DOWN]); $this->assertEquals( "Testing UpdateAddressStructure going down.\n" . "Test passed.\n", $commandTester->getDisplay() ); } /** * @expectedException Mongrate\Exception\MigrationDoesntExist * @expectedExceptionMessage There is no migration called "Elvis" in "resources/examples/Elvis/Migration.php" */ public function testExecute_migrationDoesntExist() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'name' => 'Elvis']); } public function testExecute_hasMongoObjectsInYml() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'DeleteOldLogs', 'direction' => DirectionEnum::UP]); $this->assertEquals( "Testing DeleteOldLogs going up.\n" . "Test passed.\n", $commandTester->getDisplay() ); } }
BernardoSilva/mongrate
test/Mongrate/Tests/Command/TestMigrationCommandTest.php
PHP
mit
3,547
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ declare(strict_types=1); namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator; use ProxyManager\Generator\MethodGenerator; use ProxyManager\ProxyGenerator\Util\Properties; use ReflectionClass; use ReflectionProperty; /** * The `staticProxyConstructor` implementation for null object proxies * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class StaticProxyConstructor extends MethodGenerator { /** * Constructor * * @param ReflectionClass $originalClass Reflection of the class to proxy * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ public function __construct(ReflectionClass $originalClass) { parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC); $nullableProperties = array_map( function (ReflectionProperty $publicProperty) : string { return '$instance->' . $publicProperty->getName() . ' = null;'; }, Properties::fromReflectionClass($originalClass)->getPublicProperties() ); $this->setDocBlock('Constructor for null object initialization'); $this->setBody( 'static $reflection;' . "\n\n" . '$reflection = $reflection ?: $reflection = new \ReflectionClass(__CLASS__);' . "\n" . '$instance = (new \ReflectionClass(get_class()))->newInstanceWithoutConstructor();' . "\n\n" . ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '') . 'return $instance;' ); } }
rainlike/justshop
vendor/ocramius/proxy-manager/src/ProxyManager/ProxyGenerator/NullObject/MethodGenerator/StaticProxyConstructor.php
PHP
mit
2,514
/** * Copyright (C) 2016 by Johan von Forstner under the MIT license: * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.geeksfactory.opacclient.objects; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Represents a copy of a medium ({@link DetailedItem}) available in a library. */ public class Copy { private String barcode; private String location; private String department; private String branch; private String issue; private String status; private LocalDate returnDate; private String reservations; private String shelfmark; private String resInfo; private String url; /** * @return The barcode of a copy. Optional. */ public String getBarcode() { return barcode; } /** * @param barcode The barcode of a copy. Optional. */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * @return The location (like "third floor") of a copy. Optional. */ public String getLocation() { return location; } /** * @param location The location (like "third floor") of a copy. Optional. */ public void setLocation(String location) { this.location = location; } /** * @return The department (like "music library") of a copy. Optional. */ public String getDepartment() { return department; } /** * @param department The department (like "music library") of a copy. Optional. */ public void setDepartment(String department) { this.department = department; } /** * @return The branch a copy is in. Should be set, if your library has more than one branch. */ public String getBranch() { return branch; } /** * @param branch The branch a copy is in. Should be set, if your library has more than one * branch. */ public void setBranch(String branch) { this.branch = branch; } /** * @return The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public String getIssue() { return issue; } /** * @param issue The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public void setIssue(String issue) { this.issue = issue; } /** * @return Current status of a copy ("lent", "free", ...). Should be set. */ public String getStatus() { return status; } /** * @param status Current status of a copy ("lent", "free", ...). Should be set. */ public void setStatus(String status) { this.status = status; } /** * @return Expected date of return if a copy is lent out. Optional. */ public LocalDate getReturnDate() { return returnDate; } /** * @param returndate Expected date of return if a copy is lent out. Optional. */ public void setReturnDate(LocalDate returndate) { this.returnDate = returndate; } /** * @return Number of pending reservations if a copy is currently lent out. Optional. */ public String getReservations() { return reservations; } /** * @param reservations Number of pending reservations if a copy is currently lent out. * Optional. */ public void setReservations(String reservations) { this.reservations = reservations; } /** * @return Identification in the libraries' shelf system. Optional. */ public String getShelfmark() { return shelfmark; } /** * @param shelfmark Identification in the libraries' shelf system. Optional. */ public void setShelfmark(String shelfmark) { this.shelfmark = shelfmark; } /** * @return Reservation information for copy-based reservations. Intended for use in your {@link * de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)} * implementation. */ public String getResInfo() { return resInfo; } /** * @param resInfo Reservation information for copy-based reservations. Intended for use in your * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation (DetailedItem, * Account, int, String)} implementation. */ public void setResInfo(String resInfo) { this.resInfo = resInfo; } /** * @return URL to an online copy */ public String getUrl() { return url; } /** * @param url URL to an online copy */ public void setUrl(String url) { this.url = url; } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in ISO-8601 format (yyyy-MM-dd). */ public void set(String key, String value) { switch (key) { case "barcode": setBarcode(value); break; case "location": setLocation(value); break; case "department": setDepartment(value); break; case "branch": setBranch(value); break; case "status": setStatus(value); break; case "returndate": setReturnDate(new LocalDate(value)); break; case "reservations": setReservations(value); break; case "signature": setShelfmark(value); break; case "resinfo": setResInfo(value); break; case "url": setUrl(value); break; default: throw new IllegalArgumentException("key unknown"); } } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * For "returndate", the given {@link DateTimeFormatter} will be used to parse the date. * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in a format parseable by the given {@link * DateTimeFormatter}, otherwise an {@link IllegalArgumentException} will be * thrown. * @param fmt the {@link DateTimeFormatter} to use for parsing dates */ public void set(String key, String value, DateTimeFormatter fmt) { if (key.equals("returndate")) { if (!value.isEmpty()) { setReturnDate(fmt.parseLocalDate(value)); } } else { set(key, value); } } /** * Get property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * Dates will be returned in ISO-8601 format (yyyy-MM-dd). If you supply an invalid key, an * {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above */ public String get(String key) { switch (key) { case "barcode": return getBarcode(); case "location": return getLocation(); case "department": return getDepartment(); case "branch": return getBranch(); case "status": return getStatus(); case "returndate": return getReturnDate() != null ? ISODateTimeFormat.date().print(getReturnDate()) : null; case "reservations": return getReservations(); case "signature": return getShelfmark(); case "resinfo": return getResInfo(); case "url": return getUrl(); default: throw new IllegalArgumentException("key unknown"); } } /** * @return boolean value indicating if this copy contains any data or not. */ public boolean notEmpty() { return getBarcode() != null || getLocation() != null || getDepartment() != null || getBranch() != null || getStatus() != null || getReturnDate() != null || getReservations() != null || getShelfmark() != null || getResInfo() != null || getIssue() != null || getUrl() != null; } @Override public String toString() { return "Copy{" + "barcode='" + barcode + '\'' + ", location='" + location + '\'' + ", department='" + department + '\'' + ", branch='" + branch + '\'' + ", status='" + status + '\'' + ", returnDate=" + returnDate + ", reservations='" + reservations + '\'' + ", shelfmark='" + shelfmark + '\'' + ", issue='" + issue + '\'' + ", resInfo='" + resInfo + '\'' + ", url='" + url + '\'' + '}'; } }
johan12345/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/objects/Copy.java
Java
mit
11,432
package id.birokrazy.model; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Type; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import javax.persistence.*; import java.util.List; /** * @author Arthur Purnama (arthur@purnama.de) */ @Entity @Indexed public class Department { @Id @GeneratedValue private Long id; @Version @Column(columnDefinition = "bigint default 0") private Long version; @Column(nullable = false, unique = true) private String uniqueName; @Column(nullable = false) @Field private String name; @Column private String description; @Column() @Type(type = "text") private String content; @Column(nullable = false) private Double rating; @Column(nullable = false) private Long reviews; @Column(nullable = false) private String address; @Column private String addressAdd; @Column private String district; @Column(nullable = false) private String zipCode; @Column(nullable = false) private String city; @Column(nullable = false) private String state; @Column private String telephone; @Column private String email; @Column private String openingHour; @Column private String longitude; @Column private String latitude; @OneToMany(mappedBy = "department") @OrderBy("id desc") @JsonIgnore private List<Review> reviewList; @ManyToMany(mappedBy = "departmentList") @OrderBy("id desc") @JsonIgnore private List<CivilService> civilServiceList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public Long getReviews() { return reviews; } public void setReviews(Long reviews) { this.reviews = reviews; } public List<Review> getReviewList() { return reviewList; } public void setReviewList(List<Review> reviewList) { this.reviewList = reviewList; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddressAdd() { return addressAdd; } public void setAddressAdd(String addressAdd) { this.addressAdd = addressAdd; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public List<CivilService> getCivilServiceList() { return civilServiceList; } public void setCivilServiceList(List<CivilService> civilServiceList) { this.civilServiceList = civilServiceList; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getOpeningHour() { return openingHour; } public void setOpeningHour(String openingHour) { this.openingHour = openingHour; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUniqueName() { return uniqueName; } public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } @Field public String getLocation() { return address + " " + addressAdd + " " + district + " " + city + " " + state + " " + zipCode; } @Field public String getLocationName() { return district + ", " + city + " (" + zipCode + "), " + state; } }
purnama/birokrazy
src/main/java/id/birokrazy/model/Department.java
Java
mit
5,175
/* The MIT License (MIT) Copyright (c) IIIT-DELHI authors: HEMANT JAIN "hjcooljohny75@gmail.com" ANIRUDH NAIN 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. * */ //To define all the properties needed to make the rdf of the email package check.email; import com.hp.hpl.jena.rdf.model.*; public class EMAILRDF { //Create a default model private static Model m = ModelFactory.createDefaultModel(); //Subject of the mail public static final Property MSGID = m.createProperty("MESSAGEID:" ); public static final Property MAILID = m.createProperty("MAILID:" ); public static final Property SUBJECT = m.createProperty("SUB:" ); //Sender of the mail public static final Property FROM = m.createProperty("FROM:" ); public static final Property FROMFULL = m.createProperty("FROMFULL:" ); public static final Property TOFULL = m.createProperty("TOFULL:" ); public static final Property EMAILID = m.createProperty("EMAILID:" ); //Receiver of the mail public static final Property TO = m.createProperty("TO:" ); //Return path public static final Property RETURN_PATH = m.createProperty("RETURNPATH:" ); //main contents of the mail public static final Property CONTENT = m.createProperty("CONTENT:" ); //format of the mail public static final Property FORMAT = m.createProperty("FORMAT:" ); //content type like html etc public static final Property CONTENT_TYPE = m.createProperty("CONTENTTYPE:" ); //encoding in bits public static final Property ENCODING = m.createProperty("ENCODING:" ); //date of the email public static final Property DATE = m.createProperty("DATE:" ); //CC of email public static final Property CC = m.createProperty("CC:" ); //BCC of email public static final Property BCC = m.createProperty("BCC:" ); //NAME OF THE SENDER public static final Property ATTACHEMENT_NAME = m.createProperty("ATTACHEMENTNAME:" ); public static final Property ATTACHEMENT_NO = m.createProperty("ATTACHEMENTNO:" ); //SIZE OF MAIL public static final Property MAIL_SIZE = m.createProperty("MAILSIZE:" ); //SIZE OF THE ATTACHEMENT of email public static final Property ATTACHEMENT_SIZE = m.createProperty("ATTACHEMENTSIZE:" ); //MAIL TO WHICH PARTICULAR MAIL HAVE REPLIED public static final Property IN_REPLYTO = m.createProperty("REPLIEDTO:" ); public static final Property IN_REPLYTONAME = m.createProperty("REPLIEDTONAME:" ); //FOLDER IN WHICH email EXISTS public static final Property FOLDER_NAME = m.createProperty("FOLDERNAME:" ); //UID of email public static final Property UID = m.createProperty("UID:" ); //name os receiver of email public static final Property REC_NAME = m.createProperty("RECIEVERS_NAME:" ); //name of sender of email public static final Property SEND_NAME = m.createProperty("SENDERNAME:" ); }
COOLHEMANTJAIN/MAILDETECTIVE
maildetective1.0/src/check/email/EMAILRDF.java
Java
mit
3,829
import argparse import os import sys import numpy as np from PIL import Image import chainer from chainer import cuda import chainer.functions as F from chainer.functions import caffe from chainer import Variable, optimizers import pickle def subtract_mean(x0): x = x0.copy() x[0,0,:,:] -= 104 x[0,1,:,:] -= 117 x[0,2,:,:] -= 123 return x def add_mean(x0): x = x0.copy() x[0,0,:,:] += 104 x[0,1,:,:] += 117 x[0,2,:,:] += 123 return x def image_resize(img_file, width): gogh = Image.open(img_file) orig_w, orig_h = gogh.size[0], gogh.size[1] if orig_w>orig_h: new_w = width new_h = width*orig_h/orig_w gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,width-new_h:,:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) else: new_w = width*orig_w/orig_h new_h = width gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,:,width-new_w:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) return xp.asarray(gogh), new_w, new_h def save_image(img, width, new_w, new_h, it): def to_img(x): im = np.zeros((new_h,new_w,3)) im[:,:,0] = x[2,:,:] im[:,:,1] = x[1,:,:] im[:,:,2] = x[0,:,:] def clip(a): return 0 if a<0 else (255 if a>255 else a) im = np.vectorize(clip)(im).astype(np.uint8) Image.fromarray(im).save(args.out_dir+"/im_%05d.png"%it) if args.gpu>=0: img_cpu = add_mean(img.get()) else: img_cpu = add_mean(img) if width==new_w: to_img(img_cpu[0,:,width-new_h:,:]) else: to_img(img_cpu[0,:,:,width-new_w:]) def nin_forward(x): y0 = F.relu(model.conv1(x)) y1 = model.cccp2(F.relu(model.cccp1(y0))) x1 = F.relu(model.conv2(F.average_pooling_2d(F.relu(y1), 3, stride=2))) y2 = model.cccp4(F.relu(model.cccp3(x1))) x2 = F.relu(model.conv3(F.average_pooling_2d(F.relu(y2), 3, stride=2))) y3 = model.cccp6(F.relu(model.cccp5(x2))) x3 = F.relu(getattr(model,"conv4-1024")(F.dropout(F.average_pooling_2d(F.relu(y3), 3, stride=2), train=False))) return [y0,x1,x2,x3] def vgg_forward(x): y1 = model.conv1_2(F.relu(model.conv1_1(x))) x1 = F.average_pooling_2d(F.relu(y1), 2, stride=2) y2 = model.conv2_2(F.relu(model.conv2_1(x1))) x2 = F.average_pooling_2d(F.relu(y2), 2, stride=2) y3 = model.conv3_3(F.relu(model.conv3_2(F.relu(model.conv3_1(x2))))) x3 = F.average_pooling_2d(F.relu(y3), 2, stride=2) y4 = model.conv4_3(F.relu(model.conv4_2(F.relu(model.conv4_1(x3))))) # x4 = F.average_pooling_2d(F.relu(y4), 2, stride=2) # y5 = model.conv5_3(F.relu(model.conv5_2(F.relu(model.conv5_1(x4))))) return [y1,y2,y3,y4] def get_matrix(y): ch = y.data.shape[1] wd = y.data.shape[2] gogh_y = F.reshape(y, (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) return gogh_matrix class Clip(chainer.Function): def forward(self, x): x = x[0] ret = cuda.elementwise( 'T x','T ret', ''' ret = x<-100?-100:(x>100?100:x); ''','clip')(x) return ret def generate_image(img_orig, img_style, width, nw, nh, max_iter, lr, alpha, beta, img_gen=None): mid_orig = nin_forward(Variable(img_orig)) style_mats = [get_matrix(y) for y in nin_forward(Variable(img_style))] if img_gen is None: if args.gpu >= 0: img_gen = xp.random.uniform(-20,20,(1,3,width,width),dtype=np.float32) else: img_gen = np.random.uniform(-20,20,(1,3,width,width)).astype(np.float32) x = Variable(img_gen) xg = xp.zeros_like(x.data) optimizer = optimizers.Adam(alpha=lr) optimizer.setup((img_gen,xg)) for i in range(max_iter): x = Variable(img_gen) y = nin_forward(x) optimizer.zero_grads() L = Variable(xp.zeros((), dtype=np.float32)) for l in range(4): ch = y[l].data.shape[1] wd = y[l].data.shape[2] gogh_y = F.reshape(y[l], (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) L1 = np.float32(alpha[l])*F.mean_squared_error(y[l], Variable(mid_orig[l].data)) L2 = np.float32(beta[l])*F.mean_squared_error(gogh_matrix, Variable(style_mats[l].data))/np.float32(4) L += L1+L2 if i%100==0: print i,l,L1.data,L2.data L.backward() xg += x.grad optimizer.update() tmp_shape = img_gen.shape if args.gpu >= 0: img_gen += Clip().forward(img_gen).reshape(tmp_shape) - img_gen else: def clip(x): return -100 if x<-100 else (100 if x>100 else x) img_gen += np.vectorize(clip)(img_gen).reshape(tmp_shape) - img_gen if i%50==0: save_image(img_gen, W, nw, nh, i) parser = argparse.ArgumentParser( description='A Neural Algorithm of Artistic Style') parser.add_argument('--model', '-m', default='nin_imagenet.caffemodel', help='model file') parser.add_argument('--orig_img', '-i', default='orig.png', help='Original image') parser.add_argument('--style_img', '-s', default='style.png', help='Style image') parser.add_argument('--out_dir', '-o', default='output', help='Output directory') parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)') parser.add_argument('--iter', default=5000, type=int, help='number of iteration') parser.add_argument('--lr', default=4.0, type=float, help='learning rate') parser.add_argument('--lam', default=0.005, type=float, help='original image weight / style weight ratio') parser.add_argument('--width', '-w', default=435, type=int, help='image width, height') args = parser.parse_args() try: os.mkdir(args.out_dir) except: pass if args.gpu >= 0: cuda.check_cuda_available() cuda.get_device(args.gpu).use() xp = cuda.cupy else: xp = np chainer.Function.type_check_enable = False print "load model... %s"%args.model func = caffe.CaffeFunction(args.model) model = func.fs if args.gpu>=0: model.to_gpu() W = args.width img_gogh,_,_ = image_resize(args.style_img, W) img_hongo,nw,nh = image_resize(args.orig_img, W) generate_image(img_hongo, img_gogh, W, nw, nh, img_gen=None, max_iter=args.iter, lr=args.lr, alpha=[args.lam * x for x in [0,0,1,1]], beta=[1,1,1,1])
wf9a5m75/chainer-gogh
chainer-gogh.py
Python
mit
7,054
App.SubmissionsResponseController = Ember.ObjectController.extend({ actions: { saveNotes: function() { var onSuccess = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box'>Your notes were saved!<a class='close'>&times;</a></div>"); }; var onFail = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box alert'>Uh oh! Something went wrong...<a class='close'>&times;</a></div>"); }; var model = this.get('model'); model.save().then(onSuccess, onFail); return model; } } });
andrewjadams3/Klassewerk
app/assets/javascripts/controllers/submissions_response_controller.js
JavaScript
mit
648
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\App\Test\Unit; use \Magento\Framework\App\SetupInfo; class SetupInfoTest extends \PHPUnit_Framework_TestCase { /** * A default fixture * * @var array */ private static $fixture = ['DOCUMENT_ROOT' => '/doc/root', 'SCRIPT_FILENAME' => '/doc/root/dir/file.php']; /** * @param array $server * @param string $expectedError * @dataProvider constructorExceptionsDataProvider */ public function testConstructorExceptions($server, $expectedError) { $this->setExpectedException('\InvalidArgumentException', $expectedError); new SetupInfo($server); } public function constructorExceptionsDataProvider() { $docRootErr = 'DOCUMENT_ROOT variable is unavailable.'; $projectRootErr = 'Project root cannot be automatically detected.'; return [ [[], $docRootErr], [['DOCUMENT_ROOT' => ''], $docRootErr], [['DOCUMENT_ROOT' => '/foo'], $projectRootErr], [['DOCUMENT_ROOT' => '/foo', 'SCRIPT_FILENAME' => ''], $projectRootErr], ]; } /** * @param array $server * @param string $expected * @dataProvider getUrlDataProvider */ public function testGetUrl($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getUrl()); } /** * @return array */ public function getUrlDataProvider() { return [ [ self::$fixture, '/setup/' ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'install'], '/install/', ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL => 'http://example.com/'], 'http://example.com/', ], ]; } /** * @param array $server * @param string $expected * @dataProvider getProjectUrlDataProvider */ public function testGetProjectUrl($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getProjectUrl()); } /** * @return array */ public function getProjectUrlDataProvider() { return [ [self::$fixture, ''], [self::$fixture + ['HTTP_HOST' => ''], ''], [ ['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/other/baz.php', 'HTTP_HOST' => 'example.com'], 'http://example.com/' ], [self::$fixture + ['HTTP_HOST' => 'example.com'], 'http://example.com/dir/'], [ ['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/foo/bar/baz.php', 'HTTP_HOST' => 'example.com'], 'http://example.com/' ], ]; } /** * @param array $server * @param string $projectRoot * @param string $expected * @dataProvider getDirDataProvider */ public function testGetDir($server, $projectRoot, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getDir($projectRoot)); } /** * @return array */ public function getDirDataProvider() { return [ [ self::$fixture, '/test/root', '/test/root/setup', ], [ self::$fixture, '/test/root/', '/test/root/setup', ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '/install/'], '/test/', '/test/install', ], ]; } /** * @param array $server * @param bool $expected * @dataProvider isAvailableDataProvider */ public function testIsAvailable($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->isAvailable()); } /** * @return array */ public function isAvailableDataProvider() { $server = ['DOCUMENT_ROOT' => __DIR__, 'SCRIPT_FILENAME' => __FILE__]; return [ 'root = doc root, but no "setup" sub-directory' => [ $server, // it will look for "setup/" sub-directory, but won't find anything false ], 'root = doc root, nonexistent sub-directory' => [ $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'nonexistent'], false ], 'root = doc root, existent sub-directory' => [ $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files'], true ], 'root within doc root, existent sub-directory' => [ [ 'DOCUMENT_ROOT' => dirname(__DIR__), 'SCRIPT_FILENAME' => __FILE__, SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files' ], true ], 'root outside of doc root, existent sub-directory' => [ [ 'DOCUMENT_ROOT' => __DIR__, 'SCRIPT_FILENAME' => dirname(dirname(__DIR__)) . '/foo.php', SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => basename(__DIR__) ], false ], 'root within doc root, existent sub-directory, trailing slash' => [ [ 'DOCUMENT_ROOT' => dirname(__DIR__) . DIRECTORY_SEPARATOR, 'SCRIPT_FILENAME' => __FILE__, SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files' ], true ], ]; } }
j-froehlich/magento2_wk
vendor/magento/framework/App/Test/Unit/SetupInfoTest.php
PHP
mit
5,963
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Views extends Application { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/ * - or - * http://example.com/welcome/index * * So any other public methods not prefixed with an underscore will * map to /welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->data['pagetitle'] = 'Ordered TODO List'; $tasks = $this->tasks->all(); // get all the tasks $this->data['content'] = 'Ok'; // so we don't need pagebody $this->data['leftside'] = $this->makePrioritizedPanel($tasks); $this->data['rightside'] = $this->makeCategorizedPanel($tasks); $this->render('template_secondary'); } function makePrioritizedPanel($tasks) { $parms = ['display_tasks' => []]; // extract the undone tasks foreach ($tasks as $task) { if ($task->status != 2) $undone[] = $task; } // order them by priority usort($undone, "orderByPriority"); // substitute the priority name foreach ($undone as $task) $task->priority = $this->app->priority($task->priority); foreach ($undone as $task) $converted[] = (array) $task; // and then pass them on $parms = ['display_tasks' => $converted]; // INSERT the next two lines $role = $this->session->userdata('userrole'); $parms['completer'] = ($role == ROLE_OWNER) ? '/views/complete' : '#'; return $this->parser->parse('by_priority', $parms, true); } function makeCategorizedPanel($tasks) { $parms = ['display_tasks' => $this->tasks->getCategorizedTasks()]; return $this->parser->parse('by_category', $parms, true); } // complete flagged items function complete() { $role = $this->session->userdata('userrole'); if ($role != ROLE_OWNER) redirect('/work'); // loop over the post fields, looking for flagged tasks foreach ($this->input->post() as $key => $value) { if (substr($key, 0, 4) == 'task') { // find the associated task $taskid = substr($key, 4); $task = $this->tasks->get($taskid); $task->status = 2; // complete $this->tasks->update($task); } } $this->index(); } } // return -1, 0, or 1 of $a's priority is higher, equal to, or lower than $b's function orderByPriority($a, $b) { if ($a->priority > $b->priority) return -1; elseif ($a->priority < $b->priority) return 1; else return 0; } ?>
MVC-todo-list/starter-todo4
application/controllers/Views.php
PHP
mit
2,696
'use strict'; const helpers = require('../../../src/helpers'); const assert = require('assert'); const arghun = require('../../../'); const opt = { blDir: ['even-more', 'crap', 'A-characters'] }; const expected = { './test/testData/testDirectory/B-characters': 6, './test/testData/testDirectory/B-characters/more-B': 3, './test/testData/testDirectory/B-characters/more-B/inside-B': 2, './test/testData/testDirectory/B-characters/more-B/inside-B/custom': 4, './test/testData/testDirectory/B-characters/my-man': 1, './test/testData/testDirectory/C-characters': 6, './test/testData/testDirectory/C-characters/my-man': 2, './test/testData/testDirectory/D-characters': 7, './test/testData/testDirectory/D-characters/more-and-more-D': 6, './test/testData/testDirectory/D-characters/my-man': 1, './test/testData/testDirectory/E-characters': 12, './test/testData/testDirectory/F-characters': 5, './test/testData/testDirectory/F-characters/moremoremore': 3, './test/testData/testDirectory/F-characters/my-man': 1, './test/testData/testDirectory/G-characters': 7 }; async function walkDirBlacklistDirs(path) { try { const result = await arghun.walkDir(path, opt); assert.deepEqual(result, expected, 'walkDir failed with dirs blacklist'); helpers.log('walkDir with dirs blacklist - successful'); } catch(err) { helpers.log(err); throw new Error(err); } } module.exports = walkDirBlacklistDirs;
derberg/zlicz
test/testCases/walkDir/walkDirBlacklistDirs.js
JavaScript
mit
1,491
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller) { controller.set('setupRoutes', [ { label: false, links: [ { href: 'heatmap.index', text: 'Setup' }, { href: 'heatmap.properties', text: 'Properties' }, { href: 'heatmap.marker', text: 'Heatmap Marker' } ] } ]); } });
Matt-Jensen/ember-cli-g-maps
tests/dummy/app/pods/heatmap/route.js
JavaScript
mit
499
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if DIRECTX11_1 namespace SharpDX.WIC { public partial class ImageEncoder { /// <summary> /// Creates a new image encoder object. /// </summary> /// <param name="factory">The WIC factory.</param> /// <param name="d2dDevice">The <see cref="Direct2D1.Device" /> object on which the corresponding image encoder is created.</param> /// <msdn-id>hh880849</msdn-id> /// <unmanaged>HRESULT IWICImagingFactory2::CreateImageEncoder([In] ID2D1Device* pD2DDevice,[In] IWICImageEncoder** ppWICImageEncoder)</unmanaged> /// <unmanaged-short>IWICImagingFactory2::CreateImageEncoder</unmanaged-short> public ImageEncoder(ImagingFactory2 factory, Direct2D1.Device d2dDevice) { factory.CreateImageEncoder(d2dDevice, this); } } } #endif
wyrover/SharpDX
Source/SharpDX.Direct2D1/WIC/ImageEncoder.cs
C#
mit
1,969
#include "StdAfx.h" #include "ComponentsList.h" #include "dotNetInstallerDlg.h" CComponentsList::CComponentsList() : m_pConfiguration(NULL) , m_pExecuteCallback(NULL) { } IMPLEMENT_DYNAMIC(CComponentsList, CCheckListBox) BEGIN_MESSAGE_MAP(CComponentsList, CCheckListBox) ON_CONTROL_REFLECT(CLBN_CHKCHANGE, OnCheckChange) ON_WM_LBUTTONDBLCLK() END_MESSAGE_MAP() void CComponentsList::OnCheckChange() { this->Invalidate(); } void CComponentsList::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC); if (((LONG)(lpDrawItemStruct->itemID) >= 0) && (lpDrawItemStruct->itemAction & (ODA_DRAWENTIRE | ODA_SELECT))) { int cyItem = GetItemHeight(lpDrawItemStruct->itemID); BOOL fDisabled = !IsWindowEnabled() || !IsEnabled(lpDrawItemStruct->itemID); COLORREF newTextColor = fDisabled ? RGB(0, 0, 0) : GetSysColor(COLOR_WINDOWTEXT); // light gray COLORREF oldTextColor = pDC->SetTextColor(newTextColor); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); COLORREF oldBkColor = pDC->SetBkColor(newBkColor); if (newTextColor == newBkColor) newTextColor = RGB(0xC0, 0xC0, 0xC0); // dark gray if (!fDisabled && ((lpDrawItemStruct->itemState & ODS_SELECTED) != 0)) { pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT)); pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT)); } if (m_cyText == 0) VERIFY(cyItem >= CalcMinimumItemHeight()); CString strText; GetText(lpDrawItemStruct->itemID, strText); pDC->ExtTextOut(lpDrawItemStruct->rcItem.left + 5, lpDrawItemStruct->rcItem.top + max(0, (cyItem - m_cyText) / 2), ETO_OPAQUE, &(lpDrawItemStruct->rcItem), strText, strText.GetLength(), NULL); int nCheck = GetCheck(lpDrawItemStruct->itemID); if (fDisabled && nCheck == 0) { CRect checkbox(0, lpDrawItemStruct->rcItem.top, lpDrawItemStruct->rcItem.left, lpDrawItemStruct->rcItem.bottom); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); CBrush brush(newBkColor); pDC->FillRect(& checkbox, & brush); } pDC->SetTextColor(oldTextColor); pDC->SetBkColor(oldBkColor); } if ((lpDrawItemStruct->itemAction & ODA_FOCUS) != 0) pDC->DrawFocusRect(&(lpDrawItemStruct->rcItem)); } void CComponentsList::PreDrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CCheckListBox::PreDrawItem(lpDrawItemStruct); } void CComponentsList::AddComponent(const ComponentPtr& component) { int id = AddString(component->description.c_str()); SetItemDataPtr(id, get(component)); if (component->checked) SetCheck(id, 1); if (component->disabled) Enable(id, 0); CDC * pDC = GetDC(); ASSERT(pDC); CSize size = pDC->GetTextExtent(component->GetDisplayName().c_str()); if ((size.cx > 0) && (GetHorizontalExtent() < size.cx)) { SetHorizontalExtent(size.cx); } ReleaseDC(pDC); } void CComponentsList::OnLButtonDblClk(UINT nFlags, CPoint point) { if (nFlags & MK_CONTROL && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); Exec(component); if (m_pExecuteCallback) { m_pExecuteCallback->LoadComponentsList(false); } } } else if (nFlags & MK_SHIFT && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); SetCheck(uiItem, ! GetCheck(uiItem)); } } } void CComponentsList::Exec(const ComponentPtr& component) { try { if (m_pExecuteCallback) { m_pExecuteCallback->OnExecBegin(); } LOG(L"--- Component '" << component->id << L"' (" << component->GetDisplayName() << L"): EXECUTING"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecBegin(component)) return; component->Exec(); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecWait(component)) return; component->Wait(); LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): SUCCESS"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecSuccess(component)) return; } catch(std::exception& ex) { LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): ERROR - " << DVLib::string2wstring(ex.what())); DniMessageBox::Show(DVLib::string2wstring(ex.what()).c_str(), MB_OK | MB_ICONSTOP); } } void CComponentsList::SetExecuteCallback(CdotNetInstallerDlg * pExec) { m_pExecuteCallback = pExec; } void CComponentsList::Load(InstallConfiguration * pConfiguration) { m_pConfiguration = pConfiguration; }
dblock/dotnetinstaller
dotNetInstaller/ComponentsList.cpp
C++
mit
5,456
/* * Copyright (c) 2012 Maciej Walkowiak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pl.maciejwalkowiak.plist.handler; import pl.maciejwalkowiak.plist.PlistSerializerImpl; import pl.maciejwalkowiak.plist.XMLHelper; import java.util.Map; /** * @author Maciej Walkowiak */ public class MapHandler extends AbstractHandler { public MapHandler(PlistSerializerImpl plistSerializer) { super(plistSerializer); } @Override String doHandle(Object object) { Map<String, Object> map = (Map<String, Object>) object; StringBuilder result = new StringBuilder(); for (Map.Entry<String, Object> entry : map.entrySet()) { result.append(XMLHelper.wrap(plistSerializer.getNamingStrategy().fieldNameToKey(entry.getKey())).with("key")); result.append(plistSerializer.serialize(entry.getValue())); } return XMLHelper.wrap(result).with("dict"); } public boolean supports(Object object) { return object instanceof Map; } }
bugix/java-plist-serializer
src/main/java/pl/maciejwalkowiak/plist/handler/MapHandler.java
Java
mit
1,980
package org.deviceconnect.android.libmedia.streaming.mpeg2ts; /** * フレームのタイプを定義します. */ enum FrameType { /** * 音声のフレームタイプを定義. */ AUDIO, /** * 映像のフレームタイプを定義. */ VIDEO, /** * 音声と映像の混合のフレームタイプを定義. */ MIXED }
DeviceConnect/DeviceConnect-Android
dConnectSDK/dConnectLibStreaming/libmedia/src/main/java/org/deviceconnect/android/libmedia/streaming/mpeg2ts/FrameType.java
Java
mit
380
package mariculture.core.helpers; import java.util.Random; import mariculture.core.tile.base.TileMultiBlock; import mariculture.core.util.Fluids; import mariculture.core.util.IItemDropBlacklist; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; public class BlockHelper { public static boolean isWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.water; } public static boolean isHPWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Fluids.getFluidBlock("hp_water"); } public static boolean isLava(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.lava; } public static boolean isFishLiveable(World world, int x, int y, int z) { if (world.provider.isHellWorld) return isLava(world, x, y, z); return isWater(world, x, y, z); } public static boolean isFishable(World world, int x, int y, int z) { return isWater(world, x, y, z) || isLava(world, x, y, z) && world.provider.isHellWorld; } public static boolean isAir(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.isAirBlock(x, y, z); } catch (Exception e) {} } return false; } public static void setBlock(World world, int x, int y, int z, Block block, int meta) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { world.setBlock(x, y, z, block, meta, 3); } catch (Exception e) {} } } public static Block getBlock(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlock(x, y, z); } catch (Exception e) {} } return Blocks.stone; } public static int getMeta(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlockMetadata(x, y, z); } catch (Exception e) {} } return -1; } public static boolean chunkExists(World world, int x, int z) { return world.getChunkProvider().chunkExists(x >> 4, z >> 4); } public static String getName(ItemStack stack) { return stack != null ? stack.getItem().getItemStackDisplayName(stack) : ""; } public static String getName(TileEntity tile) { return tile != null ? getName(new ItemStack(tile.getBlockType(), 1, tile.getBlockMetadata())) : ""; } public static ForgeDirection rotate(ForgeDirection dir, int num) { if (dir == ForgeDirection.NORTH) return ForgeDirection.EAST; if (dir == ForgeDirection.EAST) return num == 2 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; if (dir == ForgeDirection.SOUTH) return ForgeDirection.WEST; if (dir == ForgeDirection.WEST) return num == 6 ? ForgeDirection.UP : ForgeDirection.NORTH; if (dir == ForgeDirection.UP) return ForgeDirection.DOWN; return ForgeDirection.NORTH; } public static ForgeDirection rotate(ForgeDirection dir) { return rotate(dir, 6); } public static void dropItems(World world, int x, int y, int z) { Random rand = world.rand; TileEntity tile = world.getTileEntity(x, y, z); if (!(tile instanceof IInventory)) return; if (tile instanceof TileMultiBlock) { TileMultiBlock multi = (TileMultiBlock) tile; if (multi.master != null) if (!multi.isMaster()) return; } IInventory inventory = (IInventory) tile; for (int i = 0; i < inventory.getSizeInventory(); i++) { boolean drop = true; if (tile instanceof IItemDropBlacklist) { drop = ((IItemDropBlacklist) tile).doesDrop(i); } if (drop) { ItemStack item = inventory.getStackInSlot(i); if (item != null && item.stackSize > 0) { item = item.copy(); inventory.decrStackSize(i, 1); float rx = rand.nextFloat() * 0.6F + 0.1F; float ry = rand.nextFloat() * 0.6F + 0.1F; float rz = rand.nextFloat() * 0.6F + 0.1F; EntityItem entity_item = new EntityItem(world, x + rx, y + ry, z + rz, new ItemStack(item.getItem(), item.stackSize, item.getItemDamage())); if (item.hasTagCompound()) { entity_item.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy()); } float factor = 0.05F; entity_item.motionX = rand.nextGaussian() * factor; entity_item.motionY = rand.nextGaussian() * factor + 0.2F; entity_item.motionZ = rand.nextGaussian() * factor; world.spawnEntityInWorld(entity_item); item.stackSize = 0; } } } } private static boolean removeBlock(World world, EntityPlayerMP player, int x, int y, int z) { Block block = world.getBlock(x, y, z); int l = world.getBlockMetadata(x, y, z); block.onBlockHarvested(world, x, y, z, l, player); boolean flag = block.removedByPlayer(world, player, x, y, z, true); if (flag) { block.onBlockDestroyedByPlayer(world, x, y, z, l); } return flag; } public static void destroyBlock(World world, int x, int y, int z) { destroyBlock(world, x, y, z, null, null); } public static void destroyBlock(World world, int x, int y, int z, Block required, ItemStack held) { if (!(world instanceof WorldServer)) return; Block block = world.getBlock(x, y, z); if (required != null && block != required) return; if (block.getBlockHardness(world, x, y, z) < 0.0F) return; FakePlayer player = PlayerHelper.getFakePlayer(world); if (player != null && held != null) { player.setCurrentItemOrArmor(0, held.copy()); } int l = world.getBlockMetadata(x, y, z); world.playAuxSFXAtEntity(player, 2001, x, y, z, Block.getIdFromBlock(block) + (world.getBlockMetadata(x, y, z) << 12)); boolean flag = removeBlock(world, player, x, y, z); if (flag) { block.harvestBlock(world, player, x, y, z, l); } return; } }
svgorbunov/Mariculture
src/main/java/mariculture/core/helpers/BlockHelper.java
Java
mit
7,041
(function(){ "use strict"; KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft"); KC3StrategyTabs.aircraft.definition = { tabSelf: KC3StrategyTabs.aircraft, squadNames: {}, _items: {}, _holders: {}, _slotNums: {}, /* INIT Prepares static data needed ---------------------------------*/ init :function(){ }, /* RELOAD Prepares latest player data ---------------------------------*/ reload :function(){ var self = this; this._items = {}; this._holders = {}; this._slotNums = {}; KC3ShipManager.load(); KC3GearManager.load(); PlayerManager.loadBases(); // Get squad names if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; } this.squadNames = JSON.parse(localStorage.planes); // Compile equipment holders var ctr, ThisItem, MasterItem, ThisShip, MasterShip; for(ctr in KC3ShipManager.list){ this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]); // No plane is able to be equipped in ex-slot for now } for(ctr in PlayerManager.bases){ this.checkLbasSlotForItemHolder(PlayerManager.bases[ctr]); } for(ctr in PlayerManager.baseConvertingSlots){ this._holders["s"+PlayerManager.baseConvertingSlots[ctr]] = "LbasMoving"; } // Compile ships on Index var thisType, thisSlotitem, thisGearInstance; function GetMyHolder(){ return self._holders["s"+this.itemId]; } function NoHolder(){ return false; } for(ctr in KC3GearManager.list){ ThisItem = KC3GearManager.list[ctr]; MasterItem = ThisItem.master(); if(!MasterItem) continue; //if(KC3GearManager.carrierBasedAircraftType3Ids.indexOf(MasterItem.api_type[3]) == -1) continue; // Add holder to the item object temporarily via function return if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){ ThisItem.MyHolder = GetMyHolder; }else{ ThisItem.MyHolder = NoHolder; } // Check if slotitem_type is filled if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){ this._items["t"+MasterItem.api_type[3]] = []; } thisType = this._items["t"+MasterItem.api_type[3]]; // Check if slotitem_id is filled if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){ this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = { id: ThisItem.masterId, type_id: MasterItem.api_type[3], english: ThisItem.name(), japanese: MasterItem.api_name, stats: { fp: MasterItem.api_houg, tp: MasterItem.api_raig, aa: MasterItem.api_tyku, ar: MasterItem.api_souk, as: MasterItem.api_tais, ev: MasterItem.api_houk, ls: MasterItem.api_saku, dv: MasterItem.api_baku, ht: MasterItem.api_houm, rn: MasterItem.api_leng, or: MasterItem.api_distance }, instances: [] }; } thisSlotitem = this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id]; thisSlotitem.instances.push(ThisItem); } // sort this_items var sortMasterItem = function(a, b){ var attr; switch( i ){ case 't6': case 6: attr = 'aa'; break; case 't7': case 7: attr = 'dv'; break; case 't8': case 8: attr = 'tp'; break; case 't9': case 9: attr = 'ls'; break; case 't10': case 10: attr = 'dv'; break; default: attr = 'aa'; break; } if( b.stats[attr] == a.stats[attr] ) return b.stats.ht - a.stats.ht; return b.stats[attr] - a.stats[attr]; }; var sortSlotItem = function(a,b){ return b.ace - a.ace; }; for( var i in this._items ){ // make elements in this._items true Array for( var j in this._items[i] ){ // sort item by ace this._items[i][j].instances.sort(sortSlotItem); this._items[i].push( this._items[i][j] ); delete this._items[i][j]; } // sort MasterItem by stat this._items[i].sort(sortMasterItem); } }, /* Check a ship's equipment slot of an item is equipped --------------------------------------------*/ checkShipSlotForItemHolder :function(slot, ThisShip){ if(ThisShip.items[slot] > 0){ this._holders["s"+ThisShip.items[slot]] = ThisShip; this._slotNums["s"+ThisShip.items[slot]] = slot; } }, /* Check LBAS slot of an aircraft is equipped --------------------------------------------*/ checkLbasSlotForItemHolder :function(LandBase){ for(var squad in LandBase.planes){ if(LandBase.planes[squad].api_slotid > 0){ this._holders["s"+LandBase.planes[squad].api_slotid] = LandBase; } } }, /* EXECUTE Places data onto the interface ---------------------------------*/ execute :function(){ var self = this; $(".tab_aircraft .item_type").on("click", function(){ KC3StrategyTabs.gotoTab(null, $(this).data("type")); }); $(".tab_aircraft .item_list").on("change", ".instance_name input", function(){ self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val(); localStorage.planes = JSON.stringify(self.squadNames); }); if(!!KC3StrategyTabs.pageParams[1]){ this.showType(KC3StrategyTabs.pageParams[1]); } else { this.showType($(".tab_aircraft .item_type").first().data("type")); } }, /* Show slotitem type --------------------------------------------*/ showType :function(type_id){ $(".tab_aircraft .item_type").removeClass("active"); $(".tab_aircraft .item_type[data-type={0}]".format(type_id)).addClass("active"); $(".tab_aircraft .item_list").html(""); var ctr, ThisType, ItemElem, ThisSlotitem; var gearClickFunc = function(e){ KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt")); }; var lbasPlanesFilter = function(s){ return s.api_slotid === ThisPlane.itemId; }; for(ctr in this._items["t"+type_id]){ ThisSlotitem = this._items["t"+type_id][ctr]; ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list"); $(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png"); $(".icon img", ItemElem).attr("alt", ThisSlotitem.id); $(".icon img", ItemElem).click(gearClickFunc); $(".english", ItemElem).text(ThisSlotitem.english); $(".japanese", ItemElem).text(ThisSlotitem.japanese); this.slotitem_stat(ItemElem, ThisSlotitem, "fp"); this.slotitem_stat(ItemElem, ThisSlotitem, "tp"); this.slotitem_stat(ItemElem, ThisSlotitem, "aa"); this.slotitem_stat(ItemElem, ThisSlotitem, "ar"); this.slotitem_stat(ItemElem, ThisSlotitem, "as"); this.slotitem_stat(ItemElem, ThisSlotitem, "ev"); this.slotitem_stat(ItemElem, ThisSlotitem, "ls"); this.slotitem_stat(ItemElem, ThisSlotitem, "dv"); this.slotitem_stat(ItemElem, ThisSlotitem, "ht"); this.slotitem_stat(ItemElem, ThisSlotitem, "rn"); this.slotitem_stat(ItemElem, ThisSlotitem, "or"); var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity; for(PlaneCtr in ThisSlotitem.instances){ ThisPlane = ThisSlotitem.instances[PlaneCtr]; PlaneBox = $(".tab_aircraft .factory .instance").clone(); $(".instances", ItemElem).append(PlaneBox); $(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png"); if(ThisPlane.stars > 0){ $(".instance_star span", PlaneBox).text( ThisPlane.stars > 9 ? "m" : ThisPlane.stars); } else { $(".instance_star img", PlaneBox).hide(); } if(ThisPlane.ace > 0){ $(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png"); }else{ $(".instance_chev img", PlaneBox).hide(); } $(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId); if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){ $(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] ); } if(ThisPlane.MyHolder()){ if(ThisPlane.MyHolder() instanceof KC3LandBase){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS World "+ThisPlane.MyHolder().map ); $(".holder_level", PlaneBox).text( "#"+ThisPlane.MyHolder().rid ); ThisCapacity = ThisPlane.MyHolder().planes .filter(lbasPlanesFilter)[0].api_max_count; } else if(ThisPlane.MyHolder() === "LbasMoving"){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS Moving" ); $(".holder_level", PlaneBox).text( "" ); ThisCapacity = ""; } else { $(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) ); $(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() ); $(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level); ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ]; } if(ThisCapacity > 0){ // Compute for veteranized fighter power var MyFighterPowerText = ""; if(ConfigManager.air_formula == 1){ MyFighterPowerText = ThisPlane.fighterPower(ThisCapacity); }else{ MyFighterPowerText = "~"+ThisPlane.fighterVeteran(ThisCapacity); } $(".instance_aaval", PlaneBox).text( MyFighterPowerText ); } $(".instance_aaval", PlaneBox).addClass("activeSquad"); $(".instance_slot", PlaneBox).text(ThisCapacity); }else{ $(".holder_pic", PlaneBox).hide(); $(".holder_name", PlaneBox).hide(); $(".holder_level", PlaneBox).hide(); $(".instance_aaval", PlaneBox).addClass("reserveSquad"); $(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa ); } } } }, /* Determine if an item has a specific stat --------------------------------------------*/ slotitem_stat :function(ItemElem, SlotItem, statName){ if(SlotItem.stats[statName] !== 0 && (statName !== "or" || (statName === "or" && KC3GearManager.landBasedAircraftType3Ids.indexOf(SlotItem.type_id)>-1) ) ){ $(".stats .item_"+statName+" span", ItemElem).text(SlotItem.stats[statName]); }else{ $(".stats .item_"+statName, ItemElem).hide(); } } }; })();
c933103/KC3Kai
src/pages/strategy/tabs/aircraft/aircraft.js
JavaScript
mit
10,605
'use strict'; /* This is the primary module of the Ava bot, if you are not using docker to run the bot you can use another method to run this file as long as you make sure you have the correct dependencies */ const bot = require('./bot.js'); const log = require('./logger.js')(module); log.info('======== ava.js running ========'); // This step serves the important purpose of allowing a specific function to be called to start the bot bot.startup();
JamesLongman/ava-bot
lib/ava.js
JavaScript
mit
455
/** * @class Jaml * @author Ed Spencer (http://edspencer.net) * Jaml is a simple JavaScript library which makes HTML generation easy and pleasurable. * Examples: http://edspencer.github.com/jaml * Introduction: http://edspencer.net/2009/11/jaml-beautiful-html-generation-for-javascript.html */ Jaml = function() { return { templates: {}, /** * Registers a template by name * @param {String} name The name of the template * @param {Function} template The template function */ register: function(name, template) { this.templates[name] = template; }, /** * Renders the given template name with an optional data object * @param {String} name The name of the template to render * @param {Object} thisObj Optional data object * @param {Object} data Optional data object */ render: function(name, thisObj, data) { var template = this.templates[name], renderer = new Jaml.Template(template); return renderer.render.apply(renderer, Array.prototype.slice.call(arguments, 1)); } }; }();
edspencer/jaml
src/Jaml.js
JavaScript
mit
1,100
require_relative "http_client" require_relative 'artist' require_relative 'album' module Xiami class Song include Virtus.model(finalize: false) attribute :id, Integer attribute :name, String attribute :temporary_url, String attribute :artist, Artist attribute :album, 'Xiami::Album' attribute :lyrics_url, String class << self def search(query) Searcher.search(query: query) end def search_all(query) FullSearcher.search(query: query) end def fetch(song_url) song_id = song_url.match(/song\/([0-9]+)/)[1] rescue song_url fetch!(song_id) rescue nil end def fetch!(id) song = parse_xml_info!(id) rescue parse_html_page!(id) song.id = id song.fetch_all_album_arts! song end def parse_html_page!(id) html = HTTPClient.get_content("http://www.xiami.com/song/#{id}") Parser::SongHTMLParser.parse(html) end def parse_xml_info!(id) xml = HTTPClient.get_content("http://www.xiami.com/widget/xml-single/uid/0/sid/#{id}") Parser::SongXMLParser.parse(xml) end def parse_lyrics_info!(id) xml = HTTPClient.get_content("http://www.xiami.com/song/playlist/id/#{id}") Parser::LyricsXMLParser.parse(xml) end def parse_lyrics!(id) url = parse_lyrics_info!(id) HTTPClient.get_content(url) end end def fetch_all_album_arts! results = CoverFetcher.fetch_all(album.cover_url, HTTPClient.proxy) album.cover_urls = results[:cover_urls] album.cover_url = results[:cover_url] end def ==(another) return false if another.nil? self.id == another.id end def title name end def artist_name artist.name end def album_name album.name end end end
forresty/xiami
lib/xiami/song.rb
Ruby
mit
1,928
module.exports = { vert: [ 'uniform mat4 u_view_matrix;', 'attribute vec2 a_position;', 'attribute vec4 a_color;', 'varying vec4 v_color;', 'void main () {', ' gl_Position = u_view_matrix * vec4(a_position, 1.0, 1.0);', ' v_color = a_color;', '}' ].join('\n'), frag:[ 'precision lowp float;', 'varying vec4 v_color;', 'void main() {', ' gl_FragColor = v_color;', '}' ].join('\n') };
clark-stevenson/phaser
v3/src/renderer/webgl/shaders/UntexturedAndTintedShader.js
JavaScript
mit
509
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02.ConcatenateTextFiles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.ConcatenateTextFiles")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("af1279c8-1d89-4fe8-9bc7-b8edc5f9ca0c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tddold/Telerik-Academy-2
Csharp-Part2/08.TextFiles/02.ConcatenateTextFiles/Properties/AssemblyInfo.cs
C#
mit
1,422
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting; using CM.Payments.Client.Model; using System.Reflection; using CM.Payments.Client.Enums; //<auto-generated> // IMPORTANT NOTE: // This code is generated by MessageUnitTestGenerator in this project. // Date and time: 06-04-2018 14:52:27 // // Changes to this file may cause incorrect behavior and will be lost on the next code generation. //</auto-generated> namespace CM.Payments.Client.Test { [TestClass, ExcludeFromCodeCoverage] public partial class AfterPayDetailsResponseTests : BaseJsonConvertTests { public TestContext TestContext { get; set; } [TestMethod] public void AfterPayDetailsResponse() { var obj = new AfterPayDetailsResponse { AuthenticationUrl = "Lorum_737", BankAccountNumber = "Lorum_307", BillToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_91", HouseNumber = 16, HouseNumberAddition = "Lorum_983", IsoCountryCode = "Lorum_910", PostalCode = "Lorum_125", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_316", Gender = "Lorum_811", Initials = "Lorum_27", IsoLanguage = "Lorum_772", LastName = "Lorum_226", PhoneNumber1 = "Lorum_384", PhoneNumber2 = "Lorum_608" }, Region = "Lorum_83", StreetName = "Lorum_97" }, CallbackUrl = "Lorum_991", CancelledUrl = "Lorum_705", ExpiredUrl = "Lorum_717", FailedUrl = "Lorum_287", InvoiceNumber = "Lorum_905", IpAddress = "Lorum_958", Orderline = new List<AfterPayDetailsRequest.OrderLine> { new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_894", ArticleId = "Lorum_161", NetUnitPrice = 84, Quantity = 1, UnitPrice = 20, VatCategory = AfterPayVatCategory.Low }, new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_969", ArticleId = "Lorum_91", NetUnitPrice = 45, Quantity = 58, UnitPrice = 8, VatCategory = AfterPayVatCategory.Zero } }, OrderNumber = "Lorum_768", Password = "Lorum_478", PortfolioId = 99, PurchaseId = "Lorum_408", Result = new AfterPayDetailsResponse.ResultResponse { Checksum = "Lorum_551", OrderReference = "Lorum_526", ResultId = 18, StatusCode = "Lorum_918", TimestampIn = "Lorum_404", TimestampOut = "Lorum_219", TotalInvoicedAmount = 6, TotalReservedAmount = 41, TransactionId = "Lorum_95" }, ShipToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_945", HouseNumber = 86, HouseNumberAddition = "Lorum_338", IsoCountryCode = "Lorum_352", PostalCode = "Lorum_393", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_867", Gender = "Lorum_944", Initials = "Lorum_618", IsoLanguage = "Lorum_778", LastName = "Lorum_412", PhoneNumber1 = "Lorum_930", PhoneNumber2 = "Lorum_312" }, Region = "Lorum_979", StreetName = "Lorum_711" }, SuccessUrl = "Lorum_680", TotalOrderAmount = 35 }; var deserialized = ConversionTest(obj); Assert.IsNotNull(deserialized); Assert.AreEqual(obj.AuthenticationUrl, deserialized.AuthenticationUrl); Assert.AreEqual(obj.BankAccountNumber, deserialized.BankAccountNumber); Assert.AreEqual(obj.BillToAddress.City, deserialized.BillToAddress.City); Assert.AreEqual(obj.BillToAddress.HouseNumber, deserialized.BillToAddress.HouseNumber); Assert.AreEqual(obj.BillToAddress.HouseNumberAddition, deserialized.BillToAddress.HouseNumberAddition); Assert.AreEqual(obj.BillToAddress.IsoCountryCode, deserialized.BillToAddress.IsoCountryCode); Assert.AreEqual(obj.BillToAddress.PostalCode, deserialized.BillToAddress.PostalCode); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(obj.BillToAddress.Reference.DateOfBirth.Year, obj.BillToAddress.Reference.DateOfBirth.Month, obj.BillToAddress.Reference.DateOfBirth.Day, obj.BillToAddress.Reference.DateOfBirth.Hour, obj.BillToAddress.Reference.DateOfBirth.Minute, obj.BillToAddress.Reference.DateOfBirth.Second), new DateTime(deserialized.BillToAddress.Reference.DateOfBirth.Year, deserialized.BillToAddress.Reference.DateOfBirth.Month, deserialized.BillToAddress.Reference.DateOfBirth.Day, deserialized.BillToAddress.Reference.DateOfBirth.Hour, deserialized.BillToAddress.Reference.DateOfBirth.Minute, deserialized.BillToAddress.Reference.DateOfBirth.Second)); Assert.AreEqual(obj.BillToAddress.Reference.EmailAddress, deserialized.BillToAddress.Reference.EmailAddress); Assert.AreEqual(obj.BillToAddress.Reference.Gender, deserialized.BillToAddress.Reference.Gender); Assert.AreEqual(obj.BillToAddress.Reference.Initials, deserialized.BillToAddress.Reference.Initials); Assert.AreEqual(obj.BillToAddress.Reference.IsoLanguage, deserialized.BillToAddress.Reference.IsoLanguage); Assert.AreEqual(obj.BillToAddress.Reference.LastName, deserialized.BillToAddress.Reference.LastName); Assert.AreEqual(obj.BillToAddress.Reference.PhoneNumber1, deserialized.BillToAddress.Reference.PhoneNumber1); Assert.AreEqual(obj.BillToAddress.Reference.PhoneNumber2, deserialized.BillToAddress.Reference.PhoneNumber2); Assert.AreEqual(obj.BillToAddress.Region, deserialized.BillToAddress.Region); Assert.AreEqual(obj.BillToAddress.StreetName, deserialized.BillToAddress.StreetName); Assert.AreEqual(obj.CallbackUrl, deserialized.CallbackUrl); Assert.AreEqual(obj.CancelledUrl, deserialized.CancelledUrl); Assert.AreEqual(obj.ExpiredUrl, deserialized.ExpiredUrl); Assert.AreEqual(obj.FailedUrl, deserialized.FailedUrl); Assert.AreEqual(obj.InvoiceNumber, deserialized.InvoiceNumber); Assert.AreEqual(obj.IpAddress, deserialized.IpAddress); Assert.AreEqual(obj.Orderline?.Count(), deserialized.Orderline?.Count()); for(var orderlineIndex = 0; orderlineIndex < obj.Orderline.Count(); orderlineIndex++) { var expectedOrderLineInOrderline = obj.Orderline.ElementAt(orderlineIndex) as AfterPayDetailsRequest.OrderLine; var actualOrderLineInOrderline = deserialized.Orderline.ElementAt(orderlineIndex) as AfterPayDetailsRequest.OrderLine; Assert.AreEqual(expectedOrderLineInOrderline.ArticleDescription, actualOrderLineInOrderline.ArticleDescription); Assert.AreEqual(expectedOrderLineInOrderline.ArticleId, actualOrderLineInOrderline.ArticleId); Assert.AreEqual(expectedOrderLineInOrderline.NetUnitPrice, actualOrderLineInOrderline.NetUnitPrice); Assert.AreEqual(expectedOrderLineInOrderline.Quantity, actualOrderLineInOrderline.Quantity); Assert.AreEqual(expectedOrderLineInOrderline.UnitPrice, actualOrderLineInOrderline.UnitPrice); Assert.AreEqual(expectedOrderLineInOrderline.VatCategory, actualOrderLineInOrderline.VatCategory); } Assert.AreEqual(obj.OrderNumber, deserialized.OrderNumber); Assert.AreEqual(obj.Password, deserialized.Password); Assert.AreEqual(obj.PortfolioId, deserialized.PortfolioId); Assert.AreEqual(obj.PurchaseId, deserialized.PurchaseId); Assert.AreEqual(obj.Result.Checksum, deserialized.Result.Checksum); Assert.AreEqual(obj.Result.OrderReference, deserialized.Result.OrderReference); Assert.AreEqual(obj.Result.ResultId, deserialized.Result.ResultId); Assert.AreEqual(obj.Result.StatusCode, deserialized.Result.StatusCode); Assert.AreEqual(obj.Result.TimestampIn, deserialized.Result.TimestampIn); Assert.AreEqual(obj.Result.TimestampOut, deserialized.Result.TimestampOut); Assert.AreEqual(obj.Result.TotalInvoicedAmount, deserialized.Result.TotalInvoicedAmount); Assert.AreEqual(obj.Result.TotalReservedAmount, deserialized.Result.TotalReservedAmount); Assert.AreEqual(obj.Result.TransactionId, deserialized.Result.TransactionId); Assert.AreEqual(obj.ShipToAddress.City, deserialized.ShipToAddress.City); Assert.AreEqual(obj.ShipToAddress.HouseNumber, deserialized.ShipToAddress.HouseNumber); Assert.AreEqual(obj.ShipToAddress.HouseNumberAddition, deserialized.ShipToAddress.HouseNumberAddition); Assert.AreEqual(obj.ShipToAddress.IsoCountryCode, deserialized.ShipToAddress.IsoCountryCode); Assert.AreEqual(obj.ShipToAddress.PostalCode, deserialized.ShipToAddress.PostalCode); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(obj.ShipToAddress.Reference.DateOfBirth.Year, obj.ShipToAddress.Reference.DateOfBirth.Month, obj.ShipToAddress.Reference.DateOfBirth.Day, obj.ShipToAddress.Reference.DateOfBirth.Hour, obj.ShipToAddress.Reference.DateOfBirth.Minute, obj.ShipToAddress.Reference.DateOfBirth.Second), new DateTime(deserialized.ShipToAddress.Reference.DateOfBirth.Year, deserialized.ShipToAddress.Reference.DateOfBirth.Month, deserialized.ShipToAddress.Reference.DateOfBirth.Day, deserialized.ShipToAddress.Reference.DateOfBirth.Hour, deserialized.ShipToAddress.Reference.DateOfBirth.Minute, deserialized.ShipToAddress.Reference.DateOfBirth.Second)); Assert.AreEqual(obj.ShipToAddress.Reference.EmailAddress, deserialized.ShipToAddress.Reference.EmailAddress); Assert.AreEqual(obj.ShipToAddress.Reference.Gender, deserialized.ShipToAddress.Reference.Gender); Assert.AreEqual(obj.ShipToAddress.Reference.Initials, deserialized.ShipToAddress.Reference.Initials); Assert.AreEqual(obj.ShipToAddress.Reference.IsoLanguage, deserialized.ShipToAddress.Reference.IsoLanguage); Assert.AreEqual(obj.ShipToAddress.Reference.LastName, deserialized.ShipToAddress.Reference.LastName); Assert.AreEqual(obj.ShipToAddress.Reference.PhoneNumber1, deserialized.ShipToAddress.Reference.PhoneNumber1); Assert.AreEqual(obj.ShipToAddress.Reference.PhoneNumber2, deserialized.ShipToAddress.Reference.PhoneNumber2); Assert.AreEqual(obj.ShipToAddress.Region, deserialized.ShipToAddress.Region); Assert.AreEqual(obj.ShipToAddress.StreetName, deserialized.ShipToAddress.StreetName); Assert.AreEqual(obj.SuccessUrl, deserialized.SuccessUrl); Assert.AreEqual(obj.TotalOrderAmount, deserialized.TotalOrderAmount); } } }
cmpayments/payments-sdk-net
Source/CM.Payments.Client.Test/Generated/AfterPayDetailsResponse_Tests.cs
C#
mit
10,445
require "spec_helper" describe ChefSpec::Matchers::StateAttrsMatcher do subject { described_class.new(%i{a b}) } context "when the resource does not exist" do let(:resource) { nil } before { subject.matches?(resource) } it "does not match" do expect(subject).to_not be_matches(resource) end it "has the correct description" do expect(subject.description).to eq("have state attributes [:a, :b]") end it "has the correct failure message for should" do expect(subject.failure_message).to include <<-EOH.gsub(/^ {8}/, "") expected _something_ to have state attributes, but the _something_ you gave me was nil! Ensure the resource exists before making assertions: expect(resource).to be EOH end it "has the correct failure message for should not" do expect(subject.failure_message_when_negated).to include <<-EOH.gsub(/^ {8}/, "") expected _something_ to not have state attributes, but the _something_ you gave me was nil! Ensure the resource exists before making assertions: expect(resource).to be EOH end end context "when the resource exists" do let(:klass) { double("class", state_attrs: %i{a b}) } let(:resource) { double("resource", class: klass) } before { subject.matches?(resource) } it "has the correct description" do expect(subject.description).to eq("have state attributes [:a, :b]") end it "has the correct failure message for should" do expect(subject.failure_message).to eq("expected [:a, :b] to equal [:a, :b]") end it "has the correct failure message for should not" do expect(subject.failure_message_when_negated).to eq("expected [:a, :b] to not equal [:a, :b]") end it "matches when the state attributes are correct" do expect(subject).to be_matches(resource) end it "does not match when the state attributes are incorrect" do allow(klass).to receive(:state_attrs).and_return(%i{c d}) expect(subject).to_not be_matches(resource) end it "does not match when partial state attribute are incorrect" do allow(klass).to receive(:state_attrs).and_return(%i{b c}) expect(subject).to_not be_matches(resource) end end end
chefspec/chefspec
spec/unit/matchers/state_attrs_matcher_spec.rb
Ruby
mit
2,289
<?php /* * This file is part of the PagerBundle package. * * (c) Marcin Butlak <contact@maker-labs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace MakerLabs\PagerBundle; use MakerLabs\PagerBundle\Adapter\PagerAdapterInterface; /** * Pager * * @author Marcin Butlak <contact@maker-labs.com> */ class Pager { /** * * @var integer */ protected $page = 1; /** * * @var integer */ protected $limit = 20; /** * Constructor * * @param PagerAdapterInterface $adapter The pager adapter * @param array $options Additional options */ public function __construct(PagerAdapterInterface $adapter, array $options = array()) { $this->adapter = $adapter; if (isset($options['limit'])) { $this->setLimit($options['limit']); } if (isset($options['page'])) { $this->setPage($options['page']); } } /** * Sets the current page number * * @param integer $page The current page number * @return Pager instance */ public function setPage($page) { $this->page = min($page > 0 ? $page : $this->getFirstPage(), $this->getLastPage()); return $this; } /** * Returns the current page number * * @return integer */ public function getPage() { return $this->page; } /** * Sets the results limit for one page * * @param integer $limit * @return Pager instance */ public function setLimit($limit) { $this->limit = $limit > 0 ? $limit : 1; $this->setPage($this->page); return $this; } /** * Returns the current results limit for one page * * @return integer */ public function getLimit() { return $this->limit; } /** * Returns the next page number * * @return integer */ public function getNextPage() { return $this->page < $this->getLastPage() ? $this->page + 1 : $this->getLastPage(); } /** * Returns the previous page number * * @return integer */ public function getPreviousPage() { return $this->page > $this->getFirstPage() ? $this->page - 1 : $this->getFirstPage(); } /** * Returns true if the current page is first * * @return boolean */ public function isFirstPage() { return $this->page == 1; } /** * Returns the first page number * * @return integer */ public function getFirstPage() { return 1; } /** * Returns true if the current page is last * * @return boolean */ public function isLastPage() { return $this->page == $this->getLastPage(); } /** * Returns the last page number * * @return integer */ public function getLastPage() { return $this->hasResults() ? ceil($this->adapter->count() / $this->limit) : $this->getFirstPage(); } /** * Returns true if the current result set requires pagination * * @return boolean */ public function isPaginable() { return $this->adapter->count() > $this->limit; } /** * Generates a page list * * @param integer $pages Number of pages to generate * @return array The page list */ public function getPages($pages = 10) { $tmp = $this->page - floor($pages / 2); $begin = $tmp > $this->getFirstPage() ? $tmp : $this->getFirstPage(); $end = min($begin + $pages - 1, $this->getLastPage()); return range($begin, $end, 1); } /** * Returns true if the current result set is not empty * * @return boolean */ public function hasResults() { return $this->adapter->count() > 0; } /** * * Returns results list for the current page and limit * * @return array */ public function getResults() { return $this->hasResults() ? $this->adapter->getResults(($this->page - 1) * $this->limit, $this->limit) : array(); } /** * Returns the current adapter instance * * @return PagerAdapterInterface */ public function getAdapter() { return $this->adapter; } }
soniar4i/Alood
src/MakerLabs/PagerBundle/Pager.php
PHP
mit
4,498
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.config; import java.util.List; import org.w3c.dom.Node; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionDecorator; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * Base implementation for * {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator BeanDefinitionDecorators} * wishing to add an {@link org.aopalliance.intercept.MethodInterceptor interceptor} * to the resulting bean. * * <p>This base class controls the creation of the {@link ProxyFactoryBean} bean definition * and wraps the original as an inner-bean definition for the {@code target} property * of {@link ProxyFactoryBean}. * * <p>Chaining is correctly handled, ensuring that only one {@link ProxyFactoryBean} definition * is created. If a previous {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator} * already created the {@link org.springframework.aop.framework.ProxyFactoryBean} then the * interceptor is simply added to the existing definition. * * <p>Subclasses have only to create the {@code BeanDefinition} to the interceptor that * they wish to add. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 * @see org.aopalliance.intercept.MethodInterceptor */ public abstract class AbstractInterceptorDrivenBeanDefinitionDecorator implements BeanDefinitionDecorator { @Override public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) { BeanDefinitionRegistry registry = parserContext.getRegistry(); // get the root bean name - will be the name of the generated proxy factory bean String existingBeanName = definitionHolder.getBeanName(); BeanDefinition targetDefinition = definitionHolder.getBeanDefinition(); BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET"); // delegate to subclass for interceptor definition BeanDefinition interceptorDefinition = createInterceptorDefinition(node); // generate name and register the interceptor String interceptorName = existingBeanName + '.' + getInterceptorNameSuffix(interceptorDefinition); BeanDefinitionReaderUtils.registerBeanDefinition( new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry); BeanDefinitionHolder result = definitionHolder; if (!isProxyFactoryBeanDefinition(targetDefinition)) { // create the proxy definition RootBeanDefinition proxyDefinition = new RootBeanDefinition(); // create proxy factory bean definition proxyDefinition.setBeanClass(ProxyFactoryBean.class); proxyDefinition.setScope(targetDefinition.getScope()); proxyDefinition.setLazyInit(targetDefinition.isLazyInit()); // set the target proxyDefinition.setDecoratedDefinition(targetHolder); proxyDefinition.getPropertyValues().add("target", targetHolder); // create the interceptor names list proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>()); // copy autowire settings from original bean definition. proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate()); proxyDefinition.setPrimary(targetDefinition.isPrimary()); if (targetDefinition instanceof AbstractBeanDefinition) { proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition); } // wrap it in a BeanDefinitionHolder with bean name result = new BeanDefinitionHolder(proxyDefinition, existingBeanName); } addInterceptorNameToList(interceptorName, result.getBeanDefinition()); return result; } @SuppressWarnings("unchecked") private void addInterceptorNameToList(String interceptorName, BeanDefinition beanDefinition) { List<String> list = (List<String>) beanDefinition.getPropertyValues().getPropertyValue("interceptorNames").getValue(); list.add(interceptorName); } private boolean isProxyFactoryBeanDefinition(BeanDefinition existingDefinition) { return ProxyFactoryBean.class.getName().equals(existingDefinition.getBeanClassName()); } protected String getInterceptorNameSuffix(BeanDefinition interceptorDefinition) { return StringUtils.uncapitalize(ClassUtils.getShortName(interceptorDefinition.getBeanClassName())); } /** * Subclasses should implement this method to return the {@code BeanDefinition} * for the interceptor they wish to apply to the bean being decorated. */ protected abstract BeanDefinition createInterceptorDefinition(Node node); }
boggad/jdk9-sample
sample-catalog/spring-jdk9/src/spring.aop/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java
Java
mit
5,744
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class UPSProgressInformationSequence extends AbstractTag { protected $Id = '0074,1002'; protected $Name = 'UPSProgressInformationSequence'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'UPS Progress Information Sequence'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/UPSProgressInformationSequence.php
PHP
mit
844
package luhn import "strings" func Valid(id string) bool { if len(strings.TrimSpace(id)) == 1 { return false } d := make([]int, 0, len(id)) for _, r := range id { if r == ' ' { continue } if r < '0' || r > '9' { return false } d = append(d, int(r-'0')) } return sum(d)%10 == 0 } func sum(d []int) (s int) { for i, x := range d { j := len(d) - i if j%2 == 0 { x *= 2 if x > 9 { x -= 9 } } s += x } return }
exercism/xgo
exercises/luhn/example.go
GO
mit
461
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '3.7.2', {"requires": ["event-base", "node-core", "dom-base"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/node-base/node-base-debug.js
JavaScript
mit
33,629
## Copyright (c) 2001-2010, Scott D. Peckham ## January 2009 (converted from IDL) ## November 2009 (collected into cfg_files.py ## May 2010 (added read_key_value_pair()) ## July 2010 (added read_list() import numpy #--------------------------------------------------------------------- # # unit_test() # # skip_header() # get_yes_words() # read_words() # read_list() # (7/27/10) # # read_key_value_pair() # (5/7/10) # read_line_after_key() # read_words_after_key() # read_list_after_key() # read_value() # # var_type_code() # read_input_option() # read_output_option() # (boolean and string) # #--------------------------------------------------------------------- def unit_test(): import d8_base comp = d8_base.d8_component() #------------------------------ comp.CCA = False comp.directory = '/Applications/Erode/Data/Test1/' comp.data_prefix = 'Test1' comp.case_prefix = 'Test1' comp.read_config_file() print 'comp.method =', comp.method print 'comp.method_name =', comp.method_name print 'comp.dt =', comp.dt print 'comp.dt.dtype =', comp.dt.dtype print 'comp.LINK_FLATS =', comp.LINK_FLATS print 'comp.LR_PERIODIC =', comp.LR_PERIODIC print 'comp.TB_PERIODIC =', comp.TB_PERIODIC print 'comp.SAVE_DW_PIXELS =', comp.SAVE_DW_PIXELS print 'Finished with cfg_files.unit_test().' print ' ' # unit_test() #--------------------------------------------------------------------- def skip_header(file_unit, n_lines=4): #------------------------- # Skip over header lines #------------------------- for k in xrange(n_lines): line = file_unit.readline() # skip_header() #--------------------------------------------------------------------- def get_yes_words(): yes_words = ['1', 'true', 'on', 'yes', 'ok'] return yes_words # get_yes_words() #--------------------------------------------------------------------- def read_words(file_unit, word_delim=None): #---------------------------------------------------- # Note: If (word_delim is None), then the "split()" # method for strings will use any whitespace # string as a separator. #---------------------------------------------------- line = file_unit.readline() words = line.split( word_delim ) return words # read_words() #--------------------------------------------------------------------- def read_list(file_unit, dtype_list=None, dtype='string', word_delim=None): #------------------------------------------------------------- # Notes: Example (read boolean and string/filename): # vlist = read_list_after_key(file_unit, # ['boolean', 'string']) #------------------------------------------------------------- words = read_words(file_unit, word_delim=word_delim) #---------------------------------------------- # If "dtype_list" is None, then assume that # every element in the list has type "dtype". #---------------------------------------------------- # NB! "dtype_list" cannot default to "[]", because # then values set from a previous call to this # function are remembered and used. #---------------------------------------------------- ## if (dtype_list == []): ## if (len(dtype_list) == 0): if (dtype_list is None): dtype_list = [] for k in xrange(len(words)): dtype_list.append( dtype.lower() ) elif (len(dtype_list) > len(words)): print 'ERROR in cfg_files.read_list_after_key().' print ' Not enough values in the line.' return k = 0 yes_words = get_yes_words() var_list = [] for type_str in dtype_list: vtype = type_str.lower() word = words[k].strip() if (vtype == 'string'): var = word elif (vtype == 'boolean'): var = (word in yes_words) else: value = eval( word ) exec('var = numpy.' + vtype + '( value )') var_list.append( var ) k += 1 return var_list # read_list() #--------------------------------------------------------------------- def read_key_value_pair(file_unit, key_delim=':', SILENT=True): line = file_unit.readline() #-------------------------------------- # Extract the variable name or label, # which may contain blank spaces #-------------------------------------- p = line.find( key_delim ) if (p == -1): if not(SILENT): print 'ERROR in cfg_files.read_line_after_key():' print ' Key-value delimiter not found.' return ('', '') key = line[:p] value = line[p + 1:] value = value.strip() # (strip leading & trailing whitespace) return (key, value) # read_key_value_pair() #--------------------------------------------------------------------- def read_line_after_key(file_unit, key_delim=':'): line = file_unit.readline() #-------------------------------------- # Extract the variable name or label, # which may contain blank spaces #-------------------------------------- p = line.find( key_delim ) if (p == -1): print 'ERROR in cfg_files.read_line_after_key():' print ' Key-value delimiter not found.' return '' label = line[:p] line = line[p + 1:] return line.strip() # (strip leading and trailing whitespace) # read_line_after_key() #--------------------------------------------------------------------- def read_words_after_key(file_unit, key_delim=':', word_delim=None, n_words=None): #---------------------------------------------------- # Note: If (word_delim is None), then the "split()" # method for strings will use any whitespace # string as a separator. #---------------------------------------------------- line = read_line_after_key( file_unit, key_delim=key_delim) #------------------------------- # Extract variables as strings #------------------------------- words = line.split( word_delim ) #----------------------------------- # Option to check for enough words #----------------------------------- if (n_words is None): return words if (len(words) < n_words): print 'ERROR in read_words_after_key():' print ' Not enough words found.' return words # read_words_after_key() #--------------------------------------------------------------------- def read_list_after_key(file_unit, dtype_list=None, dtype='string', key_delim=':', word_delim=None): ## print 'before: dtype =', dtype ## print 'before: dtype_list =', dtype_list #------------------------------------------------------------- # Notes: Example (read boolean and string/filename): # vlist = read_list_after_key(file_unit, # ['boolean', 'string']) #------------------------------------------------------------- words = read_words_after_key(file_unit, key_delim=key_delim, word_delim=word_delim) #---------------------------------------------- # If "dtype_list" is None, then assume that # every element in the list has type "dtype". #---------------------------------------------------- # NB! "dtype_list" cannot default to "[]", because # then values set from a previous call to this # function are remembered and used. #---------------------------------------------------- ## if (dtype_list == []): ## if (len(dtype_list) == 0): if (dtype_list is None): dtype_list = [] for k in xrange(len(words)): dtype_list.append( dtype.lower() ) elif (len(dtype_list) > len(words)): print 'ERROR in cfg_files.read_list_after_key().' print ' Not enough values in the line.' return ## print 'after: dtype =', dtype ## print 'after: dtype_list =', dtype_list ## print '--------------------------------' k = 0 yes_words = get_yes_words() var_list = [] for type_str in dtype_list: vtype = type_str.lower() word = words[k].strip() if (vtype == 'string'): var = word elif (vtype == 'boolean'): var = (word in yes_words) else: value = eval( word ) exec('var = numpy.' + vtype + '( value )') var_list.append( var ) k += 1 return var_list # read_list_after_key() #--------------------------------------------------------------------- def read_value(file_unit, dtype='string', key_delim=':'): #-------------------------------------------------------------- # Notes: Valid "var_types" are: # 'file', 'string', 'boolean' and any numpy dtype, # such as: # 'uint8', 'int16', 'int32', 'float32', 'float64' # If (var_type eq 'file'), then we want to read everything # after the ":", which may contain space characters in # the interior (e.g a directory), but with leading and # trailing spaces removed. #-------------------------------------------------------------- vtype = dtype.lower() if (vtype == 'file'): return read_line_after_key(file_unit, key_delim=key_delim) words = read_words_after_key( file_unit ) #-------------------- # Return a string ? #-------------------- if (vtype == 'string'): return words[0] #------------------------------------- # Return a boolean (True or False) ? #------------------------------------- if (vtype == 'boolean'): yes_words = get_yes_words() return (words[0].lower() in yes_words) #------------------------------------ # Try to convert string to a number #------------------------------------ try: value = eval(words[0]) except: print 'ERROR in cfg_files.read_value():' print ' Unable to convert string to number.' return words[0] #---------------------------------- # Return number of requested type #---------------------------------- exec('result = numpy.' + vtype + '( value )') return result # read_value() #--------------------------------------------------------------------- def var_type_code(var_type): cmap = {'scalar': 0, \ 'time_series': 1, \ 'time series': 1, \ 'grid' : 2, \ 'grid_stack' : 3, \ 'grid stack' : 3, \ 'grid_sequence': 3, \ 'grid sequence': 3 } code = cmap[ var_type.lower() ] return numpy.int16( code ) # var_type_code() #--------------------------------------------------------------------- def read_input_option(file_unit, key_delim=':', word_delim=None): words= read_words_after_key( file_unit, key_delim=key_delim, word_delim=word_delim ) #----------------------------------------------- # TopoFlow "var types" are: # Scalar, Time_Series, Grid, Grid_Sequence #----------------------------------------------- var_type = words[0].lower() if (var_type == 'scalar'): type_code = numpy.int16(0) scalar = numpy.float64( eval( words[1] ) ) filename = '' # (or use None ??) else: type_code = var_type_code( var_type ) scalar = None filename = words[1] return (type_code, scalar, filename) # read_input_option() #--------------------------------------------------------------------- def read_output_option(file_unit, key_delim=':', word_delim=None): #------------------------------- # Extract variables as strings #------------------------------- words = read_words_after_key( file_unit, key_delim=key_delim, word_delim=word_delim ) count = len(words) if (count == 0): print 'ERROR in cfg_files.read_output_option():' print ' No value found after delimiter.' return '' if (count == 1): print 'ERROR in cfg_files.read_output_option():' print ' No filename provided after option.' return '' yes_words = ['1','true','yes','on'] option = (words[0].lower() in yes_words) filename = words[1] return option, filename # read_output_option() #---------------------------------------------------------------------
mdpiper/topoflow
topoflow/utils/cfg_files.py
Python
mit
12,732
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:33:37 PST by lamport // modified on Fri Sep 22 13:54:35 PDT 2000 by yuanyu package tlc2.tool.liveness; import tla2sany.semantic.LevelConstants; import tlc2.output.EC; import tlc2.tool.ITool; import tlc2.tool.TLCState; import util.Assert; /** * Handles always ([]) * * @author Leslie Lamport, Yuan Yu, Simon Zambrovski * @version $Id$ */ class LNAll extends LiveExprNode { /** * */ private static final String ALWAYS = "[]"; private final LiveExprNode body; public LNAll(LiveExprNode body) { this.body = body; } public final LiveExprNode getBody() { return this.body; } public final int getLevel() { return LevelConstants.TemporalLevel; } @Override public final boolean containAction() { return this.body.containAction(); } @Override public final boolean isPositiveForm() { return this.body.isPositiveForm(); } public final boolean eval(ITool tool, TLCState s1, TLCState s2) { Assert.fail(EC.TLC_LIVE_CANNOT_EVAL_FORMULA, ALWAYS); return false; // make compiler happy } public final void toString(StringBuffer sb, String padding) { sb.append(ALWAYS); this.getBody().toString(sb, padding + " "); } /* Return A if this expression is of form []<>A. */ public LiveExprNode getAEBody() { LiveExprNode allBody = getBody(); if (allBody instanceof LNEven) { return ((LNEven) allBody).getBody(); } return super.getAEBody(); } public void extractPromises(TBPar promises) { getBody().extractPromises(promises); } public int tagExpr(int tag) { return getBody().tagExpr(tag); } public final LiveExprNode makeBinary() { return new LNAll(getBody().makeBinary()); } public LiveExprNode flattenSingleJunctions() { return new LNAll(getBody().flattenSingleJunctions()); } public LiveExprNode simplify() { LiveExprNode body1 = getBody().simplify(); if (body1 instanceof LNAll) { body1 = ((LNAll) body1).getBody(); } return new LNAll(body1); } public boolean isGeneralTF() { LiveExprNode allBody = getBody(); if (allBody instanceof LNEven) { return false; } return super.isGeneralTF(); } public LiveExprNode pushNeg() { return new LNEven(getBody().pushNeg()); } public LiveExprNode pushNeg(boolean hasNeg) { if (hasNeg) { return new LNEven(getBody().pushNeg(true)); } else { return new LNAll(getBody().pushNeg(false)); } } public boolean equals(LiveExprNode exp) { if (exp instanceof LNAll) { return getBody().equals(((LNAll) exp).getBody()); } return false; } /* (non-Javadoc) * @see tlc2.tool.liveness.LiveExprNode#toDotViz() */ public String toDotViz() { return ALWAYS + getBody().toDotViz(); } }
lemmy/tlaplus
tlatools/org.lamport.tlatools/src/tlc2/tool/liveness/LNAll.java
Java
mit
2,829
import os import shutil import subprocess def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def install(omp=False, mpi=False, phdf5=False, dagmc=False): # Create build directory and change to it shutil.rmtree('build', ignore_errors=True) os.mkdir('build') os.chdir('build') # Build in debug mode by default cmake_cmd = ['cmake', '-Ddebug=on'] # Turn off OpenMP if specified if not omp: cmake_cmd.append('-Dopenmp=off') # Use MPI wrappers when building in parallel if mpi: os.environ['CXX'] = 'mpicxx' # Tell CMake to prefer parallel HDF5 if specified if phdf5: if not mpi: raise ValueError('Parallel HDF5 must be used in ' 'conjunction with MPI.') cmake_cmd.append('-DHDF5_PREFER_PARALLEL=ON') else: cmake_cmd.append('-DHDF5_PREFER_PARALLEL=OFF') if dagmc: cmake_cmd.append('-Ddagmc=ON') # Build in coverage mode for coverage testing cmake_cmd.append('-Dcoverage=on') # Build and install cmake_cmd.append('..') print(' '.join(cmake_cmd)) subprocess.check_call(cmake_cmd) subprocess.check_call(['make', '-j4']) subprocess.check_call(['sudo', 'make', 'install']) def main(): # Convert Travis matrix environment variables into arguments for install() omp = (os.environ.get('OMP') == 'y') mpi = (os.environ.get('MPI') == 'y') phdf5 = (os.environ.get('PHDF5') == 'y') dagmc = (os.environ.get('DAGMC') == 'y') # Build and install install(omp, mpi, phdf5, dagmc) if __name__ == '__main__': main()
liangjg/openmc
tools/ci/travis-install.py
Python
mit
2,019
<?php return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '[2-9]\\d{6}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '', ), 'fixedLine' => array ( 'NationalNumberPattern' => ' (?: 2(?: [034789]\\d| 1[0-7] )| 4(?: [013-8]\\d| 2[4-7] )| [56]\\d{2}| 8(?: 14| 3[129] ) )\\d{4} ', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '2012345', ), 'mobile' => array ( 'NationalNumberPattern' => ' (?: 25\\d| 4(?: 2[12389]| 9\\d )| 7\\d{2}| 87[15-8]| 9[1-8]\\d )\\d{4} ', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '2512345', ), 'tollFree' => array ( 'NationalNumberPattern' => '80[012]\\d{4}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '8001234', ), 'premiumRate' => array ( 'NationalNumberPattern' => '30\\d{5}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '3012345', ), 'sharedCost' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', 'ExampleNumber' => '', ), 'noInternationalDialling' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', 'ExampleNumber' => '', ), 'id' => 'MU', 'countryCode' => 230, 'internationalPrefix' => '0(?:[2-7]0|33)', 'preferredInternationalPrefix' => '020', 'sameMobileAndFixedLinePattern' => false, 'numberFormat' => array ( 0 => array ( 'pattern' => '([2-9]\\d{2})(\\d{4})', 'format' => '$1 $2', 'leadingDigitsPatterns' => array ( ), 'nationalPrefixFormattingRule' => '', 'domesticCarrierCodeFormattingRule' => '', ), ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => NULL, 'leadingZeroPossible' => NULL, );
kokone/wp-phone-number
libphonenumber/data/PhoneNumberMetadata_MU.php
PHP
mit
2,103
package org.cdlib.xtf.textIndexer; /** * Copyright (c) 2006, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of California nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Acknowledgements: * * A significant amount of new and/or modified code in this module * was made possible by a grant from the Andrew W. Mellon Foundation, * as part of the Melvyl Recommender Project. */ import java.io.File; import org.apache.lucene.index.IndexReader; import org.apache.lucene.spelt.SpellWriter; import org.apache.lucene.util.ProgressTracker; import org.cdlib.xtf.util.Path; import org.cdlib.xtf.util.Trace; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * This class provides a simple mechanism for generating a spelling correction * dictionary after new documents have been added or updated. <br><br> * * To use this class, simply instantiate a copy, and call the * {@link IdxTreeDictMaker#processDir(File) processDir()} * method on a directory containing an index. Note that the directory passed * may also be a root directory with many index sub-directories if desired. */ public class IdxTreeDictMaker { //////////////////////////////////////////////////////////////////////////// /** * Create an <code>IdxTreeDictMaker</code> instance and call this method to * create spelling dictionaries for one or more Lucene indices. <br><br> * * @param dir The index database directory to scan. May be a * directory containing a single index, or the root * directory of a tree containing multiple indices. * <br><br> * * @.notes This method also calls itself recursively to process * potential index sub-directories below the passed * directory. */ public void processDir(File dir) throws Exception { // If the file we were passed was in fact a directory... if (dir.getAbsoluteFile().isDirectory()) { // And it contains an index, optimize it. if (IndexReader.indexExists(dir.getAbsoluteFile())) makeDict(dir); else { // Get the list of files it contains. String[] files = dir.getAbsoluteFile().list(); // And process each of them. for (int i = 0; i < files.length; i++) processDir(new File(dir, files[i])); } return; } // if( dir.isDirectory() ) // The current file is not a directory, so skip it. } // processDir() //////////////////////////////////////////////////////////////////////////// /** * Performs the actual work of creating a spelling dictionary. * <br><br> * * @param mainIdxDir The index database directory to scan. This * directory must contain a single Lucene index. * <br><br> * * @throws Exception Passes back any exceptions generated by Lucene * during the dictionary generation process. * <br><br> */ public void makeDict(File mainIdxDir) throws Exception { // Detect if spelling data is present. String indexPath = Path.normalizePath(mainIdxDir.toString()); String spellIdxPath = indexPath + "spellDict/"; String wordQueuePath = spellIdxPath + "newWords.txt"; String pairQueuePath = spellIdxPath + "newPairs.txt"; if (new File(wordQueuePath).length() < 1 && new File(pairQueuePath).length() < 1) { return; } // Tell what index we're working on... String mainIdxPath = Path.normalizePath(mainIdxDir.toString()); Trace.info("Index: [" + mainIdxPath + "] ... "); Trace.tab(); Trace.tab(); // for phase SpellWriter spellWriter = null; try { // Open the SpellWriter. We don't have to specify a stopword set for // this phase (it's only used during queuing.) // spellWriter = SpellWriter.open(new File(spellIdxPath)); spellWriter.setMinWordFreq(3); // Perform the update. spellWriter.flushQueuedWords(new ProgressTracker() { public void report(int pctDone, String descrip) { String pctTxt = Integer.toString(pctDone); while (pctTxt.length() < 3) pctTxt = " " + pctTxt; Trace.info("[" + pctTxt + "%] " + descrip); } }); } // try( to open the specified index ) catch (Exception e) { Trace.error("*** Dictionary Creation Halted Due to Error:" + e); throw e; } finally { spellWriter.close(); } Trace.untab(); // for phase Trace.untab(); Trace.info("Done."); } // makeDict() } // class IdxTreeDictMaker
CDLUC3/dash-xtf
xtf/WEB-INF/src/org/cdlib/xtf/textIndexer/IdxTreeDictMaker.java
Java
mit
6,314
<?php require_once(lib_path.'PHPMailer_5.2.1/class.phpmailer.php'); class Email{ /** * sendMsg * * Envia um e-mail utilizando a bibliteca PHPMailer. * * @version 1.0 * @param string $to E-mail do destinatário. * @param string $subject Assunto do e-mail. * @param string $msg Mensagem do e-mail (html). * @param string $configs Array com as configurações do envio. * Índice 'SMTPAuth' - Informa se a conexão com o SMTP será autenticada. * Índice 'SMTPSecure' - Define o padrão de segurança (SSL, TLS, STARTTLS). * Índice 'Host' - Host smtp para envio do e-mail. * Índice 'SMTPAuth' - Informa se a conexão com o SMTP será autenticada. * Índice 'Port' - Porta do SMTP para envio do e-mail. * Índice 'Username' - Usuário para autenticação do SMTP. * Índice 'Password' - Senha para autenticação do SMTP. * Índice 'AddReplyTo' - E-mail e nome para resposta do e-mail. * array( 0 => e-mail, 1 => nome) * Índice 'SetFrom' - E-mail e nome do remetente do e-mail. * array( 0 => e-mail, 1 => nome) * @param string $msg Mensagem do e-mail (html). * @param string $msg Mensagem do e-mail (html). * @param string $msg Mensagem do e-mail (html). * @return boolean / mensagens de erros Retorna true caso o e-mail tenha sido enviado ou as mensagens de erro caso não tenha sido enviado. */ public static function sendMsg($to,$subject,$msg,$configs = '',$debug = 1){ $configs = ($configs == '' || $configs == null)?Config::$email['default']: $configs; $configs = (is_string($configs))?Config::$email[$configs]: $configs; $mail = new PHPMailer(true); // True para a função enviar exceções de erros $mail->IsSMTP(); // Definindo a classe para utilizar SMTP. try { $mail->SMTPDebug = $debug; // Ativar informações de debug $mail->SMTPAuth = $configs['SMTPAuth']; // Informa se a conexão com o SMTP será autenticada. $mail->SMTPSecure = $configs['SMTPSecure'];// Define o padrão de segurança (SSL, TLS, STARTTLS). $mail->Host = $configs['Host']; // Host smtp para envio do e-mail. $mail->Port = $configs['Port'];; // Porta do SMTP para envio do e-mail. $mail->Username = $configs['Username']; // Usuário para autenticação do SMTP. $mail->Password = $configs['Password']; // Senha para autenticação do SMTP. $mail->AddAddress($to, ""); $mail->AddReplyTo($configs['AddReplyTo'][0], $configs['AddReplyTo'][1]); $mail->SetFrom($configs['SetFrom'][0], $configs['SetFrom'][1]); $mail->Subject = $subject; $mail->AltBody = 'Para ver essa mensagem utilize um programa compatível com e-mails em formato HTML!'; // optional - MsgHTML will create an alternate automatically $mail->MsgHTML($msg); $mail->Send(); return true; } catch (phpmailerException $e) { return $e->errorMessage(); // Mensagens de erro das exceções geradas pelo phpmailer. } catch (Exception $e) { return $e->getMessage(); // Mensagens de exceções geradas durante a execução da função. } } } ?>
AndrePessoa/Topo
topo/app/core/email.class.php
PHP
mit
3,191
'use strict'; var assert = require('assert') var Promise = require('promise') var connect = require('../') var client = connect({ version: 3, cache: 'file', auth: '90993e4e47b0fdd1f51f4c67b17368c62a3d6097' // github-basic-js-test }); describe('async', function () { it('can make simple api requests', function (done) { this.timeout(5000) client.get('/users/:user/gists', {user: 'ForbesLindesay'}, function (err, res) { if (err) return done(err) assert(Array.isArray(res)) res.forEach(function (gist) { assert(typeof gist.url === 'string') assert(typeof gist.public === 'boolean') }) done() }) }) it('can have a `host` option passed in', function (done) { this.timeout(5000) client.headBuffer('https://github.com/ForbesLindesay/github-basic', done) }) it('can make streaming requests', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'visionmedia', repo: 'jade', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 150) done() }) }) it('can make streaming requests for commits', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/commits', { owner: 'ForbesLindesay', repo: 'browserify-middleware', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 140) done() }) }) it('can make streaming requests with just one page', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'ForbesLindesay', repo: 'github-basic', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) done() }) }) describe('helpers', function () { describe('exists(user, repo)', function () { it('returns `true` if a repo exists', function (done) { client.exists('ForbesLindesay', 'pull-request', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); it('returns `false` if a repo does not exist', function (done) { client.exists('ForbesLindesay', 'i-wont-ever-create-this', function (err, res) { if (err) return done(err); assert(res === false); done(); }); }); }); var branch = (new Date()).toISOString().replace(/[^0-9a-zA-Z]+/g, '') + 'async'; describe('fork(user, repo, options)', function () { it('forks `user/repo` to the current user', function (done) { this.timeout(60000); client.fork('ForbesLindesay', 'pull-request-test', function (err, res) { if (err) return done(err); client.exists('github-basic-js-test', 'pull-request-test', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); }); }); describe('branch(user, repo, form, to, options)', function () { it('creates a new branch `to` in `user/repo` based on `from`', function (done) { this.timeout(10000); client.branch('github-basic-js-test', 'pull-request-test', 'master', branch, function (err, res) { if (err) return done(err); client.head('/repos/github-basic-js-test/pull-request-test/git/refs/heads/:branch', {branch: branch}, done); }); }); }); describe('commit(commit, options)', function () { it('commits an update to a branch', function (done) { this.timeout(15000) var commit = { branch: branch, message: 'test commit', updates: [{path: 'test-file.txt', content: 'lets-add-a-file wahooo'}] }; client.commit('github-basic-js-test', 'pull-request-test', commit, function (err, res) { if (err) return done(err); client.head('https://github.com/github-basic-js-test/pull-request-test/blob/' + branch + '/test-file.txt', done); }); }); }); describe('pull(from, to, message, options)', function () { it('creates a pull request', function (done) { this.timeout(15000) var from = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: branch }; var to = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: 'master' }; var message = { title: branch, body: 'A test pull request' }; client.pull(from, to, message, function (err, res) { if (err) return done(err); ///repos/github-basic-js-test/pull-request-test/pulls/1 client.head('/repos/github-basic-js-test/pull-request-test/pulls/' + res.number, done); }); }); }); }); });
scriptit/github-basic
test/async.js
JavaScript
mit
5,038
class PeopleController < HasAccountsController def index set_collection_ivar resource_class.search( params[:by_text], :star => true, :page => params[:page] ) end def show # Invoice scoping by state @invoices = resource.invoices.where("type != 'Salary'").invoice_state(params[:invoice_state]) show! end # has_many :phone_numbers def new_phone_number if resource_id = params[:id] @person = Person.find(resource_id) else @person = resource_class.new end @vcard = @person.vcard @item = @vcard.contacts.build respond_with @item end end
hauledev/has_account_engine
spec/dummy/app/controllers/people_controller.rb
Ruby
mit
624
// moment.js locale configuration // locale : Russian [ru] // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire // author : Коренберг Марк : https://github.com/socketpair function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(num, withoutSuffix, key) { var format = { mm: withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', hh: 'час_часа_часов', dd: 'день_дня_дней', MM: 'месяц_месяца_месяцев', yy: 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return num + " " + plural(format[key], +num); } } var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; // http://new.gramota.ru/spravka/rules/139-prop : § 103 // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 export var ru = { abbr: 'ru', months: { format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, monthsShort: { // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, weekdays: { standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), monthsParse: monthsParse, longMonthsParse: monthsParse, shortMonthsParse: monthsParse, // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // копия предыдущего monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // полные названия с падежами monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, // Выражение, которое соотвествует только сокращённым формам monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY г.', LLL: 'D MMMM YYYY г., HH:mm', LLLL: 'dddd, D MMMM YYYY г., HH:mm' }, relativeTime: { future: 'через %s', past: '%s назад', s: 'несколько секунд', m: relativeTimeWithPlural, mm: relativeTimeWithPlural, h: 'час', hh: relativeTimeWithPlural, d: 'день', dd: relativeTimeWithPlural, M: 'месяц', MM: relativeTimeWithPlural, y: 'год', yy: relativeTimeWithPlural }, meridiemParse: /ночи|утра|дня|вечера/i, isPM: function (input) { return /^(дня|вечера)$/.test(input); }, meridiem: function (hour) { if (hour < 4) { return 'ночи'; } else if (hour < 12) { return 'утра'; } else if (hour < 17) { return 'дня'; } else { return 'вечера'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, ordinal: function (num, period) { switch (period) { case 'M': case 'd': case 'DDD': return num + "-\u0439"; case 'D': return num + "-\u0433\u043E"; case 'w': case 'W': return num + "-\u044F"; default: return num.toString(10); } }, week: { dow: 1, doy: 4 // The week that contains Jan 4th is the first week of the year. } }; //# sourceMappingURL=ru.js.map
CatsPoo/ShiftOnline
angular.src/node_modules/ngx-bootstrap/bs-moment/i18n/ru.js
JavaScript
mit
6,071
var express = require('express'); var router = express.Router(); var request = require('request'); // Setup Redis Client var redis = require("redis"); var client = redis.createClient(process.env.REDISCACHE_SSLPORT, process.env.REDISCACHE_HOSTNAME, { auth_pass: process.env.REDISCACHE_PRIMARY_KEY, tls: { servername: process.env.REDISCACHE_HOSTNAME } }); /* GET dashboard. */ router.get('/', function (req, res) { // Query the API for incident data getIncidents().then(function (incidents) { // Render view res.render('dashboard', { title: 'Outage Dashboard', incidents: incidents }); }); }); module.exports = router; function getIncidents() { return new Promise(function (resolve, reject) { // Check cache for incidentData key client.get('incidentData', function (error, reply) { if (reply) { // Cached key exists console.log('Cached key found'); // Parse results var incidents; if (reply === 'undefined') { // No results, return null incidents = null; } else { incidents = JSON.parse(reply); } // Resolve Promise with incident data resolve(incidents); } else { // Cached key does not exist console.log('Cached key not found'); // Define URL to use for the API var apiUrl = `${process.env.INCIDENT_API_URL}/incidents`; // Make a GET request with the Request libary request(apiUrl, { json: true }, function (error, results, body) { // Store results in cache client.set("incidentData", JSON.stringify(body), 'EX', 60, function (error, reply) { console.log('Stored results in cache'); }); // Resolve Promise with incident data resolve(body); }); } }); }); }
AzureCAT-GSI/DevCamp
HOL/node/03-azuread-office365/start/routes/dashboard.js
JavaScript
mit
2,173
require 'rails_helper' RSpec.describe PusherController, :type => :controller do describe "GET webhook" do it "returns http success" do get :webhook expect(response).to be_success end end end
nnluukhtn/coffee_run
spec/controllers/pusher_controller_spec.rb
Ruby
mit
218
 namespace S22.Xmpp.Extensions { /// <summary> /// Defines possible values for the mood of an XMPP user. /// </summary> /// <remarks>Refer to XEP-0107 for a detailed listing and description of the /// various mood values.</remarks> public enum Mood { /// <summary> /// Impressed with fear or apprehension; in fear; apprehensive. /// </summary> Afraid, /// <summary> /// Astonished; confounded with fear, surprise or wonder. /// </summary> Amazed, /// <summary> /// Inclined to love; having a propensity to love, or to sexual enjoyment; /// loving, fond, affectionate, passionate, lustful, sexual, etc. /// </summary> Amarous, /// <summary> /// Displaying or feeling anger, i.e., a strong feeling of displeasure, hostility /// or antagonism towards someone or something, usually combined with an urge /// to harm. /// </summary> Angry, /// <summary> /// To be disturbed or irritated, especially by continued or repeated acts. /// </summary> Annoyed, /// <summary> /// Full of anxiety or disquietude; greatly concerned or solicitous, esp. /// respecting something future or unknown; being in painful suspense. /// </summary> Anxious, /// <summary> /// To be stimulated in one's feelings, especially to be sexually stimulated. /// </summary> Aroused, /// <summary> /// Feeling shame or guilt. /// </summary> Ashamed, /// <summary> /// Suffering from boredom; uninterested, without attention. /// </summary> Bored, /// <summary> /// Strong in the face of fear; courageous. /// </summary> Brave, /// <summary> /// Peaceful, quiet. /// </summary> Calm, /// <summary> /// Taking care or caution; tentative. /// </summary> Cautious, /// <summary> /// Feeling the sensation of coldness, especially to the point of discomfort. /// </summary> Cold, /// <summary> /// Feeling very sure of or positive about something, especially about one's /// own capabilities. /// </summary> Confident, /// <summary> /// Chaotic, jumbled or muddled. /// </summary> Confused, /// <summary> /// Feeling introspective or thoughtful. /// </summary> Contemplative, /// <summary> /// Pleased at the satisfaction of a want or desire; satisfied. /// </summary> Contented, /// <summary> /// Grouchy, irritable; easily upset. /// </summary> Cranky, /// <summary> /// Feeling out of control; feeling overly excited or enthusiastic. /// </summary> Crazy, /// <summary> /// Feeling original, expressive, or imaginative. /// </summary> Creative, /// <summary> /// Inquisitive; tending to ask questions, investigate, or explore. /// </summary> Curious, /// <summary> /// Feeling sad and dispirited. /// </summary> Dejected, /// <summary> /// Severely despondent and unhappy. /// </summary> Depressed, /// <summary> /// Defeated of expectation or hope; let down. /// </summary> Disappointed, /// <summary> /// Filled with disgust; irritated and out of patience. /// </summary> Disgusted, /// <summary> /// Feeling a sudden or complete loss of courage in the face of trouble or danger. /// </summary> Dismayed, /// <summary> /// Having one's attention diverted; preoccupied. /// </summary> Distracted, /// <summary> /// Having a feeling of shameful discomfort. /// </summary> Embarrassed, /// <summary> /// Feeling pain by the excellence or good fortune of another. /// </summary> Envious, /// <summary> /// Having great enthusiasm. /// </summary> Excited, /// <summary> /// In the mood for flirting. /// </summary> Flirtatious, /// <summary> /// Suffering from frustration; dissatisfied, agitated, or discontented because /// one is unable to perform an action or fulfill a desire. /// </summary> Frustrated, /// <summary> /// Feeling appreciation or thanks. /// </summary> Grateful, /// <summary> /// Feeling very sad about something, especially something lost; mournful; /// sorrowful. /// </summary> Grieving, /// <summary> /// Unhappy and irritable. /// </summary> Grumpy, /// <summary> /// Feeling responsible for wrongdoing; feeling blameworthy. /// </summary> Guilty, /// <summary> /// Experiencing the effect of favourable fortune; having the feeling arising /// from the consciousness of well-being or of enjoyment; enjoying good of /// any kind, as peace, tranquillity, comfort; contented; joyous. /// </summary> Happy, /// <summary> /// Having a positive feeling, belief, or expectation that something wished /// for can or will happen. /// </summary> Hopeful, /// <summary> /// Feeling the sensation of heat, especially to the point of discomfort. /// </summary> Hot, /// <summary> /// Having or showing a modest or low estimate of one's own importance; /// feeling lowered in dignity or importance. /// </summary> Humbled, /// <summary> /// Feeling deprived of dignity or self-respect. /// </summary> Humiliated, /// <summary> /// Having a physical need for food. /// </summary> Hungry, /// <summary> /// Wounded, injured, or pained, whether physically or emotionally. /// </summary> Hurt, /// <summary> /// Favourably affected by something or someone. /// </summary> Impressed, /// <summary> /// Feeling amazement at something or someone; or feeling a combination /// of fear and reverence. /// </summary> InAwe, /// <summary> /// Feeling strong affection, care, liking, or attraction. /// </summary> InLove, /// <summary> /// Showing anger or indignation, especially at something unjust or wrong. /// </summary> Indignant, /// <summary> /// Showing great attention to something or someone; having or showing /// interest. /// </summary> Interested, /// <summary> /// Under the influence of alcohol; drunk. /// </summary> Intoxicated, /// <summary> /// Feeling as if one cannot be defeated, overcome or denied. /// </summary> Invincible, /// <summary> /// Fearful of being replaced in position or affection. /// </summary> Jealous, /// <summary> /// Feeling isolated, empty, or abandoned. /// </summary> Lonely, /// <summary> /// Unable to find one's way, either physically or emotionally. /// </summary> Lost, /// <summary> /// Feeling as if one will be favored by luck. /// </summary> Lucky, /// <summary> /// Causing or intending to cause intentional harm; bearing ill will /// towards another; cruel; malicious. /// </summary> Mean, /// <summary> /// Given to sudden or frequent changes of mind or feeling; temperamental. /// </summary> Moody, /// <summary> /// Easily agitated or alarmed; apprehensive or anxious. /// </summary> Nervous, /// <summary> /// Not having a strong mood or emotional state. /// </summary> Neutral, /// <summary> /// Feeling emotionally hurt, displeased, or insulted. /// </summary> Offended, /// <summary> /// Feeling resentful anger caused by an extremely violent or vicious attack, /// or by an offensive, immoral, or indecent act. /// </summary> Outraged, /// <summary> /// Interested in play; fun, recreational, unserious, lighthearted; joking, /// silly. /// </summary> Playful, /// <summary> /// Feeling a sense of one's own worth or accomplishment. /// </summary> Proud, /// <summary> /// Having an easy-going mood; not stressed; calm. /// </summary> Relaxed, /// <summary> /// Feeling uplifted because of the removal of stress or discomfort. /// </summary> Relieved, /// <summary> /// Feeling regret or sadness for doing something wrong. /// </summary> Remorseful, /// <summary> /// Without rest; unable to be still or quiet; uneasy; continually moving. /// </summary> Restless, /// <summary> /// Feeling sorrow; sorrowful, mournful. /// </summary> Sad, /// <summary> /// Mocking and ironical. /// </summary> Sarcastic, /// <summary> /// Pleased at the fulfillment of a need or desire. /// </summary> Satisfied, /// <summary> /// Without humor or expression of happiness; grave in manner or disposition; /// earnest; thoughtful; solemn. /// </summary> Serious, /// <summary> /// Surprised, startled, confused, or taken aback. /// </summary> Shocked, /// <summary> /// Feeling easily frightened or scared; timid; reserved or coy. /// </summary> Shy, /// <summary> /// Feeling in poor health; ill. /// </summary> Sick, /// <summary> /// Feeling the need for sleep. /// </summary> Sleepy, /// <summary> /// Acting without planning; natural; impulsive. /// </summary> Spontaneous, /// <summary> /// Suffering emotional pressure. /// </summary> Stressed, /// <summary> /// Capable of producing great physical force; or, emotionally forceful, /// able, determined, unyielding. /// </summary> Strong, /// <summary> /// Experiencing a feeling caused by something unexpected. /// </summary> Surprised, /// <summary> /// Showing appreciation or gratitude. /// </summary> Thankful, /// <summary> /// Feeling the need to drink. /// </summary> Thirsty, /// <summary> /// In need of rest or sleep. /// </summary> Tired, /// <summary> /// [Feeling any emotion not defined here.] /// </summary> Undefined, /// <summary> /// Lacking in force or ability, either physical or emotional. /// </summary> Weak, /// <summary> /// Thinking about unpleasant things that have happened or that might /// happen; feeling afraid and unhappy. /// </summary> Worried } }
smiley22/S22.Xmpp
Extensions/XEP-0107/Mood.cs
C#
mit
9,671
using System.Windows.Controls; namespace HeroesMatchTracker.Views.RawData { /// <summary> /// Interaction logic for RawMatchReplaysControl.xaml /// </summary> public partial class RawMatchReplaysControl : UserControl { public RawMatchReplaysControl() { InitializeComponent(); } } }
koliva8245/HeroesParserData
HeroesMatchTracker/Views/RawData/RawMatchReplaysControl.xaml.cs
C#
mit
346
<?php return [ 'nav-back' => '回上一頁', 'nav-new' => '新增資料夾', 'nav-upload' => '上傳檔案', 'nav-thumbnails' => '縮圖顯示', 'nav-list' => '列表顯示', 'menu-rename' => '重新命名', 'menu-delete' => '刪除', 'menu-view' => '預覽', 'menu-download' => '下載', 'menu-resize' => '縮放', 'menu-crop' => '裁剪', 'title-page' => '檔案管理', 'title-panel' => '檔案管理', 'title-upload' => '上傳檔案', 'title-view' => '預覽檔案', 'title-root' => '我的檔案', 'title-shares' => '共享的檔案', 'title-item' => '項目名稱', 'title-size' => '檔案大小', 'title-type' => '檔案類型', 'title-modified' => '上次修改', 'title-action' => '操作', 'type-folder' => '資料夾', 'message-empty' => '空的資料夾', 'message-choose' => '選擇檔案', 'message-delete' => '確定要刪除此項目嗎?', 'message-name' => '資料夾名稱:', 'message-rename' => '重新命名為:', 'message-extension_not_found' => '請安裝 gd 或 imagick 以使用縮放、裁剪、及縮圖功能', 'error-rename' => '名稱重複,請重新輸入!', 'error-file-empty' => '請選擇檔案!', 'error-file-exist' => '相同檔名的檔案已存在!', 'error-file-size' => '檔案過大,無法上傳! (檔案大小上限: :max)', 'error-delete' => '資料夾未清空,無法刪除!', 'error-folder-name' => '請輸入資料夾名稱!', 'error-folder-exist'=> '相同名稱的資料夾已存在!', 'error-folder-alnum'=> '資料夾名稱只能包含英數字!', 'error-mime' => 'Mime 格式錯誤 : ', 'error-instance' => '上傳檔案的 instance 應為 UploadedFile', 'error-invalid' => '驗證失敗,上傳未成功', 'btn-upload' => '上傳', 'btn-uploading' => '上傳中...', 'btn-close' => '關閉', 'btn-crop' => '裁剪', 'btn-cancel' => '取消', 'btn-resize' => '縮放', 'resize-ratio' => '比例:', 'resize-scaled' => '是否已縮放:', 'resize-true' => '是', 'resize-old-height' => '原始高度:', 'resize-old-width' => '原始寬度:', 'resize-new-height' => '目前高度:', 'resize-new-width' => '目前寬度:', 'locale-bootbox' => 'zh_TW', ];
crocodic-studio/simple-stock-manager
vendor/unisharp/laravel-filemanager/src/lang/zh-TW/lfm.php
PHP
mit
2,606
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { version: '<%= pkg.version %>', banner: '// Backbone.Intercept v<%= meta.version %>\n' }, preprocess: { intercept: { src: 'src/wrapper.js', dest: 'dist/backbone.intercept.js' } }, template: { options: { data: { version: '<%= meta.version %>' } }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: '<%= preprocess.intercept.dest %>' } }, concat: { options: { banner: '<%= meta.banner %>' }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: '<%= preprocess.intercept.dest %>' } }, uglify: { options: { banner: '<%= meta.banner %>' }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: 'dist/backbone.intercept.min.js', options: { sourceMap: true } } }, jshint: { intercept: { options: { jshintrc: '.jshintrc' }, src: ['src/backbone.intercept.js'] }, tests: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/unit/*.js'] } }, mochaTest: { spec: { options: { require: 'test/setup/node.js', reporter: 'dot', clearRequireCache: true, mocha: require('mocha') }, src: [ 'test/setup/helpers.js', 'test/unit/*.js' ] } }, connect: { options: { port: 8000, keepalive: true }, browser: {} } }); grunt.registerTask('test:browser', 'Test the library in the browser', [ 'jshint', 'connect' ]); grunt.registerTask('test', 'Test the library', [ 'jshint', 'mochaTest' ]); grunt.registerTask('build', 'Build the library', [ 'test', 'preprocess:intercept', 'template', 'concat', 'uglify' ]); grunt.registerTask('default', 'An alias of test', [ 'test' ]); };
elgubenis/backbone.intercept
gruntfile.js
JavaScript
mit
2,239
System.register([], function (_export, _context) { "use strict"; var p; return { setters: [], execute: function () { _export("p", p = 4); _export("p", p); } }; });
ModuleLoader/es-module-loader
test/fixtures/register-modules/rebinding.js
JavaScript
mit
197
#!/usr/bin/env python """ Apply a surface field to a shape """ from __future__ import print_function import argparse import time import sys import re from numpy import linspace from icqsol.shapes.icqShapeManager import ShapeManager from icqsol import util # time stamp tid = re.sub(r'\.', '', str(time.time())) description = 'Apply a surface field to a shape' parser = argparse.ArgumentParser(description=description) parser.add_argument('--input', dest='input', default='', help='Input file (PLY or VTK)') parser.add_argument('--expression', dest='expression', default='sin(pi*x)*cos(pi*y)*z', help='Expression of x, y, z, and t') parser.add_argument('--refine', dest='refine', default=0.0, type=float, help='Maximum edge length (use 0 if no refinement)') parser.add_argument('--name', dest='name', default='myField', help='Set the name of the field') parser.add_argument('--times', dest='times', default='', help='Comma separated list of time values') parser.add_argument('--location', dest='location', default='point', help='"point" or "cell"') parser.add_argument('--ascii', dest='ascii', action='store_true', help='Save data in ASCII format (default is binary)') parser.add_argument('--output', dest='output', default='addSurfaceFieldFromExpressionToShape-{0}.vtk'.format(tid), help='VTK Output file.') args = parser.parse_args() if not args.expression: print('ERROR: must specify --expression <expression>') sys.exit(2) if not args.input: print('ERROR: must specify input file: --input <file>') sys.exit(3) # make sure the field name contains no spaces args.name = re.sub('\s', '_', args.name) # Get the format of the input - either vtk or ply. file_format = util.getFileFormat(args.input) if file_format == util.PLY_FORMAT: shape_mgr = ShapeManager(file_format=util.PLY_FORMAT) else: # We have a VTK file, so Get the dataset type. vtk_dataset_type = util.getVtkDatasetType(args.input) shape_mgr = ShapeManager(file_format=util.VTK_FORMAT, vtk_dataset_type=vtk_dataset_type) pdata = shape_mgr.loadAsVtkPolyData(args.input) times = [0.0] if args.times: times = eval(args.times) maxEdgeLength = float('inf') if args.refine > 0: maxEdgeLength = args.refine pdataOut = shape_mgr.addSurfaceFieldFromExpressionToVtkPolyData(pdata, args.name, args.expression, times, max_edge_length=maxEdgeLength, location=args.location) if args.output: # Always produce VTK POLYDATA. shape_mgr.setWriter(file_format=util.VTK_FORMAT, vtk_dataset_type=util.POLYDATA) if args.ascii: file_type = util.ASCII else: file_type = util.BINARY shape_mgr.saveVtkPolyData(vtk_poly_data=pdataOut, file_name=args.output, file_type=file_type)
gregvonkuster/icqsol
examples/addSurfaceFieldFromExpression.py
Python
mit
3,166
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Tailviewer.Api; namespace Tailviewer.Core.Filters.ExpressionEngine { internal sealed class IsExpression<T> : IExpression<bool> { private static readonly IEqualityComparer<T> Comparer; private readonly IExpression<T> _lhs; private readonly IExpression<T> _rhs; static IsExpression() { // The default comparer sucks for custom value types as it will cause boxing on every invocation // (https://www.jacksondunstan.com/articles/5148), so we will use our own comparers for types known // to us. if (typeof(T) == typeof(LevelFlags)) { Comparer = (IEqualityComparer<T>)(object)new LevelFlagsComparer(); } else { Comparer = EqualityComparer<T>.Default; } } public IsExpression(IExpression<T> lhs, IExpression<T> rhs) { _lhs = lhs; _rhs = rhs; } #region Implementation of IExpression public Type ResultType => typeof(bool); public bool Evaluate(IReadOnlyList<IReadOnlyLogEntry> logEntry) { var lhs = _lhs.Evaluate(logEntry); var rhs = _rhs.Evaluate(logEntry); return Comparer.Equals(lhs, rhs); } object IExpression.Evaluate(IReadOnlyList<IReadOnlyLogEntry> logEntry) { return Evaluate(logEntry); } #endregion #region Equality members private bool Equals(IsExpression<T> other) { return Equals(_lhs, other._lhs) && Equals(_rhs, other._rhs); } public override bool Equals(object obj) { return ReferenceEquals(this, obj) || obj is IsExpression<T> other && Equals(other); } public override int GetHashCode() { unchecked { return ((_lhs != null ? _lhs.GetHashCode() : 0) * 397) ^ (_rhs != null ? _rhs.GetHashCode() : 0); } } public static bool operator ==(IsExpression<T> left, IsExpression<T> right) { return Equals(left, right); } public static bool operator !=(IsExpression<T> left, IsExpression<T> right) { return !Equals(left, right); } #endregion #region Overrides of Object public override string ToString() { return string.Format("{0} {1} {2}", _lhs, Tokenizer.ToString(TokenType.Is), _rhs); } #endregion [Pure] public static IsExpression<T> Create(IExpression<T> lhs, IExpression<T> rhs) { return new IsExpression<T>(lhs, rhs); } } }
Kittyfisto/Tailviewer
src/Tailviewer.Core/Filters/ExpressionEngine/IsExpression.cs
C#
mit
2,319
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'enrol_imsenterprise', language 'ru', branch 'MOODLE_20_STABLE' * * @package enrol_imsenterprise * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['aftersaving...'] = 'После сохранения своих настроек Вы, возможно, пожелаете'; $string['allowunenrol'] = 'Разрешить данным IMS <strong>отчислять</strong> студентов/преподавателей'; $string['allowunenrol_desc'] = 'При включенном параметре, участник будет отчислен из курса, если это указано в данных организации.'; $string['basicsettings'] = 'Основные настройки'; $string['coursesettings'] = 'Настройки данных курса'; $string['createnewcategories'] = 'Создавать новые (скрытые) категории курсов, если они не найдены в Moodle'; $string['createnewcategories_desc'] = 'Если элемент <org><orgunit> присутствует в данных создаваемого курса, то эта информация будет использоваться для определения категории, если курс должен быть создан с нуля. Плагин НЕ будет изменять категории существующих курсов. Если нет категории с нужным названием, то будет создана скрытая категория.'; $string['createnewcourses'] = 'Создавать новые (скрытые) курсы, если они не найдены в Moodle'; $string['createnewcourses_desc'] = 'При включенном параметре плагин IMS может создать новые курсы для любого из найденных в данных IMS, но не в базе данных в Moodle. Любой вновь созданный курс изначально скрыт.'; $string['createnewusers'] = 'Создать учетные записи для пользователей, еще не зарегистрированных в Moodle'; $string['createnewusers_desc'] = 'IMS Enterprise - типичные данные для регистрации, характеризующие группу пользователей. При включенном параметре учетная запись может быть создана для любого пользователя, отсутствующего в базе данных Moodle. Пользователей сначала ищут по их «ID-номеру», потом - по их логину в Moodle. Пароли не импортируются с помощью плагина IMS Enterprise. Для аутентификации пользователей рекомендуется использовать плагин аутентификации'; $string['cronfrequency'] = 'Частота обработки'; $string['deleteusers'] = 'Удалять учетные записи пользователей, если это указано в данных IMS'; $string['deleteusers_desc'] = 'При включенном параметре в данных IMS можно указать удаление учетных записей пользователей (если в параметре «recstatus» выбран п.3, который означает удаление аккаунта). Как это принято в Moodle, запись пользователя не удаляется из базы данных Moodle, но устанавливается флаг, который помечает аккаунт как удаленный.'; $string['doitnow'] = 'Выполнить импорт IMS прямо сейчас'; $string['filelockedmail'] = 'Процесс cron не может удалить IMS-файл ({$a}), используемый вами для записи на курсы. Обычно это означает, что неправильно установлены права доступа к этому файлу. Пожалуйста, исправьте права доступа так, чтобы система Moodle могла удалять этот файл. В противном случае один и тот же файл будет обрабатываться повторно.'; $string['filelockedmailsubject'] = 'Серьезная ошибка: Файл регистрации'; $string['fixcasepersonalnames'] = 'Изменить личные имена пользователей в Верхний Регистр'; $string['fixcaseusernames'] = 'Изменить логины в нижний регистр'; $string['ignore'] = 'Игнорировать'; $string['importimsfile'] = 'Импорт файла IMS Enterprise'; $string['imsrolesdescription'] = 'Спецификация IMS Enterprise включает в себя 8 различных типов роль. Пожалуйста, выберите, как Вы хотите назначить их в Moodle, при этом любая из них может быть проигнорирована.'; $string['location'] = 'Расположение файла'; $string['logtolocation'] = 'Расположение файла журнала (пусто, если протоколирование не ведется)'; $string['mailadmins'] = 'Уведомить администратора по электронной почте'; $string['mailusers'] = 'Уведомить пользователей по электронной почте'; $string['miscsettings'] = 'Разное'; $string['pluginname'] = 'Файл IMS Enterprise'; $string['pluginname_desc'] = 'Этот способ записи будет неоднократно проверять и обрабатывать специально-форматированный текстовый файл в указанном Вами месте. Файл должен следовать спецификации IMS Enterprise и содержать XML-элементы person, group и membership.'; $string['processphoto'] = 'Добавить данные о фотографии пользователя в профиль'; $string['processphotowarning'] = 'Внимание: обработка изображений может добавить значительную нагрузку на сервер. Рекомендуется не активировать эту опцию, если ожидается обработка большого количества студентов.'; $string['restricttarget'] = 'Обрабатывать данные только если указана следующая цель'; $string['restricttarget_desc'] = 'Файл данных IMS Enterprise может быть предназначен для нескольких «целей» - разных систем обучения или различных систем внутри школы/университета. В файле можно указать, что данные предназначены для одной или нескольких целевых именованных систем, именуя их в тегах <target>, содержащихся в теге <properties>. Обычно Вам не нужно беспокоиться об этом. Оставьте поле пустым и Moodle всегда будет обрабатывать данные файла, независимо от того, задана ли цель или нет. В противном случае введите в поле точное название, которое будет присутствовать внутри тега <target>.'; $string['roles'] = 'Роли'; $string['sourcedidfallback'] = 'Использовать идентификатор «sourcedid» для персонального идентификатора, если поле «userid» не найдено'; $string['sourcedidfallback_desc'] = 'В данных IMS поле <sourcedid> является постоянным ID-кодом человека, используемый в исходной системе. Поле <userid> - это отдельное поле, которое содержит ID-код, используемый пользователем при входе. Во многих случаях эти два кода могут быть одинаковы - но не всегда. Некоторые системы не могут выводить информацию из поля <userid>. В этом случае Вы должны включить этот параметр - разрешить использовать поле <sourcedid> в качестве ID-номера пользователя Moodle. В противном случае оставьте этот параметр отключенным.'; $string['truncatecoursecodes'] = 'Обрезать коды курсов до этой длины'; $string['truncatecoursecodes_desc'] = 'В некоторых случаях перед обработкой Вы можете обрезать коды курсов до указанной длины. Для этого введите нужное количество символов в этом поле. В противном случае оставьте это поле пустым и никаких сокращений не будет.'; $string['usecapitafix'] = 'Отметьте это поле, если используется «Capita» (его формат XML немного неверный)'; $string['usecapitafix_desc'] = 'При получении «Capita» была найдена одна небольшая ошибка в XML-выводе из системы студенческих данных. При использовании «Capita» Вы должны включить этот параметр; в противном случае оставьте его не отмеченным.'; $string['usersettings'] = 'Настройки данных пользователя'; $string['zeroisnotruncation'] = '0 указывает на отсутствие усечения';
tesler/cspt-moodle
moodle/lang/ru/enrol_imsenterprise.php
PHP
mit
11,218
module.exports = { //get global stats 'GET /stat': { controller: "StatController", action: "getGlobalStat" } }
badfuture/huoshui-backend-api
api/routes/statRoute.js
JavaScript
mit
126
/** * Node Native Module for Lib Sodium * * @Author Pedro Paixao * @email paixaop at gmail dot com * @License MIT */ #include "node_sodium.h" /** * int crypto_shorthash( * unsigned char *out, * const unsigned char *in, * unsigned long long inlen, * const unsigned char *key) * * Parameters: * [out] out result of hash * [in] in input buffer * [in] inlen size of input buffer * [in] key key buffer * * A lot of applications and programming language implementations have been * recently found to be vulnerable to denial-of-service attacks when a hash * function with weak security guarantees, like Murmurhash 3, was used to * construct a hash table. * In order to address this, Sodium provides the �shorthash� function, * currently implemented using SipHash-2-4. This very fast hash function * outputs short, but unpredictable (without knowing the secret key) values * suitable for picking a list in a hash table for a given key. */ NAPI_METHOD(crypto_shorthash) { Napi::Env env = info.Env(); ARGS(1, "argument message must be a buffer"); ARG_TO_UCHAR_BUFFER(message); ARG_TO_UCHAR_BUFFER_LEN(key, crypto_shorthash_KEYBYTES); NEW_BUFFER_AND_PTR(hash, crypto_shorthash_BYTES); if( crypto_shorthash(hash_ptr, message, message_size, key) == 0 ) { return hash; } else { return NAPI_NULL; } } /** * Register function calls in node binding */ void register_crypto_shorthash(Napi::Env env, Napi::Object exports) { // Short Hash EXPORT(crypto_shorthash); EXPORT_INT(crypto_shorthash_BYTES); EXPORT_INT(crypto_shorthash_KEYBYTES); EXPORT_STRING(crypto_shorthash_PRIMITIVE); }
paixaop/node-sodium
src/crypto_shorthash.cc
C++
mit
1,709
# frozen_string_literal: true Capybara::SpecHelper.spec '#scroll_to', requires: [:scroll] do before do @session.visit('/scroll') end it 'can scroll an element to the top of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :top) expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(1).of(0) end it 'can scroll an element to the bottom of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :bottom) el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom') viewport_bottom = el.evaluate_script('document.documentElement.clientHeight') expect(el_bottom).to be_within(1).of(viewport_bottom) end it 'can scroll an element to the center of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :center) el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())') viewport_bottom = el.evaluate_script('document.documentElement.clientHeight') expect(el_center).to be_within(2).of(viewport_bottom / 2) end it 'can scroll the window to the vertical top' do @session.scroll_to :bottom @session.scroll_to :top expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, 0] end it 'can scroll the window to the vertical bottom' do @session.scroll_to :bottom max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight') expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, max_scroll] end it 'can scroll the window to the vertical center' do @session.scroll_to :center max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight') expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, max_scroll / 2] end it 'can scroll the window to specific location' do @session.scroll_to 100, 100 expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [100, 100] end it 'can scroll an element to the top of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :top) scrolling_element_top = scrolling_element.evaluate_script('this.getBoundingClientRect().top') expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(3).of(scrolling_element_top) end it 'can scroll an element to the bottom of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :bottom) el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom') scroller_bottom = scrolling_element.evaluate_script('this.getBoundingClientRect().top + this.clientHeight') expect(el_bottom).to be_within(1).of(scroller_bottom) end it 'can scroll an element to the center of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :center) el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())') scrollable_center = scrolling_element.evaluate_script('(this.clientHeight / 2) + this.getBoundingClientRect().top') expect(el_center).to be_within(1).of(scrollable_center) end it 'can scroll the scrolling element to the top' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :bottom scrolling_element.scroll_to :top expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, 0] end it 'can scroll the scrolling element to the bottom' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :bottom max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight') expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, max_scroll] end it 'can scroll the scrolling element to the vertical center' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :center max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight') expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, max_scroll / 2] end it 'can scroll the scrolling element to specific location' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to 100, 100 expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [100, 100] end it 'can scroll the window by a specific amount' do @session.scroll_to(:current, offset: [50, 75]) expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [50, 75] end it 'can scroll the scroll the scrolling element by a specific amount' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to 100, 100 scrolling_element.scroll_to(:current, offset: [-50, 50]) expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [50, 150] end end
jnicklas/capybara
lib/capybara/spec/session/scroll_spec.rb
Ruby
mit
5,689
package main import ( "context" "encoding/json" "log" "os" "path/filepath" "time" "github.com/mafredri/cdp" "github.com/mafredri/cdp/devtool" "github.com/mafredri/cdp/protocol/page" "github.com/mafredri/cdp/rpcc" ) func main() { dir, err := os.Getwd() if err != nil { log.Fatal(err) } if err := run(context.TODO(), dir); err != nil { log.Fatal(err) } } func run(ctx context.Context, dir string) error { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, 10*time.Second) defer cancel() devt := devtool.New("http://localhost:9222") pt, err := devt.Get(ctx, devtool.Page) if err != nil { return err } conn, err := rpcc.Dial(pt.WebSocketDebuggerURL) if err != nil { return err } defer conn.Close() c := cdp.NewClient(conn) input, err := os.Create(filepath.Join(dir, "log.input")) if err != nil { return err } consoleAPICalled, err := c.Runtime.ConsoleAPICalled(ctx) if err != nil { return err } go func() { defer consoleAPICalled.Close() for { ev, err := consoleAPICalled.Recv() if err != nil { return } // Reset fields that would cause noise in diffs. ev.ExecutionContextID = 0 ev.Timestamp = 0 ev.StackTrace = nil for i, arg := range ev.Args { arg.ObjectID = nil ev.Args[i] = arg } if err = json.NewEncoder(input).Encode(ev); err != nil { log.Println(err) return } } }() domLoadTimeout := 5 * time.Second // First page load is to trigger console log behavior without object // previews. if err := navigate(c.Page, "file:///"+dir+"/log.html", domLoadTimeout); err != nil { return err } // Enable console log events. if err := c.Runtime.Enable(ctx); err != nil { return err } // Re-load the page to receive console logs with previews. if err := navigate(c.Page, "file:///"+dir+"/log.html", domLoadTimeout); err != nil { return err } time.Sleep(250 * time.Millisecond) if err := input.Close(); err != nil { return err } return nil } // navigate to the URL and wait for DOMContentEventFired. An error is // returned if timeout happens before DOMContentEventFired. func navigate(pc cdp.Page, url string, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Enable the Page domain events. if err := pc.Enable(ctx); err != nil { return err } // Open client for DOMContentEventFired to pause execution until // DOM has fully loaded. domContentEventFired, err := pc.DOMContentEventFired(ctx) if err != nil { return err } defer domContentEventFired.Close() _, err = pc.Navigate(ctx, page.NewNavigateArgs(url)) if err != nil { return err } _, err = domContentEventFired.Recv() return err }
mafredri/cdp
protocol/runtime/testdata/log_input_gen.go
GO
mit
2,730
<?php namespace BeSimple\SoapClient\Tests\AxisInterop; class TestCase extends \PHPUnit_Framework_TestCase { protected function setUp() { $ch = curl_init('http://localhost:8080/'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (curl_exec($ch) === false) { $this->markTestSkipped( 'The Axis server is not started on port 8080.' ); } curl_close($ch); } }
MarkThink/OROCRM
vendor/bundles/besimple/soap/src/BeSimple/SoapClient/Tests/AxisInterop/TestCase.php
PHP
mit
602
'use strict'; var digits = require('./../../../utils/number').digits; // TODO this could be improved by simplifying seperated constants under associative and commutative operators function factory(type, config, load, typed, math) { var util = load(require('./util')); var isCommutative = util.isCommutative; var isAssociative = util.isAssociative; var allChildren = util.allChildren; var createMakeNodeFunction = util.createMakeNodeFunction; var ConstantNode = math.expression.node.ConstantNode; var OperatorNode = math.expression.node.OperatorNode; var FunctionNode = math.expression.node.FunctionNode; function simplifyConstant(expr) { var res = foldFraction(expr); return type.isNode(res) ? res : _toNode(res); } function _eval(fnname, args) { try { return _toNumber(math[fnname].apply(null, args)); } catch (ignore) { // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions args = args.map(function(x){ if (type.isFraction(x)) { return x.valueOf(); } return x; }); return _toNumber(math[fnname].apply(null, args)); } } var _toNode = typed({ 'Fraction': _fractionToNode, 'number': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(-n)); } return new ConstantNode(n); }, 'BigNumber': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(n.negated().toString(), 'number')); } return new ConstantNode(n.toString(), 'number'); }, 'Complex': function(s) { throw 'Cannot convert Complex number to Node'; } }); // convert a number to a fraction only if it can be expressed exactly function _exactFraction(n) { if (isFinite(n)) { var f = math.fraction(n); if (f.valueOf() === n) { return f; } } return n; } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex // BigNumbers are left alone var _toNumber = typed({ 'string': function(s) { if (config.number === 'BigNumber') { return math.bignumber(s); } else if (config.number === 'Fraction') { return math.fraction(s); } else { return _exactFraction(parseFloat(s)); } }, 'Fraction': function(s) { return s; }, 'BigNumber': function(s) { return s; }, 'number': function(s) { return _exactFraction(s); }, 'Complex': function(s) { if (s.im !== 0) { return s; } return _exactFraction(s.re); }, }); function unaryMinusNode(n) { return new OperatorNode('-', 'unaryMinus', [n]); } function _fractionToNode(f) { var n; var vn = f.s*f.n; if (vn < 0) { n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]) } else { n = new ConstantNode(vn); } if (f.d === 1) { return n; } return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]); } /* * Create a binary tree from a list of Fractions and Nodes. * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so * `args` should be sorted to have the Fractions at the start (if the operator is commutative). * @param args - list of Fractions and Nodes * @param fn - evaluator for the binary operation evaluator that accepts two Fractions * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes * if args.length is 1, returns args[0] * @return - Either a Node representing a binary expression or Fraction */ function foldOp(fn, args, makeNode) { return args.reduce(function(a, b) { if (!type.isNode(a) && !type.isNode(b)) { try { return _eval(fn, [a,b]); } catch (ignoreandcontinue) {} a = _toNode(a); b = _toNode(b); } else if (!type.isNode(a)) { a = _toNode(a); } else if (!type.isNode(b)) { b = _toNode(b); } return makeNode([a, b]); }); } // destroys the original node and returns a folded one function foldFraction(node) { switch(node.type) { case 'SymbolNode': return node; case 'ConstantNode': if (node.valueType === 'number') { return _toNumber(node.value); } return node; case 'FunctionNode': if (math[node.name] && math[node.name].rawArgs) { return node; } // Process operators as OperatorNode var operatorFunctions = [ 'add', 'multiply' ]; if (operatorFunctions.indexOf(node.name) === -1) { var args = node.args.map(foldFraction); // If all args are numbers if (!args.some(type.isNode)) { try { return _eval(node.name, args); } catch (ignoreandcontine) {} } // Convert all args to nodes and construct a symbolic function call args = args.map(function(arg) { return type.isNode(arg) ? arg : _toNode(arg); }); return new FunctionNode(node.name, args); } else { // treat as operator } /* falls through */ case 'OperatorNode': var fn = node.fn.toString(); var args; var res; var makeNode = createMakeNodeFunction(node); if (node.args.length === 1) { args = [foldFraction(node.args[0])]; if (!type.isNode(args[0])) { res = _eval(fn, args); } else { res = makeNode(args); } } else if (isAssociative(node)) { args = allChildren(node); args = args.map(foldFraction); if (isCommutative(fn)) { // commutative binary operator var consts = [], vars = []; for (var i=0; i < args.length; i++) { if (!type.isNode(args[i])) { consts.push(args[i]); } else { vars.push(args[i]); } } if (consts.length > 1) { res = foldOp(fn, consts, makeNode); vars.unshift(res); res = foldOp(fn, vars, makeNode); } else { // we won't change the children order since it's not neccessary res = foldOp(fn, args, makeNode); } } else { // non-commutative binary operator res = foldOp(fn, args, makeNode); } } else { // non-associative binary operator args = node.args.map(foldFraction); res = foldOp(fn, args, makeNode); } return res; case 'ParenthesisNode': // remove the uneccessary parenthesis return foldFraction(node.content); case 'AccessorNode': /* falls through */ case 'ArrayNode': /* falls through */ case 'AssignmentNode': /* falls through */ case 'BlockNode': /* falls through */ case 'FunctionAssignmentNode': /* falls through */ case 'IndexNode': /* falls through */ case 'ObjectNode': /* falls through */ case 'RangeNode': /* falls through */ case 'UpdateNode': /* falls through */ case 'ConditionalNode': /* falls through */ default: throw 'Unimplemented node type in simplifyConstant: '+node.type; } } return simplifyConstant; } exports.math = true; exports.name = 'simplifyConstant'; exports.path = 'algebra.simplify'; exports.factory = factory;
ocadni/citychrone
node_modules/mathjs/lib/function/algebra/simplify/simplifyConstant.js
JavaScript
mit
7,764
<?php /* If you see this text in your browser, PHP is not configured correctly on this hosting provider. Contact your hosting provider regarding PHP configuration for your site. PHP file generated by Adobe Muse CC 2017.1.0.379 */ function formthrottle_check() { if (!is_writable('.')) { return '8'; } try { if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE)) { $db = new PDO('sqlite:muse-throttle-db.sqlite3'); if ( file_exists('muse-throttle-db') ) { unlink('muse-throttle-db'); } } else if (function_exists("sqlite_open")) { $db = new PDO('sqlite2:muse-throttle-db'); if ( file_exists('muse-throttle-db.sqlite3') ) { unlink('muse-throttle-db.sqlite3'); } } else { return '4'; } } catch( PDOException $Exception ) { return '9'; } $retCode ='5'; if ($db) { $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';"); if (!$res or $res->fetchColumn() == 0) { $created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)"); if($created == 0) { $created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))"); } if ($created != 1) { $retCode = '2'; } } if($retCode == '5') { $res = $db->query("SELECT COUNT(1) FROM Submission_History;"); if ($res && $res->fetchColumn() > 0) { $retCode = '0'; } else $retCode = '3'; } // Close file db connection $db = null; } else $retCode = '4'; return $retCode; } function formthrottle_too_many_submissions($ip) { $tooManySubmissions = false; try { if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE)) { $db = new PDO('sqlite:muse-throttle-db.sqlite3'); } else if (function_exists("sqlite_open")) { $db = new PDO('sqlite2:muse-throttle-db'); } else { return false; } } catch( PDOException $Exception ) { return $tooManySubmissions; } if ($db) { $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';"); if (!$res or $res->fetchColumn() == 0) { $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)"); } $db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')"); $stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))"); $stmt->bindParam(':ip', $ip); $stmt->execute(); $stmt->closeCursor(); $stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;"); $stmt->bindParam(':ip', $ip); $stmt->execute(); if ($stmt->fetchColumn() > 25) $tooManySubmissions = true; // Close file db connection $db = null; } return $tooManySubmissions; } ?>
valesbc/valesbc.github.io
scripts/form_throttle.php
PHP
mit
2,961
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2022 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Rotates the vertices of a Face to the given angle. * * The actual vertex positions are adjusted, not their transformed positions. * * Therefore, this updates the vertex data directly. * * @function Phaser.Geom.Mesh.RotateFace * @since 3.50.0 * * @param {Phaser.Geom.Mesh.Face} face - The Face to rotate. * @param {number} angle - The angle to rotate to, in radians. * @param {number} [cx] - An optional center of rotation. If not given, the Face in-center is used. * @param {number} [cy] - An optional center of rotation. If not given, the Face in-center is used. */ var RotateFace = function (face, angle, cx, cy) { var x; var y; // No point of rotation? Use the inCenter instead, then. if (cx === undefined && cy === undefined) { var inCenter = face.getInCenter(); x = inCenter.x; y = inCenter.y; } var c = Math.cos(angle); var s = Math.sin(angle); var v1 = face.vertex1; var v2 = face.vertex2; var v3 = face.vertex3; var tx = v1.x - x; var ty = v1.y - y; v1.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v2.x - x; ty = v2.y - y; v2.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v3.x - x; ty = v3.y - y; v3.set(tx * c - ty * s + x, tx * s + ty * c + y); }; module.exports = RotateFace;
photonstorm/phaser
src/geom/mesh/RotateFace.js
JavaScript
mit
1,512
/******************************************************************************* * Copyright (c) 2013-2016 LAAS-CNRS (www.laas.fr) * 7 Colonel Roche 31077 Toulouse - France * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Initial Contributors: * Thierry Monteil : Project manager, technical co-manager * Mahdi Ben Alaya : Technical co-manager * Samir Medjiah : Technical co-manager * Khalil Drira : Strategy expert * Guillaume Garzone : Developer * François Aïssaoui : Developer * * New contributors : *******************************************************************************/ package org.eclipse.om2m.core.controller; import org.eclipse.om2m.commons.exceptions.NotImplementedException; import org.eclipse.om2m.commons.exceptions.OperationNotAllowed; import org.eclipse.om2m.commons.resource.RequestPrimitive; import org.eclipse.om2m.commons.resource.ResponsePrimitive; /** * Controller for polling channel URI * */ public class PollingChannelUriController extends Controller { @Override public ResponsePrimitive doCreate(RequestPrimitive request) { throw new OperationNotAllowed("Create on PollingChannelUri is not allowed"); } @Override public ResponsePrimitive doRetrieve(RequestPrimitive request) { throw new NotImplementedException("Retrieve operation on PollingChannelURI is not implemented"); } @Override public ResponsePrimitive doUpdate(RequestPrimitive request) { throw new OperationNotAllowed("Update on PollingChannelUri is not allowed"); } @Override public ResponsePrimitive doDelete(RequestPrimitive request) { throw new OperationNotAllowed("Delete on PollingChannelUri is not allowed"); } }
cloudcomputinghust/IoT
docker/oneM2M/CSE_IPE/org.eclipse.om2m/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/PollingChannelUriController.java
Java
mit
1,885
/*! * iCheck v1.0.3, http://git.io/arlzeA * =================================== * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Sultanov, http://fronteed.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ip(hone|od|ad)|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]', stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); } }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'destroy') { tidy(self, 'ifDestroyed'); } else { operate(self, true, options); } // Fire method's callback if ($.isFunction(fire)) { fire(); } }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = 'input[type="' + selector + '"]'; } // Clickable area limit if (area < -50) { area = -50; } // Walk around the selector walker(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Check ARIA option aria = !!settings.aria, // Set ARIA placeholder ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6), // Parent & helper parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''), helper; // Set ARIA "labelledby" if (aria) { label.each(function() { parent += 'aria-labelledby="'; if (this.id) { parent += this.id; } else { this.id = ariaID; parent += ariaID; } parent += '"'; }); } // Wrap input parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert); // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className || ''); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { if ($(event.target).is('a')) { return; } operate(self, false, true); // Hover state } else if (labelHover) { // mouseout|touchend if (/ut|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); } // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); } } return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); } }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); } // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); }); } else { return this; } }; // Do something with inputs function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var each in active) { if (active[each]) { on(input, each, true); } else { off(input, each, true); } } } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); } // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); } } else { on(input, state); } } } // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); } }); } // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); } // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; } // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); } } // Trigger callbacks callbacks(input, checked, state, keep); } // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); } // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'true'); } // Remove regular state class parent[_remove](regular || option(input, callback) || ''); } // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; } // Trigger callbacks callbacks(input, checked, callback, keep); } // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); } // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'false'); } // Add regular state class parent[_add](regular || option(input, callback) || ''); } // Remove all traces function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); } // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); } } // Get some option function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; } } // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); } input[_callback]('change')[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); } } })(window.jQuery || window.Zepto);
cdnjs/cdnjs
ajax/libs/iCheck/1.0.3/icheck.js
JavaScript
mit
14,225
module Voting class Domain include DataMapper::Resource property :id, Serial property :name, String property :created_at, DateTime property :updated_at, DateTime has n, :users, :class_name => "Voting::User", :child_key => [:domain_id] validates_present :name validates_is_unique :name end end
zapnap/voting
lib/voting/domain.rb
Ruby
mit
352
// Type definitions for @ag-grid-community/core v25.0.1 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { Column } from "../entities/column"; import { CellChangedEvent, RowNode } from "../entities/rowNode"; import { CellEvent, FlashCellsEvent } from "../events"; import { Beans } from "./beans"; import { Component } from "../widgets/component"; import { ICellEditorComp } from "../interfaces/iCellEditor"; import { ICellRendererComp } from "./cellRenderers/iCellRenderer"; import { ColDef } from "../entities/colDef"; import { CellPosition } from "../entities/cellPosition"; import { RowComp } from "./row/rowComp"; import { IFrameworkOverrides } from "../interfaces/iFrameworkOverrides"; import { TooltipParentComp } from '../widgets/tooltipFeature'; import { ITooltipParams } from "./tooltipComponent"; export declare class CellComp extends Component implements TooltipParentComp { static DOM_DATA_KEY_CELL_COMP: string; private static CELL_RENDERER_TYPE_NORMAL; private static CELL_RENDERER_TYPE_PINNED; private eCellWrapper; private eCellValue; private beans; private column; private rowNode; private eParentRow; private cellPosition; private rangeCount; private hasChartRange; private usingWrapper; private wrapText; private includeSelectionComponent; private includeRowDraggingComponent; private includeDndSourceComponent; private cellFocused; private editingCell; private cellEditorInPopup; private hideEditorPopup; private createCellRendererFunc; private lastIPadMouseClickEvent; private usingCellRenderer; private cellRendererType; private cellRenderer; private cellRendererGui; private cellEditor; private selectionHandle; private autoHeightCell; private firstRightPinned; private lastLeftPinned; private rowComp; private rangeSelectionEnabled; private value; private valueFormatted; private colsSpanning; private rowSpan; private suppressRefreshCell; private tooltipFeatureEnabled; private tooltip; private scope; private readonly printLayout; private cellEditorVersion; private cellRendererVersion; constructor(scope: any, beans: Beans, column: Column, rowNode: RowNode, rowComp: RowComp, autoHeightCell: boolean, printLayout: boolean); getCreateTemplate(): string; private getStylesForRowSpanning; afterAttached(): void; private createTooltipFeatureIfNeeded; onColumnHover(): void; onCellChanged(event: CellChangedEvent): void; private getCellLeft; private getCellWidth; onFlashCells(event: FlashCellsEvent): void; private setupColSpan; getColSpanningList(): Column[]; private onDisplayColumnsChanged; private refreshAriaIndex; private getInitialCssClasses; getInitialValueToRender(): string; getRenderedRow(): RowComp; isSuppressNavigable(): boolean; getCellRenderer(): ICellRendererComp | null; getCellEditor(): ICellEditorComp | null; onNewColumnsLoaded(): void; private postProcessWrapText; refreshCell(params?: { suppressFlash?: boolean; newData?: boolean; forceRefresh?: boolean; }): void; flashCell(delays?: { flashDelay: number; fadeDelay: number; }): void; private animateCell; private replaceContentsAfterRefresh; private updateAngular1ScopeAndCompile; private angular1Compile; private postProcessStylesFromColDef; private preProcessStylesFromColDef; private processStylesFromColDef; private postProcessClassesFromColDef; private preProcessClassesFromColDef; private processClassesFromColDef; private putDataIntoCellAfterRefresh; attemptCellRendererRefresh(): boolean; private refreshToolTip; private valuesAreEqual; private getToolTip; getTooltipParams(): ITooltipParams; private getTooltipText; private processCellClassRules; private postProcessCellClassRules; private preProcessCellClassRules; setUsingWrapper(): void; private chooseCellRenderer; private createCellRendererInstance; private afterCellRendererCreated; private createCellRendererParams; private formatValue; private getValueToUse; private getValueAndFormat; private getValue; onMouseEvent(eventName: string, mouseEvent: MouseEvent): void; dispatchCellContextMenuEvent(event: Event): void; createEvent(domEvent: Event | null, eventType: string): CellEvent; private onMouseOut; private onMouseOver; private onCellDoubleClicked; startRowOrCellEdit(keyPress?: number | null, charPress?: string): void; isCellEditable(): boolean; startEditingIfEnabled(keyPress?: number | null, charPress?: string | null, cellStartedEdit?: boolean): void; private createCellEditor; private afterCellEditorCreated; private addInCellEditor; private addPopupCellEditor; private onPopupEditorClosed; private setInlineEditingClass; private createCellEditorParams; private stopEditingAndFocus; private parseValue; focusCell(forceBrowserFocus?: boolean): void; setFocusInOnEditor(): void; isEditing(): boolean; onKeyDown(event: KeyboardEvent): void; setFocusOutOnEditor(): void; private onNavigationKeyPressed; private onShiftRangeSelect; private onTabKeyDown; private onBackspaceOrDeleteKeyPressed; private onEnterKeyDown; private navigateAfterEdit; private onF2KeyDown; private onEscapeKeyDown; onKeyPress(event: KeyboardEvent): void; private onSpaceKeyPressed; private onMouseDown; private isRightClickInExistingRange; private containsWidget; private isDoubleClickOnIPad; private onCellClicked; private createGridCellVo; getCellPosition(): CellPosition; getParentRow(): HTMLElement; setParentRow(eParentRow: HTMLElement): void; getColumn(): Column; getComponentHolder(): ColDef; detach(): void; destroy(): void; onLeftChanged(): void; private modifyLeftForPrintLayout; onWidthChanged(): void; private getRangeBorders; private getInitialRangeClasses; onRowIndexChanged(): void; onRangeSelectionChanged(): void; private getHasChartRange; private shouldHaveSelectionHandle; private addSelectionHandle; updateRangeBordersIfRangeCount(): void; private refreshHandle; private updateRangeBorders; onFirstRightPinnedChanged(): void; onLastLeftPinnedChanged(): void; private populateTemplate; protected getFrameworkOverrides(): IFrameworkOverrides; private addRowDragging; private addDndSource; private addSelectionCheckbox; private addDomData; private isSingleCell; onCellFocused(event?: any): void; stopRowOrCellEdit(cancel?: boolean): void; stopEditing(cancel?: boolean): void; private clearCellElement; }
ceolter/angular-grid
community-modules/core/dist/es6/rendering/cellComp.d.ts
TypeScript
mit
6,950
using System; using Csla; namespace Invoices.DataAccess.Sql { public partial class ProductTypeCachedNVLDal { } }
CslaGenFork/CslaGenFork
trunk/CoverageTest/Invoices-CS-DAL-DR/Invoices.DataAccess.Sql/ProductTypeCachedNVLDal.cs
C#
mit
135
const Route = require('../../structures/Route'); class usersGET extends Route { constructor() { super('/admin/users', 'get', { adminOnly: true }); } async run(req, res, db) { try { const users = await db.table('users') .select('id', 'username', 'enabled', 'isAdmin', 'createdAt'); return res.json({ message: 'Successfully retrieved users', users }); } catch (error) { return super.error(res, error); } } } module.exports = usersGET;
WeebDev/lolisafe
src/api/routes/admin/usersGET.js
JavaScript
mit
473
import { Autowired, Bean, BeanStub, XmlElement } from '@ag-grid-community/core'; import coreFactory from './files/ooxml/core'; import contentTypesFactory from './files/ooxml/contentTypes'; import officeThemeFactory from './files/ooxml/themes/office'; import sharedStringsFactory from './files/ooxml/sharedStrings'; import stylesheetFactory, { registerStyles } from './files/ooxml/styles/stylesheet'; import workbookFactory from './files/ooxml/workbook'; import worksheetFactory from './files/ooxml/worksheet'; import relationshipsFactory from './files/ooxml/relationships'; import { ExcelStyle, ExcelWorksheet } from '@ag-grid-community/core'; import { XmlFactory } from "@ag-grid-community/csv-export"; /** * See https://www.ecma-international.org/news/TC45_current_work/OpenXML%20White%20Paper.pdf */ @Bean('excelXlsxFactory') export class ExcelXlsxFactory extends BeanStub { @Autowired('xmlFactory') private xmlFactory: XmlFactory; private sharedStrings: string[] = []; private sheetNames: string[]; public createSharedStrings(): string { return this.createXmlPart(sharedStringsFactory.getTemplate(this.sharedStrings)); } private createXmlPart(body: XmlElement): string { const header = this.xmlFactory.createHeader({ encoding: 'UTF-8', standalone: 'yes' }); const xmlBody = this.xmlFactory.createXml(body); return `${header}${xmlBody}`; } public createExcel(styles: ExcelStyle[], worksheets: ExcelWorksheet[], sharedStrings: string[] = []): string { this.sharedStrings = sharedStrings; this.sheetNames = worksheets.map(worksheet => worksheet.name); registerStyles(styles); return this.createWorksheet(worksheets); } public createCore(): string { return this.createXmlPart(coreFactory.getTemplate()); } public createContentTypes(): string { return this.createXmlPart(contentTypesFactory.getTemplate()); } public createRels(): string { const rs = relationshipsFactory.getTemplate([{ Id: 'rId1', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', Target: 'xl/workbook.xml' }, { Id: 'rId2', Type: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', Target: 'docProps/core.xml' }]); return this.createXmlPart(rs); } public createStylesheet(): string { return this.createXmlPart(stylesheetFactory.getTemplate()); } public createTheme(): string { return this.createXmlPart(officeThemeFactory.getTemplate()); } public createWorkbook(): string { return this.createXmlPart(workbookFactory.getTemplate(this.sheetNames)); } public createWorkbookRels(): string { const rs = relationshipsFactory.getTemplate([{ Id: 'rId1', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', Target: 'worksheets/sheet1.xml' }, { Id: 'rId2', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme', Target: 'theme/theme1.xml' }, { Id: 'rId3', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', Target: 'styles.xml' }, { Id: 'rId4', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', Target: 'sharedStrings.xml' }]); return this.createXmlPart(rs); } public createWorksheet(worksheets: ExcelWorksheet[]): string { return this.createXmlPart(worksheetFactory.getTemplate(worksheets[0])); } }
ceolter/angular-grid
enterprise-modules/excel-export/src/excelExport/excelXlsxFactory.ts
TypeScript
mit
3,835
function DetailCellRenderer() {} DetailCellRenderer.prototype.init = function(params) { this.eGui = document.createElement('div'); this.eGui.innerHTML = '<h1 style="padding: 20px;">My Custom Detail</h1>'; }; DetailCellRenderer.prototype.getGui = function() { return this.eGui; };
ceolter/angular-grid
grid-packages/ag-grid-docs/documentation/src/pages/master-detail-custom-detail/examples/simple-custom-detail/detailCellRenderer_vanilla.js
JavaScript
mit
294
/* * * * (c) 2009-2017 Highsoft, Black Label * * License: www.highcharts.com/license * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, erase = U.erase, extend = U.extend, pick = U.pick, splat = U.splat, wrap = U.wrap; import '../parts/Chart.js'; import controllableMixin from './controllable/controllableMixin.js'; import ControllableRect from './controllable/ControllableRect.js'; import ControllableCircle from './controllable/ControllableCircle.js'; import ControllablePath from './controllable/ControllablePath.js'; import ControllableImage from './controllable/ControllableImage.js'; import ControllableLabel from './controllable/ControllableLabel.js'; import eventEmitterMixin from './eventEmitterMixin.js'; import MockPoint from './MockPoint.js'; import ControlPoint from './ControlPoint.js'; var merge = H.merge, addEvent = H.addEvent, fireEvent = H.fireEvent, find = H.find, reduce = H.reduce, chartProto = H.Chart.prototype; /* ********************************************************************* * * ANNOTATION * ******************************************************************** */ /** * @typedef { * Annotation.ControllableCircle| * Annotation.ControllableImage| * Annotation.ControllablePath| * Annotation.ControllableRect * } * Annotation.Shape */ /** * @typedef {Annotation.ControllableLabel} Annotation.Label */ /** * An annotation class which serves as a container for items like labels or * shapes. Created items are positioned on the chart either by linking them to * existing points or created mock points * * @class * @name Highcharts.Annotation * * @param {Highcharts.Chart} chart a chart instance * @param {Highcharts.AnnotationsOptions} userOptions the options object */ var Annotation = H.Annotation = function (chart, userOptions) { var labelsAndShapes; /** * The chart that the annotation belongs to. * * @type {Highcharts.Chart} */ this.chart = chart; /** * The array of points which defines the annotation. * * @type {Array<Highcharts.Point>} */ this.points = []; /** * The array of control points. * * @type {Array<Annotation.ControlPoint>} */ this.controlPoints = []; this.coll = 'annotations'; /** * The array of labels which belong to the annotation. * * @type {Array<Annotation.Label>} */ this.labels = []; /** * The array of shapes which belong to the annotation. * * @type {Array<Annotation.Shape>} */ this.shapes = []; /** * The options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.options = merge(this.defaultOptions, userOptions); /** * The user options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.userOptions = userOptions; // Handle labels and shapes - those are arrays // Merging does not work with arrays (stores reference) labelsAndShapes = this.getLabelsAndShapesOptions( this.options, userOptions ); this.options.labels = labelsAndShapes.labels; this.options.shapes = labelsAndShapes.shapes; /** * The callback that reports to the overlapping-labels module which * labels it should account for. * * @name labelCollector * @memberOf Annotation# * @type {Function} */ /** * The group svg element. * * @name group * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's shapes. * * @name shapesGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's labels. * * @name labelsGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ this.init(chart, this.options); }; merge( true, Annotation.prototype, controllableMixin, eventEmitterMixin, /** @lends Annotation# */ { /** * List of events for `annotation.options.events` that should not be * added to `annotation.graphic` but to the `annotation`. * * @type {Array<string>} */ nonDOMEvents: ['add', 'afterUpdate', 'drag', 'remove'], /** * A basic type of an annotation. It allows to add custom labels * or shapes. The items can be tied to points, axis coordinates * or chart pixel coordinates. * * @sample highcharts/annotations/basic/ * Basic annotations * @sample highcharts/demo/annotations/ * Advanced annotations * @sample highcharts/css/annotations * Styled mode * @sample highcharts/annotations-advanced/controllable * Controllable items * @sample {highstock} stock/annotations/fibonacci-retracements * Custom annotation, Fibonacci retracement * * @type {Array<*>} * @since 6.0.0 * @requires modules/annotations * @optionparent annotations */ defaultOptions: { /** * Sets an ID for an annotation. Can be user later when removing an * annotation in [Chart#removeAnnotation(id)]( * /class-reference/Highcharts.Chart#removeAnnotation) method. * * @type {string|number} * @apioption annotations.id */ /** * Whether the annotation is visible. * * @sample highcharts/annotations/visible/ * Set annotation visibility */ visible: true, /** * Allow an annotation to be draggable by a user. Possible * values are `"x"`, `"xy"`, `"y"` and `""` (disabled). * * @sample highcharts/annotations/draggable/ * Annotations draggable: 'xy' * * @type {string} * @validvalue ["x", "xy", "y", ""] */ draggable: 'xy', /** * Options for annotation's labels. Each label inherits options * from the labelOptions object. An option from the labelOptions * can be overwritten by config for a specific label. * * @requires modules/annotations */ labelOptions: { /** * The alignment of the annotation's label. If right, * the right side of the label should be touching the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.AlignValue} */ align: 'center', /** * Whether to allow the annotation's labels to overlap. * To make the labels less sensitive for overlapping, * the can be set to 0. * * @sample highcharts/annotations/tooltip-like/ * Hide overlapping labels */ allowOverlap: false, /** * The background color or gradient for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ backgroundColor: 'rgba(0, 0, 0, 0.75)', /** * The border color for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString} */ borderColor: 'black', /** * The border radius in pixels for the annotaiton's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderRadius: 3, /** * The border width in pixels for the annotation's label * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderWidth: 1, /** * A class name for styling by CSS. * * @sample highcharts/css/annotations * Styled mode annotations * * @since 6.0.5 */ className: '', /** * Whether to hide the annotation's label * that is outside the plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels */ crop: false, /** * The label's pixel distance from the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {number} * @apioption annotations.labelOptions.distance */ /** * A * [format](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting) * string for the data label. * * @see [plotOptions.series.dataLabels.format](plotOptions.series.dataLabels.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.format */ /** * Alias for the format option. * * @see [format](annotations.labelOptions.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.text */ /** * Callback JavaScript function to format the annotation's * label. Note that if a `format` or `text` are defined, the * format or text take precedence and the formatter is ignored. * `This` refers to a point object. * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {Highcharts.FormatterCallbackFunction<Highcharts.Point>} * @default function () { return defined(this.y) ? this.y : 'Annotation label'; } */ formatter: function () { return defined(this.y) ? this.y : 'Annotation label'; }, /** * How to handle the annotation's label that flow outside the * plot area. The justify option aligns the label inside the * plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels * * @validvalue ["allow", "justify"] */ overflow: 'justify', /** * When either the borderWidth or the backgroundColor is set, * this is the padding within the box. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ padding: 5, /** * The shadow of the box. The shadow can be an object * configuration containing `color`, `offsetX`, `offsetY`, * `opacity` and `width`. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {boolean|Highcharts.ShadowOptionsObject} */ shadow: false, /** * The name of a symbol to use for the border around the label. * Symbols are predefined functions on the Renderer object. * * @sample highcharts/annotations/shapes/ * Available shapes for labels */ shape: 'callout', /** * Styles for the annotation's label. * * @see [plotOptions.series.dataLabels.style](plotOptions.series.dataLabels.style.html) * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.CSSObject} */ style: { /** @ignore */ fontSize: '11px', /** @ignore */ fontWeight: 'normal', /** @ignore */ color: 'contrast' }, /** * Whether to [use HTML](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html) * to render the annotation's label. */ useHTML: false, /** * The vertical alignment of the annotation's label. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.VerticalAlignValue} */ verticalAlign: 'bottom', /** * The x position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ x: 0, /** * The y position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ y: -16 }, /** * An array of labels for the annotation. For options that apply to * multiple labels, they can be added to the * [labelOptions](annotations.labelOptions.html). * * @type {Array<*>} * @extends annotations.labelOptions * @apioption annotations.labels */ /** * This option defines the point to which the label will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @sample highcharts/annotations/mock-point/ * Attach annotation to a mock point * * @type {string|Highcharts.MockPointOptionsObject} * @requires modules/annotations * @apioption annotations.labels.point */ /** * The x position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.x */ /** * The y position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.y */ /** * This number defines which xAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * xAxis array. If the option is not configured or the axis is not * found the point's x coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.xAxis */ /** * This number defines which yAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * yAxis array. If the option is not configured or the axis is not * found the point's y coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.yAxis */ /** * An array of shapes for the annotation. For options that apply to * multiple shapes, then can be added to the * [shapeOptions](annotations.shapeOptions.html). * * @type {Array<*>} * @extends annotations.shapeOptions * @apioption annotations.shapes */ /** * This option defines the point to which the shape will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @type {string|Highcharts.MockPointOptionsObject} * @extends annotations.labels.point * @apioption annotations.shapes.point */ /** * An array of points for the shape. This option is available for * shapes which can use multiple points such as path. A point can be * either a point object or a point's id. * * @see [annotations.shapes.point](annotations.shapes.point.html) * * @type {Array<string|Highcharts.MockPointOptionsObject>} * @extends annotations.labels.point * @apioption annotations.shapes.points */ /** * Id of the marker which will be drawn at the final vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerEnd */ /** * Id of the marker which will be drawn at the first vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample {highcharts} highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerStart */ /** * Options for annotation's shapes. Each shape inherits options from * the shapeOptions object. An option from the shapeOptions can be * overwritten by config for a specific shape. * * @requires modules/annotations */ shapeOptions: { /** * The width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.width **/ /** * The height of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.height */ /** * The type of the shape, e.g. circle or rectangle. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {string} * @default 'rect' * @apioption annotations.shapeOptions.type */ /** * The color of the shape's stroke. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString} */ stroke: 'rgba(0, 0, 0, 0.75)', /** * The pixel stroke width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ strokeWidth: 1, /** * The color of the shape's fill. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ fill: 'rgba(0, 0, 0, 0.75)', /** * The radius of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ r: 0, /** * Defines additional snapping area around an annotation * making this annotation to focus. Defined in pixels. */ snap: 2 }, /** * Options for annotation's control points. Each control point * inherits options from controlPointOptions object. * Options from the controlPointOptions can be overwritten * by options in a specific control point. * * @type {Annotation.ControlPoint.Options} * @requires modules/annotations * @apioption annotations.controlPointOptions */ controlPointOptions: { /** * @function {Annotation.ControlPoint.Positioner} * @apioption annotations.controlPointOptions.positioner */ symbol: 'circle', width: 10, height: 10, style: { stroke: 'black', 'stroke-width': 2, fill: 'white' }, visible: false, events: {} }, /** * Event callback when annotation is added to the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.add */ /** * Event callback when annotation is updated (e.g. drag and * droppped or resized by control points). * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.afterUpdate */ /** * Event callback when annotation is removed from the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.remove */ /** * Events available in annotations. * * @requires modules/annotations */ events: {}, /** * The Z index of the annotation. */ zIndex: 6 }, /** * Initialize the annotation. * * @param {Highcharts.Chart} * The chart * @param {Highcharts.AnnotationsOptions} * The user options for the annotation */ init: function () { this.linkPoints(); this.addControlPoints(); this.addShapes(); this.addLabels(); this.addClipPaths(); this.setLabelCollector(); }, getLabelsAndShapesOptions: function (baseOptions, newOptions) { var mergedOptions = {}; ['labels', 'shapes'].forEach(function (name) { if (baseOptions[name]) { mergedOptions[name] = splat(newOptions[name]).map( function (basicOptions, i) { return merge(baseOptions[name][i], basicOptions); } ); } }); return mergedOptions; }, addShapes: function () { (this.options.shapes || []).forEach(function (shapeOptions, i) { var shape = this.initShape(shapeOptions, i); merge(true, this.options.shapes[i], shape.options); }, this); }, addLabels: function () { (this.options.labels || []).forEach(function (labelsOptions, i) { var labels = this.initLabel(labelsOptions, i); merge(true, this.options.labels[i], labels.options); }, this); }, addClipPaths: function () { this.setClipAxes(); if (this.clipXAxis && this.clipYAxis) { this.clipRect = this.chart.renderer.clipRect( this.getClipBox() ); } }, setClipAxes: function () { var xAxes = this.chart.xAxis, yAxes = this.chart.yAxis, linkedAxes = reduce( (this.options.labels || []) .concat(this.options.shapes || []), function (axes, labelOrShape) { return [ xAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.xAxis ] || axes[0], yAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.yAxis ] || axes[1] ]; }, [] ); this.clipXAxis = linkedAxes[0]; this.clipYAxis = linkedAxes[1]; }, getClipBox: function () { return { x: this.clipXAxis.left, y: this.clipYAxis.top, width: this.clipXAxis.width, height: this.clipYAxis.height }; }, setLabelCollector: function () { var annotation = this; annotation.labelCollector = function () { return annotation.labels.reduce( function (labels, label) { if (!label.options.allowOverlap) { labels.push(label.graphic); } return labels; }, [] ); }; annotation.chart.labelCollectors.push( annotation.labelCollector ); }, /** * Set an annotation options. * * @param {Highcharts.AnnotationsOptions} - user options for an annotation */ setOptions: function (userOptions) { this.options = merge(this.defaultOptions, userOptions); }, redraw: function (animation) { this.linkPoints(); if (!this.graphic) { this.render(); } if (this.clipRect) { this.clipRect.animate(this.getClipBox()); } this.redrawItems(this.shapes, animation); this.redrawItems(this.labels, animation); controllableMixin.redraw.call(this, animation); }, /** * @param {Array<(Annotation.Label|Annotation.Shape)>} items * @param {boolean} [animation] */ redrawItems: function (items, animation) { var i = items.length; // needs a backward loop // labels/shapes array might be modified // due to destruction of the item while (i--) { this.redrawItem(items[i], animation); } }, render: function () { var renderer = this.chart.renderer; this.graphic = renderer .g('annotation') .attr({ zIndex: this.options.zIndex, visibility: this.options.visible ? 'visible' : 'hidden' }) .add(); this.shapesGroup = renderer .g('annotation-shapes') .add(this.graphic) .clip(this.chart.plotBoxClip); this.labelsGroup = renderer .g('annotation-labels') .attr({ // hideOverlappingLabels requires translation translateX: 0, translateY: 0 }) .add(this.graphic); if (this.clipRect) { this.graphic.clip(this.clipRect); } this.addEvents(); controllableMixin.render.call(this); }, /** * Set the annotation's visibility. * * @param {Boolean} [visible] - Whether to show or hide an annotation. * If the param is omitted, the annotation's visibility is toggled. */ setVisibility: function (visibility) { var options = this.options, visible = pick(visibility, !options.visible); this.graphic.attr( 'visibility', visible ? 'visible' : 'hidden' ); if (!visible) { this.setControlPointsVisibility(false); } options.visible = visible; }, setControlPointsVisibility: function (visible) { var setItemControlPointsVisibility = function (item) { item.setControlPointsVisibility(visible); }; controllableMixin.setControlPointsVisibility.call( this, visible ); this.shapes.forEach(setItemControlPointsVisibility); this.labels.forEach(setItemControlPointsVisibility); }, /** * Destroy the annotation. This function does not touch the chart * that the annotation belongs to (all annotations are kept in * the chart.annotations array) - it is recommended to use * {@link Highcharts.Chart#removeAnnotation} instead. */ destroy: function () { var chart = this.chart, destroyItem = function (item) { item.destroy(); }; this.labels.forEach(destroyItem); this.shapes.forEach(destroyItem); this.clipXAxis = null; this.clipYAxis = null; erase(chart.labelCollectors, this.labelCollector); eventEmitterMixin.destroy.call(this); controllableMixin.destroy.call(this); destroyObjectProperties(this, chart); }, /** * See {@link Highcharts.Chart#removeAnnotation}. */ remove: function () { // Let chart.update() remove annoations on demand return this.chart.removeAnnotation(this); }, update: function (userOptions) { var chart = this.chart, labelsAndShapes = this.getLabelsAndShapesOptions( this.userOptions, userOptions ), userOptionsIndex = chart.annotations.indexOf(this), options = H.merge(true, this.userOptions, userOptions); options.labels = labelsAndShapes.labels; options.shapes = labelsAndShapes.shapes; this.destroy(); this.constructor(chart, options); // Update options in chart options, used in exporting (#9767): chart.options.annotations[userOptionsIndex] = options; this.isUpdating = true; this.redraw(); this.isUpdating = false; fireEvent(this, 'afterUpdate'); }, /* ************************************************************* * ITEM SECTION * Contains methods for handling a single item in an annotation **************************************************************** */ /** * Initialisation of a single shape * * @param {Object} shapeOptions - a confg object for a single shape */ initShape: function (shapeOptions, index) { var options = merge( this.options.shapeOptions, { controlPointOptions: this.options.controlPointOptions }, shapeOptions ), shape = new Annotation.shapesMap[options.type]( this, options, index ); shape.itemType = 'shape'; this.shapes.push(shape); return shape; }, /** * Initialisation of a single label * * @param {Object} labelOptions **/ initLabel: function (labelOptions, index) { var options = merge( this.options.labelOptions, { controlPointOptions: this.options.controlPointOptions }, labelOptions ), label = new ControllableLabel( this, options, index ); label.itemType = 'label'; this.labels.push(label); return label; }, /** * Redraw a single item. * * @param {Annotation.Label|Annotation.Shape} item * @param {boolean} [animation] */ redrawItem: function (item, animation) { item.linkPoints(); if (!item.shouldBeDrawn()) { this.destroyItem(item); } else { if (!item.graphic) { this.renderItem(item); } item.redraw( pick(animation, true) && item.graphic.placed ); if (item.points.length) { this.adjustVisibility(item); } } }, /** * Hide or show annotaiton attached to points. * * @param {Annotation.Label|Annotation.Shape} item */ adjustVisibility: function (item) { // #9481 var hasVisiblePoints = false, label = item.graphic; item.points.forEach(function (point) { if ( point.series.visible !== false && point.visible !== false ) { hasVisiblePoints = true; } }); if (!hasVisiblePoints) { label.hide(); } else if (label.visibility === 'hidden') { label.show(); } }, /** * Destroy a single item. * * @param {Annotation.Label|Annotation.Shape} item */ destroyItem: function (item) { // erase from shapes or labels array erase(this[item.itemType + 's'], item); item.destroy(); }, /** * @private */ renderItem: function (item) { item.render( item.itemType === 'label' ? this.labelsGroup : this.shapesGroup ); } } ); /** * An object uses for mapping between a shape type and a constructor. * To add a new shape type extend this object with type name as a key * and a constructor as its value. */ Annotation.shapesMap = { 'rect': ControllableRect, 'circle': ControllableCircle, 'path': ControllablePath, 'image': ControllableImage }; Annotation.types = {}; Annotation.MockPoint = MockPoint; Annotation.ControlPoint = ControlPoint; H.extendAnnotation = function ( Constructor, BaseConstructor, prototype, defaultOptions ) { BaseConstructor = BaseConstructor || Annotation; merge( true, Constructor.prototype, BaseConstructor.prototype, prototype ); Constructor.prototype.defaultOptions = merge( Constructor.prototype.defaultOptions, defaultOptions || {} ); }; /* ********************************************************************* * * EXTENDING CHART PROTOTYPE * ******************************************************************** */ extend(chartProto, /** @lends Highcharts.Chart# */ { initAnnotation: function (userOptions) { var Constructor = Annotation.types[userOptions.type] || Annotation, annotation = new Constructor(this, userOptions); this.annotations.push(annotation); return annotation; }, /** * Add an annotation to the chart after render time. * * @param {Highcharts.AnnotationsOptions} options * The annotation options for the new, detailed annotation. * @param {boolean} [redraw] * * @return {Highcharts.Annotation} - The newly generated annotation. */ addAnnotation: function (userOptions, redraw) { var annotation = this.initAnnotation(userOptions); this.options.annotations.push(annotation.options); if (pick(redraw, true)) { annotation.redraw(); } return annotation; }, /** * Remove an annotation from the chart. * * @param {String|Number|Annotation} idOrAnnotation - The annotation's id or * direct annotation object. */ removeAnnotation: function (idOrAnnotation) { var annotations = this.annotations, annotation = idOrAnnotation.coll === 'annotations' ? idOrAnnotation : find( annotations, function (annotation) { return annotation.options.id === idOrAnnotation; } ); if (annotation) { fireEvent(annotation, 'remove'); erase(this.options.annotations, annotation.options); erase(annotations, annotation); annotation.destroy(); } }, drawAnnotations: function () { this.plotBoxClip.attr(this.plotBox); this.annotations.forEach(function (annotation) { annotation.redraw(); }); } }); // Let chart.update() update annotations chartProto.collectionsWithUpdate.push('annotations'); // Let chart.update() create annoations on demand chartProto.collectionsWithInit.annotations = [chartProto.addAnnotation]; chartProto.callbacks.push(function (chart) { chart.annotations = []; if (!chart.options.annotations) { chart.options.annotations = []; } chart.plotBoxClip = this.renderer.clipRect(this.plotBox); chart.controlPointsGroup = chart.renderer .g('control-points') .attr({ zIndex: 99 }) .clip(chart.plotBoxClip) .add(); chart.options.annotations.forEach(function (annotationOptions, i) { var annotation = chart.initAnnotation(annotationOptions); chart.options.annotations[i] = annotation.options; }); chart.drawAnnotations(); addEvent(chart, 'redraw', chart.drawAnnotations); addEvent(chart, 'destroy', function () { chart.plotBoxClip.destroy(); chart.controlPointsGroup.destroy(); }); }); wrap( H.Pointer.prototype, 'onContainerMouseDown', function (proceed) { if (!this.chart.hasDraggedAnnotation) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } } );
cdnjs/cdnjs
ajax/libs/highcharts/8.0.0/es-modules/annotations/annotations.src.js
JavaScript
mit
42,338
#!/usr/bin/python3 """ Simple wrapper to get diff of two schedules It's able to show different attributes (by 'attrs' kwarg) and indicate missing phases Follows 'diff' exit codes: 0 - same 1 - different 2 - other trouble Test as "python -m schedules_tools.batches.diff" """ import argparse from datetime import datetime import json import logging from schedules_tools import jsondate, discovery from schedules_tools.converter import ScheduleConverter from schedules_tools.models import Task, Schedule import sys log = logging.getLogger(__name__) REPORT_NO_CHANGE = '' REPORT_ADDED = '_added_' REPORT_REMOVED = '_removed_' REPORT_CHANGED = '_changed_' REPORT_PREFIX_MAP = { REPORT_ADDED: '[+]', REPORT_REMOVED: '[-]', REPORT_CHANGED: '[M]', REPORT_NO_CHANGE: 3 * ' ', } NAME_SIM_THRESHOLD = 0.8 TASK_SCORE_THRESHOLD = 0.45 NAME_SIM_WEIGHT = 0.5 TASK_POS_WEIGHT = 0.5 def strings_similarity(str1, str2, winkler=True, scaling=0.1): """ Find the Jaro-Winkler distance of 2 strings. https://en.wikipedia.org/wiki/Jaro-Winkler_distance :param winkler: add winkler adjustment to the Jaro distance :param scaling: constant scaling factor for how much the score is adjusted upwards for having common prefixes. Should not exceed 0.25 """ if str1 == str2: return 1.0 def num_of_char_matches(s1, len1, s2, len2): count = 0 transpositions = 0 # number of matching chars w/ different sequence order limit = int(max(len1, len2) / 2 - 1) for i in range(len1): start = i - limit if start < 0: start = 0 end = i + limit + 1 if end > len2: end = len2 index = s2.find(s1[i], start, end) if index > -1: # found common char count += 1 if index != i: transpositions += 1 return count, transpositions len1 = len(str1) len2 = len(str2) num_of_matches, transpositions = num_of_char_matches(str1, len1, str2, len2) if num_of_matches == 0: return 0.0 m = float(num_of_matches) t = transpositions / 2.0 dj = (m / float(len1) + m / float(len2) + (m - t) / m) / 3.0 if winkler: length = 0 # length of common prefix at the start of the string (max = 4) max_length = min( len1, len2, 4 ) while length < max_length and str1[length] == str2[length]: length += 1 return dj + (length * scaling * (1.0 - dj)) return dj class ScheduleDiff(object): result = [] hierarchy_attr = 'tasks' subtree_hash_attr_name = 'subtree_hash' """ Default list of attributes used to compare 2 tasks. """ default_tasks_match_attrs = ['name', 'dStart', 'dFinish'] def __init__(self, schedule_a, schedule_b, trim_time=False, extra_compare_attributes=None): self.schedule_a = schedule_a self.schedule_b = schedule_b self.trim_time = trim_time self.attributes_to_compare = self.default_tasks_match_attrs if extra_compare_attributes: # avoid using += to not modify class-level list self.attributes_to_compare = self.attributes_to_compare + list(extra_compare_attributes) self.result = self._diff() def __str__(self): return self.result_to_str() def _get_subtree(self, item): return getattr(item, self.hierarchy_attr) def result_to_str(self, items=None, level=0): """ Textual representation of the diff. """ res = '' if items is None: items = self.result schedule = Schedule() for item in items: subtree = item['subtree'] state = item['item_state'] if state in [REPORT_CHANGED, REPORT_ADDED]: task = item['right'] elif state is REPORT_REMOVED: task = item['left'] else: task = item['both'] task_obj = Task.load_from_dict(task, schedule) res += '{} {}{}\n'.format(REPORT_PREFIX_MAP[state], level * ' ', str(task_obj)) if subtree: res += self.result_to_str(subtree, level + 2) return res def _create_report(self, item_state, left=None, right=None, both=None, subtree=[], changed_attrs=[]): """ Returns a dictionary representing a possible change. { left: Task or None, right: Task or None, both: used instead of left and right, when the task are equal, subtree: List of reports from the child Tasks, changed_attr: List of changed attributes, item_state: Type of change } """ if both: report = { 'both': both.dump_as_dict(recursive=False), 'subtree': subtree, 'changed_attrs': changed_attrs, 'item_state': item_state } else: # No need to keep the whole structure, # child tasks will be placed in report['tasks'] if left is not None: left = left.dump_as_dict(recursive=False) if right is not None: right = right.dump_as_dict(recursive=False) report = { 'left': left, 'right': right, 'subtree': subtree, 'changed_attrs': changed_attrs, 'item_state': item_state, } return report def _set_subtree_items_state(self, items, state): """ Set the given state recursively on the subtree items """ def create_report(item): kwargs = { 'subtree': self._set_subtree_items_state(self._get_subtree(item), state) } if state == REPORT_NO_CHANGE: kwargs['both'] = item elif state == REPORT_ADDED: kwargs['right'] = item elif state == REPORT_REMOVED: kwargs['left'] = item return self._create_report(state, **kwargs) return [create_report(item) for item in items] def get_changed_attrs(self, task_a, task_b): """ Compare 2 tasks Uses attributes defined in `self.attributes_to_compare` and subtree hash and returns a list of atts that don't match. """ changed_attributes = [attr for attr in self.attributes_to_compare if not self._compare_tasks_attributes(task_a, task_b, attr)] if task_a.get_subtree_hash(self.attributes_to_compare) \ != task_b.get_subtree_hash(self.attributes_to_compare): changed_attributes.append(self.subtree_hash_attr_name) return changed_attributes def _compare_tasks_attributes(self, task_a, task_b, attr_name): """ Compares tasks attributes. Trims time from datetime objects if self.trim_time is set. """ attribute_a = getattr(task_a, attr_name) attribute_b = getattr(task_b, attr_name) if self.trim_time: if isinstance(attribute_a, datetime): attribute_a = attribute_a.date() if isinstance(attribute_b, datetime): attribute_b = attribute_b.date() return attribute_a == attribute_b def find_best_match(self, t1, possible_matches, start_at_index=0): """ Finds the best match for the given task in the list of possible matches. Returns the index of the best match and a dict with a state suggestion and list of changed attrs. """ match_index = None best_match = { 'state': REPORT_REMOVED, 'changes': [], 'name_score': 0, 'score': TASK_SCORE_THRESHOLD } if start_at_index > 0: possible_matches = possible_matches[start_at_index:] for i, t2 in enumerate(possible_matches, start_at_index): res = self.eval_tasks(t1, t2, i, name_threshold=best_match['name_score']) if (res['state'] is REPORT_CHANGED and res['score'] > best_match['score']): match_index = i best_match = res if res['state'] is REPORT_NO_CHANGE: match_index = i best_match = res break return match_index, best_match def _task_position_score(self, index): return 1.0 / (2 * (index + 1)) def _task_score(self, name_score, position_score): weight_sum = NAME_SIM_WEIGHT + TASK_POS_WEIGHT name_score *= NAME_SIM_WEIGHT position_score *= TASK_POS_WEIGHT return (name_score + position_score) / weight_sum def eval_tasks(self, t1, t2, t2_index, name_threshold=NAME_SIM_THRESHOLD): name_score = 0.0 position_score = 0.0 changed_attrs = self.get_changed_attrs(t1, t2) # different names if 'name' in changed_attrs: t1_subtree = t1.get_subtree_hash(self.attributes_to_compare) t2_subtree = t2.get_subtree_hash(self.attributes_to_compare) if t1_subtree and t2_subtree: if t1_subtree == t2_subtree: state = REPORT_CHANGED position_score = 1.0 else: name_score = strings_similarity(t1.name, t2.name) if (name_score > name_threshold and len(changed_attrs) < len(self.attributes_to_compare)): state = REPORT_CHANGED position_score = self._task_position_score(t2_index) else: state = REPORT_REMOVED # no subtrees else: name_score = strings_similarity(t1.name, t2.name, winkler=False) if name_score > name_threshold: state = REPORT_CHANGED position_score = self._task_position_score(t2_index) else: state = REPORT_REMOVED # names are equal else: name_score = 1.0 if (not changed_attrs or (len(changed_attrs) == 1 and self.subtree_hash_attr_name in changed_attrs)): state = REPORT_NO_CHANGE else: state = REPORT_CHANGED position_score = 1.0 return { 'state': state, 'changes': changed_attrs, 'name_score': name_score, 'position_score': position_score, 'score': self._task_score(name_score, position_score) } def _diff(self, tasks_a=None, tasks_b=None): if tasks_a is None: tasks_a = self.schedule_a.tasks if tasks_b is None: tasks_b = self.schedule_b.tasks res = [] last_b_index = 0 # shortcut to create a report for an added task def report_task_added(index, recursive=True): task = tasks_b[index] subtree = self._get_subtree(task) if recursive: subtree = self._set_subtree_items_state(subtree, REPORT_ADDED) return self._create_report(REPORT_ADDED, right=task, subtree=subtree) for task in tasks_a: match_index, match = self.find_best_match(task, tasks_b, start_at_index=last_b_index) report = {} if match_index is None: subtree = self._set_subtree_items_state(self._get_subtree(task), REPORT_REMOVED) report = self._create_report(REPORT_REMOVED, left=task, subtree=subtree) else: # ALL elements between last_b_index and match_index => ADDED res.extend([report_task_added(k) for k in range(last_b_index, match_index)]) # exact match => NO CHANGE if not match['changes']: subtree = self._set_subtree_items_state(self._get_subtree(task), match['state']) report_kwargs = {'both': task, 'subtree': subtree} # structural change => CHANGED / NO CHANGE elif self.subtree_hash_attr_name in match['changes']: # process child tasks subtree = self._diff( self._get_subtree(task), self._get_subtree(tasks_b[match_index]) ) if len(match['changes']) > 1: report_kwargs = { 'left': task, 'right': tasks_b[match_index], 'subtree': subtree } else: report_kwargs = { 'both': task, 'subtree': subtree } # no structural changes => CHANGED else: subtree = self._set_subtree_items_state( self._get_subtree(tasks_b[match_index]), REPORT_NO_CHANGE) report_kwargs = { 'left': task, 'right': tasks_b[match_index], 'subtree': subtree } report = self._create_report(match['state'], changed_attrs=match['changes'], **report_kwargs) last_b_index = match_index + 1 res.append(report) # remaining tasks => ADDED res.extend([report_task_added(k) for k in range(last_b_index, len(tasks_b))]) return res def dump_json(self, **kwargs): def _encoder(obj): if isinstance(obj, Task): return obj.dump_as_dict() return jsondate._datetime_encoder(obj) kwargs['default'] = _encoder return json.dumps(self.result, **kwargs) def setup_logging(level): log_format = '%(name)-10s %(levelname)7s: %(message)s' sh = logging.StreamHandler(sys.stdout) sh.setLevel(level) formatter = logging.Formatter(log_format) sh.setFormatter(formatter) # setup root logger inst = logging.getLogger('') inst.setLevel(level) inst.addHandler(sh) def main(): setup_logging(logging.INFO) parser = argparse.ArgumentParser( description='Tool to show differences between two schedules.') parser.add_argument('--simple-diff', help='Simple comparison between two schedules.', action='store_true', default=False) parser.add_argument( '--handlers-path', help='Add python-dot-notation path to discover handlers (needs to ' 'be python module), can be called several times ' '(conflicting names will be overriden - the last ' 'implementation will be used)', action='append', default=[]) parser.add_argument('--whole-days', help='Compare just date part of timestamp (will ' 'ignore differences in time)', action='store_true', default=False) parser.add_argument('left') parser.add_argument('right') args = parser.parse_args() for path in args.handlers_path: discovery.search_paths.append(path) left = ScheduleConverter() left.import_schedule(args.left) right = ScheduleConverter() right.import_schedule(args.right) if args.simple_diff: diff_res = left.schedule.diff(right.schedule, whole_days=args.whole_days) else: diff_res = ScheduleDiff(left.schedule, right.schedule) if diff_res: print(diff_res) sys.exit(1) if __name__ == '__main__': main()
RedHat-Eng-PGM/schedules-tools
schedules_tools/diff.py
Python
mit
16,312
this.primereact = this.primereact || {}; this.primereact.multiselect = (function (exports, React, core, inputtext, virtualscroller, PrimeReact) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var PrimeReact__default = /*#__PURE__*/_interopDefaultLegacy(PrimeReact); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Checkbox = /*#__PURE__*/function (_Component) { _inherits(Checkbox, _Component); var _super = _createSuper$4(Checkbox); function Checkbox(props) { var _this; _classCallCheck(this, Checkbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(Checkbox, [{ key: "onClick", value: function onClick(e) { if (!this.props.disabled && !this.props.readOnly && this.props.onChange) { this.props.onChange({ originalEvent: e, value: this.props.value, checked: !this.props.checked, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { type: 'checkbox', name: this.props.name, id: this.props.id, value: this.props.value, checked: !this.props.checked } }); this.inputRef.current.checked = !this.props.checked; this.inputRef.current.focus(); e.preventDefault(); } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.inputRef.current.checked = this.props.checked; if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread$2({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter') { this.onClick(event); event.preventDefault(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.element, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var _this2 = this; var containerClass = core.classNames('p-checkbox p-component', { 'p-checkbox-checked': this.props.checked, 'p-checkbox-disabled': this.props.disabled, 'p-checkbox-focused': this.state.focused }, this.props.className); var boxClass = core.classNames('p-checkbox-box', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClass = core.classNames('p-checkbox-icon p-c', _defineProperty({}, this.props.icon, this.props.checked)); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: containerClass, style: this.props.style, onClick: this.onClick, onContextMenu: this.props.onContextMenu, onMouseDown: this.props.onMouseDown }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, type: "checkbox", "aria-labelledby": this.props.ariaLabelledBy, id: this.props.inputId, name: this.props.name, tabIndex: this.props.tabIndex, defaultChecked: this.props.checked, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur, disabled: this.props.disabled, readOnly: this.props.readOnly, required: this.props.required })), /*#__PURE__*/React__default['default'].createElement("div", { className: boxClass, ref: function ref(el) { return _this2.box = el; }, role: "checkbox", "aria-checked": this.props.checked }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClass }))); } }]); return Checkbox; }(React.Component); _defineProperty(Checkbox, "defaultProps", { id: null, inputRef: null, inputId: null, value: null, name: null, checked: false, style: null, className: null, disabled: false, required: false, readOnly: false, tabIndex: null, icon: 'pi pi-check', tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onMouseDown: null, onContextMenu: null }); function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectHeader = /*#__PURE__*/function (_Component) { _inherits(MultiSelectHeader, _Component); var _super = _createSuper$3(MultiSelectHeader); function MultiSelectHeader(props) { var _this; _classCallCheck(this, MultiSelectHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, query: event.target.value }); } } }, { key: "onSelectAll", value: function onSelectAll(event) { if (this.props.onSelectAll) { this.props.onSelectAll({ originalEvent: event, checked: this.props.selectAll }); } } }, { key: "renderFilterElement", value: function renderFilterElement() { if (this.props.filter) { return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-filter-container" }, /*#__PURE__*/React__default['default'].createElement(inputtext.InputText, { type: "text", role: "textbox", value: this.props.filterValue, onChange: this.onFilter, className: "p-multiselect-filter", placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-filter-icon pi pi-search" })); } return null; } }, { key: "render", value: function render() { var filterElement = this.renderFilterElement(); var checkboxElement = this.props.showSelectAll && /*#__PURE__*/React__default['default'].createElement(Checkbox, { checked: this.props.selectAll, onChange: this.onSelectAll, role: "checkbox", "aria-checked": this.props.selectAll }); var closeElement = /*#__PURE__*/React__default['default'].createElement("button", { type: "button", className: "p-multiselect-close p-link", onClick: this.props.onClose }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-close-icon pi pi-times" }), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); var element = /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-header" }, checkboxElement, filterElement, closeElement); if (this.props.template) { var defaultOptions = { className: 'p-multiselect-header', checkboxElement: checkboxElement, checked: this.props.selectAll, onChange: this.onSelectAll, filterElement: filterElement, closeElement: closeElement, closeElementClassName: 'p-multiselect-close p-link', closeIconClassName: 'p-multiselect-close-icon pi pi-times', onCloseClick: this.props.onClose, element: element, props: this.props }; return core.ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return MultiSelectHeader; }(React.Component); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectItem = /*#__PURE__*/function (_Component) { _inherits(MultiSelectItem, _Component); var _super = _createSuper$2(MultiSelectItem); function MultiSelectItem(props) { var _this; _classCallCheck(this, MultiSelectItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.onKeyDown) { this.props.onKeyDown({ originalEvent: event, option: this.props.option }); } } }, { key: "render", value: function render() { var className = core.classNames('p-multiselect-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var checkboxClassName = core.classNames('p-checkbox-box', { 'p-highlight': this.props.selected }); var checkboxIcon = core.classNames('p-checkbox-icon p-c', { 'pi pi-check': this.props.selected }); var content = this.props.template ? core.ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; var tabIndex = this.props.disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement("li", { className: className, onClick: this.onClick, tabIndex: tabIndex, onKeyDown: this.onKeyDown, role: "option", "aria-selected": this.props.selected }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-checkbox p-component" }, /*#__PURE__*/React__default['default'].createElement("div", { className: checkboxClassName }, /*#__PURE__*/React__default['default'].createElement("span", { className: checkboxIcon }))), /*#__PURE__*/React__default['default'].createElement("span", null, content), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); } }]); return MultiSelectItem; }(React.Component); _defineProperty(MultiSelectItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, template: null, onClick: null, onKeyDown: null }); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectPanelComponent = /*#__PURE__*/function (_Component) { _inherits(MultiSelectPanelComponent, _Component); var _super = _createSuper$1(MultiSelectPanelComponent); function MultiSelectPanelComponent(props) { var _this; _classCallCheck(this, MultiSelectPanelComponent); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectPanelComponent, [{ key: "onEnter", value: function onEnter() { var _this2 = this; this.props.onEnter(function () { if (_this2.virtualScrollerRef) { var selectedIndex = _this2.props.getSelectedOptionIndex(); if (selectedIndex !== -1) { _this2.virtualScrollerRef.scrollToIndex(selectedIndex); } } }); } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { if (this.virtualScrollerRef) { this.virtualScrollerRef.scrollToIndex(0); } this.props.onFilterInputChange && this.props.onFilterInputChange(event); } }, { key: "isEmptyFilter", value: function isEmptyFilter() { return !(this.props.visibleOptions && this.props.visibleOptions.length) && this.props.hasFilter(); } }, { key: "renderHeader", value: function renderHeader() { return /*#__PURE__*/React__default['default'].createElement(MultiSelectHeader, { filter: this.props.filter, filterValue: this.props.filterValue, onFilter: this.onFilterInputChange, filterPlaceholder: this.props.filterPlaceholder, onClose: this.props.onCloseClick, showSelectAll: this.props.showSelectAll, selectAll: this.props.isAllSelected(), onSelectAll: this.props.onSelectAll, template: this.props.panelHeaderTemplate }); } }, { key: "renderFooter", value: function renderFooter() { if (this.props.panelFooterTemplate) { var content = core.ObjectUtils.getJSXElement(this.props.panelFooterTemplate, this.props, this.props.onOverlayHide); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-footer" }, content); } return null; } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.props.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.props.getOptionLabel(option); var optionKey = j + '_' + _this3.props.getOptionRenderKey(option); var disabled = _this3.props.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.props.isSelected(option), onClick: _this3.props.onOptionSelect, onKeyDown: _this3.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderEmptyFilter", value: function renderEmptyFilter() { var emptyFilterMessage = core.ObjectUtils.getJSXElement(this.props.emptyFilterMessage, this.props); return /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-empty-message" }, emptyFilterMessage); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? core.ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.props.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.props.getOptionGroupRenderKey(option); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: key }, /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.props.getOptionLabel(option); var optionKey = index + '_' + this.props.getOptionRenderKey(option); var disabled = this.props.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.props.isSelected(option), onClick: this.props.onOptionSelect, onKeyDown: this.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems() { var _this4 = this; if (this.props.visibleOptions && this.props.visibleOptions.length) { return this.props.visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } else if (this.props.hasFilter()) { return this.renderEmptyFilter(); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions), { style: _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions.style), { height: this.props.scrollHeight }), className: core.classNames('p-multiselect-items-wrapper', this.props.virtualScrollerOptions.className), items: this.props.visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread$1(_objectSpread$1({}, event), { filter: _this5.props.filterValue })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = core.classNames('p-multiselect-items p-component', options.className); var content = _this5.isEmptyFilter() ? _this5.renderEmptyFilter() : options.children; return /*#__PURE__*/React__default['default'].createElement("ul", { ref: options.ref, className: className, role: "listbox", "aria-multiselectable": true }, content); } }); return /*#__PURE__*/React__default['default'].createElement(virtualscroller.VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-items-wrapper", style: { maxHeight: this.props.scrollHeight } }, /*#__PURE__*/React__default['default'].createElement("ul", { className: "p-multiselect-items p-component", role: "listbox", "aria-multiselectable": true }, items)); } } }, { key: "renderElement", value: function renderElement() { var panelClassName = core.classNames('p-multiselect-panel p-component', { 'p-multiselect-limited': !this.props.allowOptionSelect() }, this.props.panelClassName); var header = this.renderHeader(); var content = this.renderContent(); var footer = this.renderFooter(); return /*#__PURE__*/React__default['default'].createElement(core.CSSTransition, { nodeRef: this.props.forwardRef, classNames: "p-connected-overlay", in: this.props.in, timeout: { enter: 120, exit: 100 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.props.onEntered, onExit: this.props.onExit, onExited: this.props.onExited }, /*#__PURE__*/React__default['default'].createElement("div", { ref: this.props.forwardRef, className: panelClassName, style: this.props.panelStyle, onClick: this.props.onClick }, header, content, footer)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React__default['default'].createElement(core.Portal, { element: element, appendTo: this.props.appendTo }); } }]); return MultiSelectPanelComponent; }(React.Component); var MultiSelectPanel = /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) { return /*#__PURE__*/React__default['default'].createElement(MultiSelectPanelComponent, _extends({ forwardRef: ref }, props)); }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelect = /*#__PURE__*/function (_Component) { _inherits(MultiSelect, _Component); var _super = _createSuper(MultiSelect); function MultiSelect(props) { var _this; _classCallCheck(this, MultiSelect); _this = _super.call(this, props); _this.state = { filter: '', focused: false, overlayVisible: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); _this.onCloseClick = _this.onCloseClick.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); _this.onOverlayEnter = _this.onOverlayEnter.bind(_assertThisInitialized(_this)); _this.onOverlayEntered = _this.onOverlayEntered.bind(_assertThisInitialized(_this)); _this.onOverlayExit = _this.onOverlayExit.bind(_assertThisInitialized(_this)); _this.onOverlayExited = _this.onOverlayExited.bind(_assertThisInitialized(_this)); _this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this)); _this.getOptionLabel = _this.getOptionLabel.bind(_assertThisInitialized(_this)); _this.getOptionRenderKey = _this.getOptionRenderKey.bind(_assertThisInitialized(_this)); _this.isOptionDisabled = _this.isOptionDisabled.bind(_assertThisInitialized(_this)); _this.getOptionGroupChildren = _this.getOptionGroupChildren.bind(_assertThisInitialized(_this)); _this.getOptionGroupLabel = _this.getOptionGroupLabel.bind(_assertThisInitialized(_this)); _this.getOptionGroupRenderKey = _this.getOptionGroupRenderKey.bind(_assertThisInitialized(_this)); _this.allowOptionSelect = _this.allowOptionSelect.bind(_assertThisInitialized(_this)); _this.isSelected = _this.isSelected.bind(_assertThisInitialized(_this)); _this.isAllSelected = _this.isAllSelected.bind(_assertThisInitialized(_this)); _this.hasFilter = _this.hasFilter.bind(_assertThisInitialized(_this)); _this.getSelectedOptionIndex = _this.getSelectedOptionIndex.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.overlayRef = /*#__PURE__*/React.createRef(); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(MultiSelect, [{ key: "onPanelClick", value: function onPanelClick(event) { core.OverlayService.emit('overlay-click', { originalEvent: event, target: this.container }); } }, { key: "allowOptionSelect", value: function allowOptionSelect() { return !this.props.selectionLimit || !this.props.value || this.props.value && this.props.value.length < this.props.selectionLimit; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var _this2 = this; var originalEvent = event.originalEvent, option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var selected = this.isSelected(option); var allowOptionSelect = this.allowOptionSelect(); if (selected) this.updateModel(originalEvent, this.props.value.filter(function (val) { return !core.ObjectUtils.equals(isOptionValueUsed ? val : _this2.getOptionValue(val), optionValue, _this2.equalityKey()); }));else if (allowOptionSelect) this.updateModel(originalEvent, [].concat(_toConsumableArray(this.props.value || []), [optionValue])); } }, { key: "onOptionKeyDown", value: function onOptionKeyDown(event) { var originalEvent = event.originalEvent; var listItem = originalEvent.currentTarget; switch (originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } originalEvent.preventDefault(); break; //enter and space case 13: case 32: this.onOptionSelect(event); originalEvent.preventDefault(); break; //escape case 27: this.hide(); this.inputRef.current.focus(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return core.DomHandler.hasClass(nextItem, 'p-disabled') || core.DomHandler.hasClass(nextItem, 'p-multiselect-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return core.DomHandler.hasClass(prevItem, 'p-disabled') || core.DomHandler.hasClass(prevItem, 'p-multiselect-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onClick", value: function onClick(event) { if (!this.props.disabled && !this.isPanelClicked(event) && !core.DomHandler.hasClass(event.target, 'p-multiselect-token-icon') && !this.isClearClicked(event)) { if (this.state.overlayVisible) { this.hide(); } else { this.show(); } this.inputRef.current.focus(); } } }, { key: "onKeyDown", value: function onKeyDown(event) { switch (event.which) { //down case 40: if (!this.state.overlayVisible && event.altKey) { this.show(); event.preventDefault(); } break; //space case 32: if (this.state.overlayVisible) this.hide();else this.show(); event.preventDefault(); break; //escape case 27: this.hide(); break; //tab case 9: if (this.state.overlayVisible) { var firstFocusableElement = core.DomHandler.getFirstFocusableElement(this.overlayRef.current); if (firstFocusableElement) { firstFocusableElement.focus(); event.preventDefault(); } } break; } } }, { key: "onSelectAll", value: function onSelectAll(event) { var _this3 = this; if (this.props.onSelectAll) { this.props.onSelectAll(event); } else { var value = null; var visibleOptions = this.getVisibleOptions(); if (event.checked) { value = []; if (visibleOptions) { var selectedOptions = visibleOptions.filter(function (option) { return _this3.isOptionDisabled(option) && _this3.isSelected(option); }); value = selectedOptions.map(function (option) { return _this3.getOptionValue(option); }); } } else if (visibleOptions) { visibleOptions = visibleOptions.filter(function (option) { return !_this3.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { value = []; visibleOptions.forEach(function (optionGroup) { return value = [].concat(_toConsumableArray(value), _toConsumableArray(_this3.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this3.isOptionDisabled(option); }).map(function (option) { return _this3.getOptionValue(option); }))); }); } else { value = visibleOptions.map(function (option) { return _this3.getOptionValue(option); }); } value = _toConsumableArray(new Set([].concat(_toConsumableArray(value), _toConsumableArray(this.props.value || [])))); } this.updateModel(event.originalEvent, value); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { var _this4 = this; var filter = event.query; this.setState({ filter: filter }, function () { if (_this4.props.onFilter) { _this4.props.onFilter({ originalEvent: event, filter: filter }); } }); } }, { key: "resetFilter", value: function resetFilter() { var _this5 = this; var filter = ''; this.setState({ filter: filter }, function () { _this5.props.onFilter && _this5.props.onFilter({ filter: filter }); }); } }, { key: "show", value: function show() { this.setState({ overlayVisible: true }); } }, { key: "hide", value: function hide() { this.setState({ overlayVisible: false }); } }, { key: "onOverlayEnter", value: function onOverlayEnter(callback) { core.ZIndexUtils.set('overlay', this.overlayRef.current); this.alignOverlay(); this.scrollInView(); callback && callback(); } }, { key: "onOverlayEntered", value: function onOverlayEntered(callback) { this.bindDocumentClickListener(); this.bindScrollListener(); this.bindResizeListener(); callback && callback(); this.props.onShow && this.props.onShow(); } }, { key: "onOverlayExit", value: function onOverlayExit() { this.unbindDocumentClickListener(); this.unbindScrollListener(); this.unbindResizeListener(); } }, { key: "onOverlayExited", value: function onOverlayExited() { if (this.props.filter && this.props.resetFilterOnHide) { this.resetFilter(); } core.ZIndexUtils.clear(this.overlayRef.current); this.props.onHide && this.props.onHide(); } }, { key: "alignOverlay", value: function alignOverlay() { core.DomHandler.alignOverlay(this.overlayRef.current, this.label.parentElement, this.props.appendTo || PrimeReact__default['default'].appendTo); } }, { key: "scrollInView", value: function scrollInView() { var highlightItem = core.DomHandler.findSingle(this.overlayRef.current, 'li.p-highlight'); if (highlightItem) { highlightItem.scrollIntoView({ block: 'nearest', inline: 'start' }); } } }, { key: "onCloseClick", value: function onCloseClick(event) { this.hide(); this.inputRef.current.focus(); event.preventDefault(); event.stopPropagation(); } }, { key: "getSelectedOptionIndex", value: function getSelectedOptionIndex() { if (this.props.value != null && this.props.options) { if (this.props.optionGroupLabel) { for (var i = 0; i < this.props.options.length; i++) { var selectedOptionIndex = this.findOptionIndexInList(this.props.value, this.getOptionGroupChildren(this.props.options[i])); if (selectedOptionIndex !== -1) { return { group: i, option: selectedOptionIndex }; } } } else { return this.findOptionIndexInList(this.props.value, this.props.options); } } return -1; } }, { key: "findOptionIndexInList", value: function findOptionIndexInList(value, list) { var _this6 = this; var key = this.equalityKey(); return list.findIndex(function (item) { return value.some(function (val) { return core.ObjectUtils.equals(val, _this6.getOptionValue(item), key); }); }); } }, { key: "isSelected", value: function isSelected(option) { var _this7 = this; var selected = false; if (this.props.value) { var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var key = this.equalityKey(); selected = this.props.value.some(function (val) { return core.ObjectUtils.equals(isOptionValueUsed ? val : _this7.getOptionValue(val), optionValue, key); }); } return selected; } }, { key: "getLabelByValue", value: function getLabelByValue(val) { var option; if (this.props.options) { if (this.props.optionGroupLabel) { var _iterator = _createForOfIteratorHelper(this.props.options), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var optionGroup = _step.value; option = this.findOptionByValue(val, this.getOptionGroupChildren(optionGroup)); if (option) { break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { option = this.findOptionByValue(val, this.props.options); } } return option ? this.getOptionLabel(option) : null; } }, { key: "findOptionByValue", value: function findOptionByValue(val, list) { var key = this.equalityKey(); var _iterator2 = _createForOfIteratorHelper(list), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var option = _step2.value; var optionValue = this.getOptionValue(option); if (core.ObjectUtils.equals(optionValue, val, key)) { return option; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return null; } }, { key: "onFocus", value: function onFocus(event) { var _this8 = this; event.persist(); this.setState({ focused: true }, function () { if (_this8.props.onFocus) { _this8.props.onFocus(event); } }); } }, { key: "onBlur", value: function onBlur(event) { var _this9 = this; event.persist(); this.setState({ focused: false }, function () { if (_this9.props.onBlur) { _this9.props.onBlur(event); } }); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this10 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this10.state.overlayVisible && _this10.isOutsideClicked(event)) { _this10.hide(); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this11 = this; if (!this.scrollHandler) { this.scrollHandler = new core.ConnectedOverlayScrollHandler(this.container, function () { if (_this11.state.overlayVisible) { _this11.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this12 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this12.state.overlayVisible && !core.DomHandler.isAndroid()) { _this12.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "isOutsideClicked", value: function isOutsideClicked(event) { return this.container && !(this.container.isSameNode(event.target) || this.isClearClicked(event) || this.container.contains(event.target) || this.isPanelClicked(event)); } }, { key: "isClearClicked", value: function isClearClicked(event) { return core.DomHandler.hasClass(event.target, 'p-multiselect-clear-icon'); } }, { key: "isPanelClicked", value: function isPanelClicked(event) { return this.overlayRef && this.overlayRef.current && this.overlayRef.current.contains(event.target); } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } if (this.state.overlayVisible && this.hasFilter()) { this.alignOverlay(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentClickListener(); this.unbindResizeListener(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } core.ZIndexUtils.clear(this.overlayRef.current); } }, { key: "hasFilter", value: function hasFilter() { return this.state.filter && this.state.filter.trim().length > 0; } }, { key: "isAllSelected", value: function isAllSelected() { var _this13 = this; if (this.props.onSelectAll) { return this.props.selectAll; } else { var visibleOptions = this.getVisibleOptions(); if (visibleOptions.length === 0) { return false; } visibleOptions = visibleOptions.filter(function (option) { return !_this13.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { var _iterator3 = _createForOfIteratorHelper(visibleOptions), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var optionGroup = _step3.value; var visibleOptionsGroupChildren = this.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this13.isOptionDisabled(option); }); var _iterator4 = _createForOfIteratorHelper(visibleOptionsGroupChildren), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var option = _step4.value; if (!this.isSelected(option)) { return false; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } else { var _iterator5 = _createForOfIteratorHelper(visibleOptions), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _option = _step5.value; if (!this.isSelected(_option)) { return false; } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } } return true; } }, { key: "getOptionLabel", value: function getOptionLabel(option) { return this.props.optionLabel ? core.ObjectUtils.resolveFieldData(option, this.props.optionLabel) : option && option['label'] !== undefined ? option['label'] : option; } }, { key: "getOptionValue", value: function getOptionValue(option) { if (this.props.optionValue) { var data = core.ObjectUtils.resolveFieldData(option, this.props.optionValue); return data !== null ? data : option; } return option && option['value'] !== undefined ? option['value'] : option; } }, { key: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? core.ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(option); } }, { key: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "isOptionDisabled", value: function isOptionDisabled(option) { if (this.props.optionDisabled) { return core.ObjectUtils.isFunction(this.props.optionDisabled) ? this.props.optionDisabled(option) : core.ObjectUtils.resolveFieldData(option, this.props.optionDisabled); } return option && option['disabled'] !== undefined ? option['disabled'] : false; } }, { key: "isOptionValueUsed", value: function isOptionValueUsed(option) { return this.props.optionValue || option && option['value'] !== undefined; } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.state.filter.trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator6 = _createForOfIteratorHelper(this.props.options), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var optgroup = _step6.value; var filteredSubOptions = core.FilterUtils.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return filteredGroups; } else { return core.FilterUtils.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "isEmpty", value: function isEmpty() { return !this.props.value || this.props.value.length === 0; } }, { key: "equalityKey", value: function equalityKey() { return this.props.optionValue ? null : this.props.dataKey; } }, { key: "checkValidity", value: function checkValidity() { return this.inputRef.current.checkValidity(); } }, { key: "removeChip", value: function removeChip(event, item) { var key = this.equalityKey(); var value = this.props.value.filter(function (val) { return !core.ObjectUtils.equals(val, item, key); }); this.updateModel(event, value); } }, { key: "getSelectedItemsLabel", value: function getSelectedItemsLabel() { var pattern = /{(.*?)}/; if (pattern.test(this.props.selectedItemsLabel)) { return this.props.selectedItemsLabel.replace(this.props.selectedItemsLabel.match(pattern)[0], this.props.value.length + ''); } return this.props.selectedItemsLabel; } }, { key: "getLabel", value: function getLabel() { var label; if (!this.isEmpty() && !this.props.fixedPlaceholder) { if (this.props.value.length <= this.props.maxSelectedLabels) { label = ''; for (var i = 0; i < this.props.value.length; i++) { if (i !== 0) { label += ','; } label += this.getLabelByValue(this.props.value[i]); } return label; } else { return this.getSelectedItemsLabel(); } } return label; } }, { key: "getLabelContent", value: function getLabelContent() { var _this14 = this; if (this.props.selectedItemTemplate) { if (!this.isEmpty()) { if (this.props.value.length <= this.props.maxSelectedLabels) { return this.props.value.map(function (val, index) { var item = core.ObjectUtils.getJSXElement(_this14.props.selectedItemTemplate, val); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: index }, item); }); } else { return this.getSelectedItemsLabel(); } } else { return core.ObjectUtils.getJSXElement(this.props.selectedItemTemplate); } } else { if (this.props.display === 'chip' && !this.isEmpty()) { return this.props.value.map(function (val) { var label = _this14.getLabelByValue(val); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-token", key: label }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-label" }, label), !_this14.props.disabled && /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-icon pi pi-times-circle", onClick: function onClick(e) { return _this14.removeChip(e, val); } })); }); } return this.getLabel(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.container, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "renderClearIcon", value: function renderClearIcon() { var _this15 = this; var empty = this.isEmpty(); if (!empty && this.props.showClear && !this.props.disabled) { return /*#__PURE__*/React__default['default'].createElement("i", { className: "p-multiselect-clear-icon pi pi-times", onClick: function onClick(e) { return _this15.updateModel(e, null); } }); } return null; } }, { key: "renderLabel", value: function renderLabel() { var _this16 = this; var empty = this.isEmpty(); var content = this.getLabelContent(); var labelClassName = core.classNames('p-multiselect-label', { 'p-placeholder': empty && this.props.placeholder, 'p-multiselect-label-empty': empty && !this.props.placeholder && !this.props.selectedItemTemplate, 'p-multiselect-items-label': !empty && this.props.value.length > this.props.maxSelectedLabels }); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this16.label = el; }, className: "p-multiselect-label-container" }, /*#__PURE__*/React__default['default'].createElement("div", { className: labelClassName }, content || this.props.placeholder || 'empty')); } }, { key: "render", value: function render() { var _this17 = this; var className = core.classNames('p-multiselect p-component p-inputwrapper', { 'p-multiselect-chip': this.props.display === 'chip', 'p-disabled': this.props.disabled, 'p-multiselect-clearable': this.props.showClear && !this.props.disabled, 'p-focus': this.state.focused, 'p-inputwrapper-filled': this.props.value && this.props.value.length > 0, 'p-inputwrapper-focus': this.state.focused || this.state.overlayVisible }, this.props.className); var iconClassName = core.classNames('p-multiselect-trigger-icon p-c', this.props.dropdownIcon); var visibleOptions = this.getVisibleOptions(); var label = this.renderLabel(); var clearIcon = this.renderClearIcon(); return /*#__PURE__*/React__default['default'].createElement("div", { id: this.props.id, className: className, onClick: this.onClick, ref: function ref(el) { return _this17.container = el; }, style: this.props.style }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, id: this.props.inputId, name: this.props.name, readOnly: true, type: "text", onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown, role: "listbox", "aria-haspopup": "listbox", "aria-labelledby": this.props.ariaLabelledBy, "aria-expanded": this.state.overlayVisible, disabled: this.props.disabled, tabIndex: this.props.tabIndex })), label, clearIcon, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-trigger" }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClassName })), /*#__PURE__*/React__default['default'].createElement(MultiSelectPanel, _extends({ ref: this.overlayRef, visibleOptions: visibleOptions }, this.props, { onClick: this.onPanelClick, onOverlayHide: this.hide, filterValue: this.state.filter, hasFilter: this.hasFilter, onFilterInputChange: this.onFilterInputChange, onCloseClick: this.onCloseClick, onSelectAll: this.onSelectAll, getOptionLabel: this.getOptionLabel, getOptionRenderKey: this.getOptionRenderKey, isOptionDisabled: this.isOptionDisabled, getOptionGroupChildren: this.getOptionGroupChildren, getOptionGroupLabel: this.getOptionGroupLabel, getOptionGroupRenderKey: this.getOptionGroupRenderKey, isSelected: this.isSelected, getSelectedOptionIndex: this.getSelectedOptionIndex, isAllSelected: this.isAllSelected, onOptionSelect: this.onOptionSelect, allowOptionSelect: this.allowOptionSelect, onOptionKeyDown: this.onOptionKeyDown, in: this.state.overlayVisible, onEnter: this.onOverlayEnter, onEntered: this.onOverlayEntered, onExit: this.onOverlayExit, onExited: this.onOverlayExited }))); } }]); return MultiSelect; }(React.Component); _defineProperty(MultiSelect, "defaultProps", { id: null, inputRef: null, name: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, display: 'comma', style: null, className: null, panelClassName: null, panelStyle: null, virtualScrollerOptions: null, scrollHeight: '200px', placeholder: null, fixedPlaceholder: false, disabled: false, showClear: false, filter: false, filterBy: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, emptyFilterMessage: 'No results found', resetFilterOnHide: false, tabIndex: 0, dataKey: null, inputId: null, appendTo: null, tooltip: null, tooltipOptions: null, maxSelectedLabels: 3, selectionLimit: null, selectedItemsLabel: '{0} items selected', ariaLabelledBy: null, itemTemplate: null, selectedItemTemplate: null, panelHeaderTemplate: null, panelFooterTemplate: null, transitionOptions: null, dropdownIcon: 'pi pi-chevron-down', showSelectAll: true, selectAll: false, onChange: null, onFocus: null, onBlur: null, onShow: null, onHide: null, onFilter: null, onSelectAll: null }); exports.MultiSelect = MultiSelect; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, primereact.core, primereact.inputtext, primereact.virtualscroller, primereact.api));
cdnjs/cdnjs
ajax/libs/primereact/6.5.1/multiselect/multiselect.js
JavaScript
mit
72,104
/* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var isArray = U.isArray; import reduceArrayMixin from '../mixins/reduce-array.js'; import multipleLinesMixin from '../mixins/multipe-lines.js'; var merge = H.merge, SMA = H.seriesTypes.sma, getArrayExtremes = reduceArrayMixin.getArrayExtremes; /** * The Stochastic series type. * * @private * @class * @name Highcharts.seriesTypes.stochastic * * @augments Highcharts.Series */ H.seriesType('stochastic', 'sma', /** * Stochastic oscillator. This series requires the `linkedTo` option to be * set and should be loaded after the `stock/indicators/indicators.js` file. * * @sample stock/indicators/stochastic * Stochastic oscillator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, joinBy, keys, navigatorOptions, * pointInterval, pointIntervalUnit, pointPlacement, * pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @optionparent plotOptions.stochastic */ { /** * @excluding index, period */ params: { /** * Periods for Stochastic oscillator: [%K, %D]. * * @type {Array<number,number>} * @default [14, 3] */ periods: [14, 3] }, marker: { enabled: false }, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>%K: {point.y}<br/>%D: {point.smoothed}<br/>' }, /** * Smoothed line options. */ smoothedLine: { /** * Styles for a smoothed line. */ styles: { /** * Pixel width of the line. */ lineWidth: 1, /** * Color of the line. If not set, it's inherited from * [plotOptions.stochastic.color * ](#plotOptions.stochastic.color). * * @type {Highcharts.ColorString} */ lineColor: undefined } }, dataGrouping: { approximation: 'averages' } }, /** * @lends Highcharts.Series# */ H.merge(multipleLinesMixin, { nameComponents: ['periods'], nameBase: 'Stochastic', pointArrayMap: ['y', 'smoothed'], parallelArrays: ['x', 'y', 'smoothed'], pointValKey: 'y', linesApiNames: ['smoothedLine'], init: function () { SMA.prototype.init.apply(this, arguments); // Set default color for lines: this.options = merge({ smoothedLine: { styles: { lineColor: this.color } } }, this.options); }, getValues: function (series, params) { var periodK = params.periods[0], periodD = params.periods[1], xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, // 0- date, 1-%K, 2-%D SO = [], xData = [], yData = [], slicedY, close = 3, low = 2, high = 1, CL, HL, LL, K, D = null, points, extremes, i; // Stochastic requires close value if (yValLen < periodK || !isArray(yVal[0]) || yVal[0].length !== 4) { return false; } // For a N-period, we start from N-1 point, to calculate Nth point // That is why we later need to comprehend slice() elements list // with (+1) for (i = periodK - 1; i < yValLen; i++) { slicedY = yVal.slice(i - periodK + 1, i + 1); // Calculate %K extremes = getArrayExtremes(slicedY, low, high); LL = extremes[0]; // Lowest low in %K periods CL = yVal[i][close] - LL; HL = extremes[1] - LL; K = CL / HL * 100; xData.push(xVal[i]); yData.push([K, null]); // Calculate smoothed %D, which is SMA of %K if (i >= (periodK - 1) + (periodD - 1)) { points = SMA.prototype.getValues.call(this, { xData: xData.slice(-periodD), yData: yData.slice(-periodD) }, { period: periodD }); D = points.yData[0]; } SO.push([xVal[i], K, D]); yData[yData.length - 1][1] = D; } return { values: SO, xData: xData, yData: yData }; } })); /** * A Stochastic indicator. If the [type](#series.stochastic.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.stochastic * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, dataParser, dataURL, joinBy, keys, * navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @apioption series.stochastic */ ''; // to include the above in the js output
cdnjs/cdnjs
ajax/libs/highcharts/7.2.2/es-modules/indicators/stochastic.src.js
JavaScript
mit
5,303
from __future__ import print_function class Sequence(object): def __init__(self, name, seq): """ :param seq: the sequence :type seq: string """ self.name = name self.sequence = seq def __len__(self): return len(self.sequence) def to_fasta(self): id_ = self.name.replace(' ', '_') fasta = '>{}\n'.format(id_) start = 0 while start < len(self.sequence): end = start + 80 fasta += self.sequence[start: end + 1] + '\n' start = end return fasta class DNASequence(Sequence): alphabet = 'ATGC' def gc_percent(self): return float(self.sequence.count('G') + self.sequence.count('C')) / len(self.sequence) class AASequence(Sequence): _water = 18.0153 _weight_table = {'A': 89.0932, 'C': 121.1582, 'E': 147.1293, 'D': 133.1027, 'G': 75.0666, 'F': 165.1891, 'I': 131.1729, 'H': 155.1546, 'K': 146.1876, 'M': 149.2113, 'L': 131.1729, 'O': 255.3134, 'N': 132.1179, 'Q': 146.1445, 'P': 115.1305, 'S': 105.0926, 'R': 174.201, 'U': 168.0532, 'T': 119.1192, 'W': 204.2252, 'V': 117.1463, 'Y': 181.1885} def molecular_weight(self): return sum([self._weight_table[aa] for aa in self.sequence]) - (len(self.sequence) - 1) * self._water
C3BI-pasteur-fr/python-course-1
source/_static/code/inheritance_sequence.py
Python
cc0-1.0
1,463
/** * Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.transform.internal; /** * @author Thomas.Eichstaedt-Engelen */ public abstract class AbstractTransformationServiceTest { protected String source = "<?xml version=\"1.0\"?><xml_api_reply version=\"1\"><weather module_id=\"0\"" + " tab_id=\"0\" mobile_row=\"0\" mobile_zipped=\"1\" row=\"0\" section=\"0\" ><forecast_information>" + "<city data=\"Krefeld, North Rhine-Westphalia\"/><postal_code data=\"Krefeld Germany\"/>" + "<latitude_e6 data=\"\"/><longitude_e6 data=\"\"/><forecast_date data=\"2011-03-01\"/>" + "<current_date_time data=\"2011-03-01 15:20:00 +0000\"/><unit_system data=\"SI\"/></forecast_information>" + "<current_conditions><condition data=\"Meistens bew�lkt\"/><temp_f data=\"46\"/><temp_c data=\"8\"/>" + "<humidity data=\"Feuchtigkeit: 66 %\"/><icon data=\"/ig/images/weather/mostly_cloudy.gif\"/>" + "<wind_condition data=\"Wind: N mit 26 km/h\"/></current_conditions><forecast_conditions><day_of_week data=\"Di.\"/>" + "<low data=\"-1\"/><high data=\"6\"/><icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/>" + "</forecast_conditions><forecast_conditions><day_of_week data=\"Mi.\"/><low data=\"-1\"/><high data=\"8\"/>" + "<icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/></forecast_conditions><forecast_conditions>" + "<day_of_week data=\"Do.\"/><low data=\"-1\"/><high data=\"8\"/><icon data=\"/ig/images/weather/sunny.gif\"/>" + "<condition data=\"Klar\"/></forecast_conditions><forecast_conditions><day_of_week data=\"Fr.\"/><low data=\"0\"/>" + "<high data=\"8\"/><icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/></forecast_conditions>" + "</weather></xml_api_reply>"; }
innoq/smarthome
bundles/core/org.eclipse.smarthome.core.transform.test/src/test/java/org/eclipse/smarthome/core/transform/internal/AbstractTransformationServiceTest.java
Java
epl-1.0
2,058
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.9-03/31/2009 04:14 PM(snajper)-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.07.19 at 07:21:12 PM EDT // package seg.jUCMNav.importexport.z151.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Description complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Description"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Description", propOrder = { "description" }) public class Description { @XmlElement(required = true) protected String description; /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } }
McGill-DP-Group/seg.jUCMNav
src/seg/jUCMNav/importexport/z151/generated/Description.java
Java
epl-1.0
1,823
/****************************************************************************** * * Copyright 2014 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package android.app; import java.awt.Cursor; /** * Stub class. */ public class ProgressDialog extends AlertDialog { public ProgressDialog(Activity activty) { super(activty); } public void show() { this.activity.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } public void dismiss() { this.activity.frame.setCursor(Cursor.getDefaultCursor()); } public void setCancelable(boolean cancelable){ } }
BOTlibre/BOTlibre
swingdroid/source/android/app/ProgressDialog.java
Java
epl-1.0
1,233
/******************************************************************************* * Copyright (c) 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.wsoc; import java.io.UnsupportedEncodingException; import java.net.URI; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Extension; import javax.websocket.Extension.Parameter; import javax.websocket.server.ServerEndpointConfig; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.websphere.ras.annotation.Sensitive; import com.ibm.ws.common.internal.encoder.Base64Coder; import com.ibm.ws.wsoc.external.ExtensionExt; import com.ibm.ws.wsoc.external.HandshakeRequestExt; import com.ibm.ws.wsoc.external.HandshakeResponseExt; import com.ibm.ws.wsoc.external.ParameterExt; import com.ibm.ws.wsoc.util.Utils; /* example of request and response GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Server responds like this: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= */ public class HandshakeProcessor { private static final TraceComponent tc = Tr.register(HandshakeProcessor.class); private String headerHost = null; private String headerUpgrade = null; private String headerConnection = null; private String headerSecWebSocketKey = null; private String headerOrigin = null; private String headerSecWebSocketProtocol = null; private String headerSecWebSocketVersion = null; private String[] clientSubProtocols = null; private List<Extension> clientExtensions = null; private List<Extension> configuredExtensions = null; private final static String subProtocolDelimiter = ","; // stuff used for populating the HandshakeRequest object for (user) configurator modification private final Map<String, List<String>> requestHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); private final Map<String, List<String>> parameterMap = new HashMap<String, List<String>>(); private URI requestURI = null; private HttpServletResponse httpResponse = null; private HttpServletRequest httpRequest = null; private Map<String, String> extraParamMap = null; private ServerEndpointConfig endpointConfig = null; private ServerEndpointConfig.Configurator endpointConfigurator = null; private final ParametersOfInterest things = new ParametersOfInterest(); public HandshakeProcessor() {} public void initialize(HttpServletRequest _hsr, HttpServletResponse resp, Map<String, String> extraParams) { httpRequest = _hsr; httpResponse = resp; extraParamMap = extraParams; } public void addWsocConfigurationData(ServerEndpointConfig _config, ServerEndpointConfig.Configurator _configurator) { endpointConfig = _config; endpointConfigurator = _configurator; } public ParametersOfInterest getParametersOfInterest() { return things; } public void readRequestInfo() throws Exception { Enumeration<String> names = httpRequest.getHeaderNames(); Map<String, String[]> paramMap = httpRequest.getParameterMap(); for (Map.Entry<String, String[]> entry : paramMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); List<String> list = Arrays.asList(value); parameterMap.put(key, list); } if (extraParamMap != null) { for (String key : extraParamMap.keySet()) { parameterMap.put(key, Arrays.asList(extraParamMap.get(key))); } } requestURI = new URI(httpRequest.getRequestURI()); things.setParameterMap(parameterMap); things.setQueryString(httpRequest.getQueryString()); things.setURI(requestURI); things.setUserPrincipal(httpRequest.getUserPrincipal()); boolean secure = httpRequest.isSecure(); if (!secure) { String s = httpRequest.getAuthType(); if ((s != null) && (s.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH))) { secure = true; } } things.setSecure(secure); things.setHttpSession(httpRequest.getSession()); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> headerValues = httpRequest.getHeaders(name); List<String> list = Collections.list(headerValues); requestHeaders.put(name, list); String headerValue = httpRequest.getHeader(name); String compName = name.trim(); if (compName.compareToIgnoreCase(Constants.HEADER_NAME_HOST) == 0) { headerHost = headerValue; if (tc.isDebugEnabled()) { Tr.debug(tc, "host header has a value of: " + headerHost); } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_UPGRADE) == 0) { headerUpgrade = headerValue; if (tc.isDebugEnabled()) { Tr.debug(tc, "upgrade header has a value of: " + headerUpgrade); } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_CONNECTION) == 0) { headerConnection = headerValue; if (tc.isDebugEnabled()) { Tr.debug(tc, "connection header has a value of: " + headerConnection); } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_SEC_WEBSOCKET_KEY) == 0) { headerSecWebSocketKey = headerValue; if (headerSecWebSocketKey != null) { headerSecWebSocketKey = headerSecWebSocketKey.trim(); } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_ORIGIN) == 0) { headerOrigin = headerValue; if (tc.isDebugEnabled()) { Tr.debug(tc, "Origin header has a value of: " + headerOrigin); } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_SEC_WEBSOCKET_PROTOCOL) == 0) { for (String val : list) { if (headerSecWebSocketProtocol == null) { headerSecWebSocketProtocol = val; } else { headerSecWebSocketProtocol = headerSecWebSocketProtocol + subProtocolDelimiter + val; } } // parse into array for later comparisons if ((headerSecWebSocketProtocol != null) && (headerSecWebSocketProtocol.length() > 0)) { clientSubProtocols = headerSecWebSocketProtocol.split(subProtocolDelimiter); // trim out the white spaces int len = clientSubProtocols.length; for (int i = 0; i < len; i++) { clientSubProtocols[i] = clientSubProtocols[i].trim(); } } } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_SEC_WEBSOCKET_EXTENSIONS) == 0) { clientExtensions = parseClientExtensions(list); } else if (compName.compareToIgnoreCase(Constants.HEADER_NAME_SEC_WEBSOCKET_VERSION) == 0) { headerSecWebSocketVersion = headerValue; if (tc.isDebugEnabled()) { Tr.debug(tc, "WebSocketVersion header has a value of: " + headerSecWebSocketVersion); } things.setWsocProtocolVersion(headerSecWebSocketVersion); } } } public void addResponseHeaders() { // set the following headers in the HTTP Response object // upgrade, connection, Sec-WebSocket-Accept String accept; httpResponse.setHeader(Constants.HEADER_NAME_UPGRADE, Constants.HEADER_VALUE_WEBSOCKET); httpResponse.setHeader(Constants.HEADER_NAME_CONNECTION, Constants.HEADER_VALUE_UPGRADE); accept = this.makeAcceptResponseHeaderValue(); httpResponse.setHeader(Constants.MC_HEADER_NAME_SEC_WEBSOCKET_ACCEPT, accept); } public boolean checkOrigin() { return endpointConfigurator.checkOrigin(headerOrigin); } public void modifyHandshake(Endpoint _ep, EndpointConfig _epc) { Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); Collection<String> names = httpResponse.getHeaderNames(); Iterator<String> it = names.iterator(); while (it.hasNext()) { String name = it.next(); Collection<String> headerValues = httpResponse.getHeaders(name); List<String> list = new ArrayList<String>(headerValues); responseHeaders.put(name, list); } // create handshake request object to give to modifier HandshakeRequestExt handshakeRequest = new HandshakeRequestExt(httpRequest, requestHeaders, parameterMap, requestURI, _ep, _epc); // create handshake response object to give to modifier HandshakeResponseExt handshakeResponse = new HandshakeResponseExt(responseHeaders); endpointConfigurator.modifyHandshake(endpointConfig, handshakeRequest, handshakeResponse); Map<String, List<String>> hdrs = handshakeResponse.getHeaders(); // We can add new headers, or overwrite existing, but we cannot remove.... // Iterator<String> i = hdrs.keySet().iterator(); Iterator<Entry<String, List<String>>> i = hdrs.entrySet().iterator(); while (i.hasNext()) { Entry<String, List<String>> entry = i.next(); List<String> list = entry.getValue(); if (list == null) { httpResponse.setHeader(entry.getKey(), ""); continue; } if (list.size() == 0) { httpResponse.setHeader(entry.getKey(), ""); } for (int x = 0; x < list.size(); x++) { if (x == 0) { httpResponse.setHeader(entry.getKey(), list.get(x)); } else { httpResponse.addHeader(entry.getKey(), list.get(x)); } } } } public void determineAndSetSubProtocol() { // the agree sub protocol is the first one in the local list the matches any of the ones in the client list. List<String> localSubProtocolList = endpointConfig.getSubprotocols(); if (localSubProtocolList == null) { localSubProtocolList = Collections.emptyList(); } List<String> clientProtocols = null; if (clientSubProtocols == null) { clientProtocols = Collections.emptyList(); } else { clientProtocols = Arrays.asList(clientSubProtocols); } String agreedSubProtocol = endpointConfigurator.getNegotiatedSubprotocol(localSubProtocolList, clientProtocols); things.setAgreedSubProtocol(agreedSubProtocol); things.setLocalSubProtocols(localSubProtocolList); if ((!"".equals(agreedSubProtocol)) && (agreedSubProtocol != null)) { httpResponse.setHeader(Constants.HEADER_NAME_SEC_WEBSOCKET_PROTOCOL, agreedSubProtocol); } } public void determineAndSetExtensions() { // Even though we have no built in extensions, we will read the ServerEndpoingConfig to see what they configure // COudl be an extension that looks at headers... configuredExtensions = endpointConfig.getExtensions(); if (configuredExtensions == null) { configuredExtensions = Collections.emptyList(); } if (clientExtensions == null) { clientExtensions = Collections.emptyList(); } List<Extension> agreedExtensions = endpointConfigurator.getNegotiatedExtensions(configuredExtensions, clientExtensions); if (agreedExtensions != null) { if (agreedExtensions.size() > 0) { StringBuffer buf = new StringBuffer(); boolean first = true; for (Extension ext : agreedExtensions) { if (first) { first = false; } else { buf.append(", "); } buf.append(ext.getName()); List<Parameter> li = ext.getParameters(); if (li != null) { if (li.size() > 0) { for (Parameter p : li) { buf.append("; " + p.getName() + "=" + p.getValue()); } } } } things.setNegotiatedExtensions(agreedExtensions); httpResponse.setHeader(Constants.HEADER_NAME_SEC_WEBSOCKET_EXTENSIONS, buf.toString()); } } } public void verifyHeaders() throws Exception { // Require HTTP/1.1 or above... String protocol = httpRequest.getProtocol(); String[] args = protocol.split("/"); if (args.length < 2) { throw new Exception("Websocket request processed, but no HTTP Protocol version was provided.."); } else { float version = Float.valueOf(args[1]); if (version < 1.1) { throw new Exception("Websocket request processed, provided HTTP Protocol level \"" + protocol + "\"provided but WebSocket support requires HTTP/1.1 or above."); } } // Must have host header.. if (headerHost == null) { throw new Exception("Websocket request processing found no Host header."); } // Must have Upgrade header equal to websocket if ((headerUpgrade == null) || (!Constants.HEADER_VALUE_WEBSOCKET.equalsIgnoreCase(headerUpgrade))) { throw new Exception("Websocket request processed but provided upgrade header \"" + headerUpgrade + "\" does not match " + Constants.HEADER_VALUE_WEBSOCKET + "."); } //Must have Connection:Upgrade header if (headerConnection != null) { boolean found = false; String[] connection = headerConnection.split(","); for (String conn : connection) { if (conn.trim().equalsIgnoreCase(Constants.HEADER_VALUE_UPGRADE)) { found = true; } } if (!found) { throw new Exception("Websocket request processed but provided connection header \"" + headerConnection + "\" does not match " + Constants.HEADER_VALUE_UPGRADE + "."); } } else { throw new Exception("Websocket request processed but provided connection header \"" + headerConnection + "\" does not match " + Constants.HEADER_VALUE_UPGRADE + "."); } // Version must equal 13... better logic will be provided once we support more than one version int supportedVersion = Integer.valueOf(Constants.HEADER_VALUE_FOR_SEC_WEBSOCKET_VERSION); if (headerSecWebSocketVersion == null) { httpResponse.setIntHeader(Constants.HEADER_NAME_SEC_WEBSOCKET_VERSION, supportedVersion); throw new Exception("Websocket request processed, but no websocket version provided."); } else { try { int version = Integer.parseInt(headerSecWebSocketVersion); if (version != supportedVersion) { httpResponse.setIntHeader(Constants.HEADER_NAME_SEC_WEBSOCKET_VERSION, supportedVersion); throw new Exception("Websocket request processed, but Version header of \"" + headerSecWebSocketVersion + "\" is not a match for supported version " + supportedVersion + "."); } } catch (NumberFormatException nfe) { httpResponse.setIntHeader(Constants.HEADER_NAME_SEC_WEBSOCKET_VERSION, supportedVersion); throw new Exception("Websocket request processed, but version header of \"" + headerSecWebSocketVersion + "\" is not valid number.", nfe); } } // Check for blank or null accept key if (("".equals(headerSecWebSocketKey)) || (headerSecWebSocketKey == null)) { throw new Exception("Websocket request processed, but Sec-WebSocket-Key is blank or null"); } byte[] decodedBytes = Base64Coder.base64DecodeString(headerSecWebSocketKey); if (decodedBytes == null) { throw new Exception("Websocket request processed, but client sent Sec-WebSocket-Key that has not been base64 encoded."); } if (decodedBytes.length != 16) { throw new Exception("Websocket request processed, but client sent Sec-WebSocket-Key that is not 16 bytes"); } } @Sensitive private String makeAcceptResponseHeaderValue() { String acceptKey = ""; try { acceptKey = Utils.makeAcceptResponseHeaderValue(headerSecWebSocketKey); } catch (NoSuchAlgorithmException e) { // allow instrumented FFDC to be used here } catch (UnsupportedEncodingException e) { // allow instrumented FFDC to be used here } return acceptKey; } public static List<Extension> parseClientExtensions(List<String> list) { List<Extension> extensions = new ArrayList<Extension>(10); String headerSecWebSocketExtensions = null; for (String val : list) { if (headerSecWebSocketExtensions == null) { headerSecWebSocketExtensions = val; } else { headerSecWebSocketExtensions = headerSecWebSocketExtensions + subProtocolDelimiter + val; } } if ((headerSecWebSocketExtensions != null) && (headerSecWebSocketExtensions.length() > 0)) { String[] extArr = headerSecWebSocketExtensions.split(subProtocolDelimiter); for (int i = 0; i < extArr.length; i++) { String[] parameters = extArr[i].trim().split(";"); String extName = parameters[0]; List<Extension.Parameter> paramList = new ArrayList<Extension.Parameter>(parameters.length - 1); if (parameters.length > 1) { for (int z = 1; z < parameters.length; z++) { String[] namevals = parameters[z].trim().split("="); String val = ""; if (namevals.length > 1) { val = namevals[1]; } paramList.add(new ParameterExt(namevals[0], val)); } } extensions.add(new ExtensionExt(extName, paramList)); } } return extensions; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.wsoc/src/com/ibm/ws/wsoc/HandshakeProcessor.java
Java
epl-1.0
20,135
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxws.test.wsr.client; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.ws.BindingProvider; import com.ibm.websphere.simplicity.RemoteFile; import componenttest.topology.impl.LibertyServer; import componenttest.topology.utils.HttpUtils; public class TestUtils { /* * This method is to work around the issue of the hard-coded address and port value which specified in the wsdl file. * A servlet could use this util to reset the EndpointAddress with the correct addr and value of a test server. * In future, if the we support vendor plan, we could specify the values there. */ public static void setEndpointAddressProperty(BindingProvider bp, String serverAddr, int serverPort) throws IOException { String endpointAddr = bp.getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString(); URL endpointUrl = new URL(endpointAddr); String newEndpointAddr = endpointUrl.getProtocol() + "://" + serverAddr + ":" + serverPort + endpointUrl.getPath(); bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, newEndpointAddr); } /** * Validate the XML attributes * * @param is * @param attributeParams The Map.Entry key likes "targetNamespace=http://com.ibm/jaxws/testmerge/replace/", value likes "{http://schemas.xmlsoap.org/wsdl/}definitions" * @return * @throws XMLStreamException * @throws FactoryConfigurationError */ public static Map<String, QName> validateXMLAttributes(InputStream is, Map<String, QName> attributeParams) throws XMLStreamException, FactoryConfigurationError { XMLStreamReader reader = null; try { reader = XMLInputFactory.newInstance().createXMLStreamReader(is); while (reader.hasNext()) { int event = reader.next(); if (XMLStreamConstants.START_ELEMENT == event) { Iterator<Map.Entry<String, QName>> iter = attributeParams.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, QName> entry = iter.next(); String[] keyValuePair = entry.getKey().split("="); QName elementQName = entry.getValue(); if (reader.getLocalName().equals(elementQName.getLocalPart()) && reader.getNamespaceURI().equals(elementQName.getNamespaceURI()) && compareAttribute(reader, keyValuePair[0], keyValuePair[1])) { iter.remove(); } } if (attributeParams.isEmpty()) { break; } } } } finally { if (reader != null) { reader.close(); } } return attributeParams; } private static boolean compareAttribute(XMLStreamReader reader, String attrName, String attrValue) { int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { String name = reader.getAttributeLocalName(i); String value = reader.getAttributeValue(i); if (name.equals(attrName) && value.equals(attrValue)) { return true; } } return false; } /** * Copy the file to server, rename if the targetFileName is not equal to srcFileName. * * @param server, the LibertyServer * @param srcPathFromPubishFolder, the folder path relative to publish folder * @param srcFileName, the source file name to copy * @param targetPathFromServerRoot, the target path relative to server root * @param targetFileName, the target file name * @throws Exception */ public static void publishFileToServer(LibertyServer server, String srcPathFromPubishFolder, String srcFileName, String targetPathFromServerRoot, String targetFileName) throws Exception { server.copyFileToLibertyServerRoot(targetPathFromServerRoot, srcPathFromPubishFolder + "/" + srcFileName); if (targetFileName != null && !targetFileName.isEmpty() && !targetFileName.equals(srcFileName)) { server.renameLibertyServerRootFile(targetPathFromServerRoot + "/" + srcFileName, targetPathFromServerRoot + "/" + targetFileName); } } /** * Replace the string in a server file. * * @param server, the LibertyServer * @param filePathFromServerRoot, the file path relative to server root * @param fromStr, the string that need replace in the file. * @param toStr, the string to replace the original one. * @throws Exception */ public static void replaceServerFileString(LibertyServer server, String filePathFromServerRoot, String fromStr, String toStr) throws Exception { InputStream is = null; OutputStream os = null; try { RemoteFile serverFile = server.getFileFromLibertyServerRoot(filePathFromServerRoot); is = serverFile.openForReading(); StringBuilder builder = new StringBuilder(); //read InputStreamReader isr = new InputStreamReader(is); BufferedReader bfin = new BufferedReader(isr); String rLine = ""; while ((rLine = bfin.readLine()) != null) { builder.append(rLine); } is.close(); //replace String xmiText = builder.toString(); String updatedText = xmiText.replaceAll(fromStr, toStr); //write os = serverFile.openForWriting(false); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(updatedText); writer.close(); } catch (Exception e) { throw e; } finally { if (is != null) { try { is.close(); } catch (IOException e) { //ignore; } } if (os != null) { try { os.close(); } catch (IOException e) { //ignore; } } } } public static String getServletResponse(String servletUrl) throws Exception { URL url = new URL(servletUrl); HttpURLConnection con = HttpUtils.getHttpConnection(url, HttpURLConnection.HTTP_OK, 10); BufferedReader br = HttpUtils.getConnectionStream(con); String result = br.readLine(); String line; while ((line = br.readLine()) != null) { result += line; } return result; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.clientcontainer_fat/fat/src/com/ibm/ws/jaxws/test/wsr/client/TestUtils.java
Java
epl-1.0
7,976
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.query.web.loopqueryano; import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.servlet.annotation.WebServlet; import org.junit.Test; import com.ibm.ws.query.testlogic.JULoopQueryAnoTest; import com.ibm.ws.query.utils.SetupQueryTestCase; import com.ibm.ws.testtooling.testinfo.JPAPersistenceContext; import com.ibm.ws.testtooling.testinfo.JPAPersistenceContext.PersistenceContextType; import com.ibm.ws.testtooling.testinfo.JPAPersistenceContext.PersistenceInjectionType; import com.ibm.ws.testtooling.vehicle.web.JPATestServlet; @SuppressWarnings("serial") @WebServlet(urlPatterns = "/JULoopQueryAnoTest_001_Servlet") public class JULoopQueryAnoTest_001_Servlet extends JPATestServlet { // Application Managed JTA @PersistenceUnit(unitName = "QUERY_JTA") private EntityManagerFactory amjtaEmf; private SetupQueryTestCase setup = null; @PostConstruct private void initFAT() { testClassName = JULoopQueryAnoTest.class.getName(); jpaPctxMap.put("test-jpa-resource-amjta", new JPAPersistenceContext("test-jpa-resource-amjta", PersistenceContextType.APPLICATION_MANAGED_JTA, PersistenceInjectionType.FIELD, "amjtaEmf")); jpaPctxMap.put("test-jpa-resource-amrl", new JPAPersistenceContext("test-jpa-resource-amrl", PersistenceContextType.APPLICATION_MANAGED_RL, PersistenceInjectionType.FIELD, "amrlEmf")); jpaPctxMap.put("test-jpa-resource-cmts", new JPAPersistenceContext("test-jpa-resource-cmts", PersistenceContextType.CONTAINER_MANAGED_TS, PersistenceInjectionType.FIELD, "cmtsEm")); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test001_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test001_AMJTA_Web"; final String testMethod = "testLoop001"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test002_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test002_AMJTA_Web"; final String testMethod = "testLoop002"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test003_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test003_AMJTA_Web"; final String testMethod = "testLoop003"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test004_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test004_AMJTA_Web"; final String testMethod = "testLoop004"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test005_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test005_AMJTA_Web"; final String testMethod = "testLoop005"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test006_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test006_AMJTA_Web"; final String testMethod = "testLoop006"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test007_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test007_AMJTA_Web"; final String testMethod = "testLoop007"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test008_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test008_AMJTA_Web"; final String testMethod = "testLoop008"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test009_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test009_AMJTA_Web"; final String testMethod = "testLoop009"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test010_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test010_AMJTA_Web"; final String testMethod = "testLoop010"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test011_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test011_AMJTA_Web"; final String testMethod = "testLoop011"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test012_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test012_AMJTA_Web"; final String testMethod = "testLoop012"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test013_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test013_AMJTA_Web"; final String testMethod = "testLoop013"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test014_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test014_AMJTA_Web"; final String testMethod = "testLoop014"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test015_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test015_AMJTA_Web"; final String testMethod = "testLoop015"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test016_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test016_AMJTA_Web"; final String testMethod = "testLoop016"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test017_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test017_AMJTA_Web"; final String testMethod = "testLoop017"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test018_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test018_AMJTA_Web"; final String testMethod = "testLoop018"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } // TODO: Fails, review failure // @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test019_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test019_AMJTA_Web"; final String testMethod = "testLoop019"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test020_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test020_AMJTA_Web"; final String testMethod = "testLoop020"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test021_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test021_AMJTA_Web"; final String testMethod = "testLoop021"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test022_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test022_AMJTA_Web"; final String testMethod = "testLoop022"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test023_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test023_AMJTA_Web"; final String testMethod = "testLoop023"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test024_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test024_AMJTA_Web"; final String testMethod = "testLoop024"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } @Test public void jpa_spec10_query_svlquery_juloopquery_ano_test025_AMJTA_Web() throws Exception { final String testName = "jpa_spec10_query_svlquery_juloopquery_ano_test025_AMJTA_Web"; final String testMethod = "testLoop025"; final String testResource = "test-jpa-resource-amjta"; executeTest(testName, testMethod, testResource); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.tests.spec10.query_fat.common/test-applications/svlquery/src/com/ibm/ws/query/web/loopqueryano/JULoopQueryAnoTest_001_Servlet.java
Java
epl-1.0
11,753
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.java.client.action; import com.google.gwtmockito.GwtMockitoTestRunner; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.Promise; import org.eclipse.che.api.promises.client.PromiseError; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.action.Presentation; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.app.CurrentProject; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.selection.Selection; import org.eclipse.che.ide.ext.java.client.JavaLocalizationConstant; import org.eclipse.che.ide.ext.java.client.JavaResources; import org.eclipse.che.ide.ext.java.client.project.classpath.ClasspathResolver; import org.eclipse.che.ide.ext.java.client.project.classpath.service.ClasspathServiceClient; import org.eclipse.che.ide.ext.java.client.project.node.PackageNode; import org.eclipse.che.ide.ext.java.client.project.node.SourceFolderNode; import org.eclipse.che.ide.ext.java.shared.dto.classpath.ClasspathEntryDto; import org.eclipse.che.ide.part.explorer.project.ProjectExplorerPresenter; import org.eclipse.che.ide.project.node.FolderReferenceNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.EMERGE_MODE; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test for {@link MarkDirAsSourceAction} * * @author Valeriy Svydenko */ @RunWith(GwtMockitoTestRunner.class) public class MarkDirAsSourceActionTest { final private static String PROJECT_PATH = "/projects/path"; final private static String TEXT = "to be or not to be"; @Mock private JavaResources javaResources; @Mock private AppContext appContext; @Mock private ClasspathServiceClient classpathService; @Mock private ClasspathResolver classpathResolver; @Mock private NotificationManager notificationManager; @Mock private ProjectExplorerPresenter projectExplorerPresenter; @Mock private JavaLocalizationConstant locale; @Mock private CurrentProject currentProject; @Mock private ProjectConfigDto projectConfigDto; @Mock private ActionEvent actionEvent; @Mock private Presentation presentation; @Mock private Selection selection; @Mock private FolderReferenceNode folderReferenceNode; @Mock private Promise<List<ClasspathEntryDto>> classpathPromise; @Mock private PromiseError promiseError; @Captor private ArgumentCaptor<Operation<List<ClasspathEntryDto>>> classpathCapture; @Captor private ArgumentCaptor<Operation<PromiseError>> classpathErrorCapture; @InjectMocks private MarkDirAsSourceAction action; @Before public void setUp() throws Exception { when(appContext.getCurrentProject()).thenReturn(currentProject); when(currentProject.getProjectConfig()).thenReturn(projectConfigDto); when(projectConfigDto.getPath()).thenReturn(PROJECT_PATH); when(projectExplorerPresenter.getSelection()).thenReturn(selection); when(selection.getHeadElement()).thenReturn(folderReferenceNode); when(actionEvent.getPresentation()).thenReturn(presentation); FolderReferenceNode folder = mock(FolderReferenceNode.class); when(selection.getHeadElement()).thenReturn(folder); when(classpathService.getClasspath(anyString())).thenReturn(classpathPromise); when(classpathPromise.then(Matchers.<Operation<List<ClasspathEntryDto>>>anyObject())).thenReturn(classpathPromise); } @Test public void titleAndDescriptionShouldBeSet() throws Exception { verify(locale).markDirectoryAsSourceAction(); verify(locale).markDirectoryAsSourceDescription(); } @Test public void actionShouldBePerformed() throws Exception { List<ClasspathEntryDto> classpathEntries = new ArrayList<>(); Set<String> sources = new HashSet<>(); when(folderReferenceNode.getStorablePath()).thenReturn(TEXT); when(classpathResolver.getSources()).thenReturn(sources); action.actionPerformed(actionEvent); verify(classpathService.getClasspath(PROJECT_PATH)).then(classpathCapture.capture()); classpathCapture.getValue().apply(classpathEntries); verify(classpathResolver).resolveClasspathEntries(classpathEntries); verify(classpathResolver).getSources(); Assert.assertEquals(1, sources.size()); verify(classpathResolver).updateClasspath(); } @Test public void readingClasspathFailed() throws Exception { action.actionPerformed(actionEvent); when(promiseError.getMessage()).thenReturn(TEXT); verify(classpathService.getClasspath(PROJECT_PATH)).catchError(classpathErrorCapture.capture()); classpathErrorCapture.getValue().apply(promiseError); verify(notificationManager).notify("Can't get classpath", TEXT, FAIL, EMERGE_MODE); } @Test public void actionShouldBeHideIfSelectedNodeIsSource() throws Exception { SourceFolderNode sourceFolder = mock(SourceFolderNode.class); when(selection.getHeadElement()).thenReturn(sourceFolder); action.updateInPerspective(actionEvent); verify(presentation).setVisible(false); verify(presentation).setEnabled(anyBoolean()); } @Test public void actionShouldBeVisibleIfSelectedNodeIsNotSource() throws Exception { action.updateInPerspective(actionEvent); verify(presentation).setVisible(true); verify(presentation).setEnabled(anyBoolean()); } @Test public void actionShouldBeDisableIfSelectionIsMultiple() throws Exception { when(selection.isSingleSelection()).thenReturn(false); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } @Test public void actionShouldBeDisableIfSelectedNodeIsPackage() throws Exception { PackageNode packageNode = mock(PackageNode.class); when(selection.getHeadElement()).thenReturn(packageNode); when(selection.isSingleSelection()).thenReturn(true); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } @Test public void actionShouldBeDisableIfSelectedNodeIsNotFolder() throws Exception { Object someNode = mock(Object.class); when(selection.getHeadElement()).thenReturn(someNode); when(selection.isSingleSelection()).thenReturn(true); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } }
stour/che
plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/action/MarkDirAsSourceActionTest.java
Java
epl-1.0
8,195